mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-11-27 06:32:42 +00:00
Compare commits
135
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f58faaa0d | ||
|
|
e9305f3501 | ||
|
|
052dfe3c12 | ||
|
|
59f655ed46 | ||
|
|
1f20425f3d | ||
|
|
06647f8ea3 | ||
|
|
5127f78def | ||
|
|
7f136e0618 | ||
|
|
e079827dd3 | ||
|
|
d848084b59 | ||
|
|
5bbf266455 | ||
|
|
fc4f91339f | ||
|
|
1ae56692aa | ||
|
|
d1f87855e4 | ||
|
|
04eee5f373 | ||
|
|
c121056558 | ||
|
|
cd1d243ac5 | ||
|
|
0214eaed59 | ||
|
|
0245964a04 | ||
|
|
a2263bc253 | ||
|
|
a932f10e90 | ||
|
|
da124f019b | ||
|
|
6f1f277ed9 | ||
|
|
d7dd08fad6 | ||
|
|
355d7c2d46 | ||
|
|
b9d12c09e3 | ||
|
|
7a1a0d75ee | ||
|
|
263c09d07b | ||
|
|
39346559ce | ||
|
|
e4e9df0a49 | ||
|
|
149e1e5bf0 | ||
|
|
0da7120a7d | ||
|
|
d94b3b19ad | ||
|
|
169ceb3cf3 | ||
|
|
ded91c6882 | ||
|
|
4ce81be081 | ||
|
|
740ee455d3 | ||
|
|
81fbbf42b7 | ||
|
|
ba6c45d621 | ||
|
|
1c76170bad | ||
|
|
4d60ce9263 | ||
|
|
d513935523 | ||
|
|
01fcb09f83 | ||
|
|
57240da793 | ||
|
|
91e78ec1ae | ||
|
|
648a2a8ed8 | ||
|
|
83c8493c02 | ||
|
|
67352c9952 | ||
|
|
b4170ac68c | ||
|
|
767cacbcdc | ||
|
|
b708883e13 | ||
|
|
ded19ad510 | ||
|
|
3579dbf245 | ||
|
|
8a0714104a | ||
|
|
61817b01c6 | ||
|
|
d3e7182ff2 | ||
|
|
6a50ccd271 | ||
|
|
f4ff25f308 | ||
|
|
df95e5f2b0 | ||
|
|
b6e98a8231 | ||
|
|
48a35c7982 | ||
|
|
13652c2832 | ||
|
|
02a4f37e32 | ||
|
|
1ce6198c39 | ||
|
|
0fdc689b3b | ||
|
|
21bcb6be91 | ||
|
|
ed960eb909 | ||
|
|
5a0419d8f7 | ||
|
|
b429e41f62 | ||
|
|
8bfcd23b77 | ||
|
|
74429eb4eb | ||
|
|
9f182616a5 | ||
|
|
148318ec21 | ||
|
|
0caa6b7d90 | ||
|
|
dd30833789 | ||
|
|
f82f4cf5eb | ||
|
|
3f8a04d893 | ||
|
|
f6525d72f8 | ||
|
|
eeffa5749b | ||
|
|
36a32940ba | ||
|
|
6d344ee3d7 | ||
|
|
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 | ||
|
|
19a694260d |
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
|
||||
|
||||
@@ -81,10 +73,14 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
|
||||
|
||||
- Prefer Obsidian's established classes such as `mod-warning` before adding plugin-specific CSS. Consult the Obsidian CSS variables and component conventions when styling settings or dialogs.
|
||||
- Never use `document.createElement()`, `Document.createElement()`, or `Document.createDocumentFragment()`. Always use Obsidian's `createEl()`, `createDiv()`, `createSpan()`, `createSvg()`, and `createFragment()` helpers. When an element must deliberately belong to a specific document that Obsidian's helpers cannot target, such as a canvas used for drawing or an element inside an iframe, use the `deliberateCreateElement` function injected by `rollup.config.mjs` and declare it in the consuming module, for example `declare const deliberateCreateElement: (document: Document, tagName: string) => HTMLElement;`.
|
||||
- Use semantic interactive elements and Obsidian's event helpers. Link-like navigation should use a real anchor, not a button merely styled as a link; use `onClickEvent` when applying custom navigation behavior. Validate touch interactions on a physical mobile device because desktop mobile emulation proves layout, not native touch activation.
|
||||
- When a control already has a styled tooltip, do not also set an HTML `title` attribute. Keep its accessible name in `aria-label`; `title` produces a second native Chromium/Electron tooltip and must not replace accessible labeling.
|
||||
- Do not write an element's `style` attribute directly. Use `setStyle` and `removeStyle` from `src/utils/styleUtils.ts` when a dynamic inline style is genuinely necessary.
|
||||
- Use the existing visibility helpers instead of the native `hidden` property or attribute, which is not reliable in Obsidian's styled UI. Choose `hideElement`/`showElement` or `setComponentVisibility` from `src/utils/styleUtils.ts`, or `setElementHidden`/`setElementDisplay` from `src/utils/htmlUtils.ts` when a boolean/display-oriented API is clearer.
|
||||
- Search `src/utils/styleUtils.ts` and `src/utils/htmlUtils.ts` before introducing new DOM styling helpers or display classes.
|
||||
- Run Obsidian CodeScanner after CSS changes. Preserve compatibility with the declared minimum Obsidian version and prefer a widely supported property when it provides the same result; for example, a basic underline is preferable to optional underline-thickness/offset styling.
|
||||
- For a known vault path, use the most specific synchronous lookup: `app.vault.getFolderByPath()` for folders and `app.vault.getFileByPath()` for files. Use `getAbstractFileByPath()` only when either type is intentionally accepted, and avoid adapter-level existence checks when the Vault API already models the target.
|
||||
- Radix content in the customized Excalidraw package may be rendered through `ObsidianRadixPortal` directly under the owning document's body. A body portal escapes component ancestor selectors and modal stacking contexts. When a trigger is visible but its menu or popover is not, first inspect whether the content mounted behind a modal or lost ancestor-scoped styles. Use a class on the portaled content, a portal-safe selector, and an explicit stacking level when required; validate main-window, popout, click-outside, and Escape behavior.
|
||||
|
||||
## Performance
|
||||
|
||||
@@ -92,6 +88,16 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
|
||||
- Avoid long-running tasks during `onload`; use lazy initialization.
|
||||
- Batch disk access and avoid excessive vault scans.
|
||||
- Debounce/throttle expensive operations in response to file system events.
|
||||
- For temporary performance diagnostics, use a unique searchable prefix and
|
||||
emit one copyable string per event rather than logging expandable objects.
|
||||
Keep timing-only callbacks and state isolated from production behavior.
|
||||
- Distinguish synchronous API duration, queue completion, browser-task yields,
|
||||
animation-frame callbacks, and actual paint; none is a substitute for the
|
||||
others when explaining perceived latency.
|
||||
- Temporary diagnostics are not product observability. Do not log vault
|
||||
contents, and include filenames only when the maintainer explicitly needs
|
||||
per-file attribution. Remove the diagnostics before commit and search both
|
||||
`src/` and the built `dist/main.js` for their prefix.
|
||||
|
||||
## Coding conventions
|
||||
|
||||
@@ -108,6 +114,7 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
|
||||
- Don't assume desktop-only behavior unless `isDesktopOnly` is `true`.
|
||||
- Avoid using desktop only objects and functions such as Node Buffer, SharedArrayBuffer, etc. For the special case when this is required, make proper mobile safe guards.
|
||||
- Avoid large in-memory structures; be mindful of memory and storage constraints.
|
||||
- Treat a physical phone or tablet as a separate validation environment for touch targets, synthesized clicks, scrolling gestures, focus, and the mobile WebView. Desktop mobile emulation is useful for responsive layout checks but is not a substitute for real touch testing.
|
||||
|
||||
## Agent do/don't
|
||||
|
||||
@@ -191,20 +198,97 @@ 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
|
||||
- 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, ReactDOM, and the official JSX runtime entry points are normal modules in the main Rollup bundle, not separately compressed or evaluated payloads. React must remain external to the separately built Excalidraw artifact: the plugin supplies its one bundled private React runtime to the single evaluated Excalidraw runtime used by every view. Mermaid is also intentionally absent from the artifact and is loaded lazily at runtime through Excalidraw Extras. All other required Excalidraw assets are expected to work offline except the deliberately lazy CJK font subsets.
|
||||
|
||||
### Two-Repository Excalidraw Workflow
|
||||
|
||||
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.
|
||||
- A local artifact copy proves integration only. If plugin source consumes a
|
||||
new fork API, do not describe the plugin handoff as commit- or release-ready
|
||||
until the published package is installed and the exact dependency and
|
||||
lockfile contain that API, unless the maintainer explicitly requests a
|
||||
paired intermediate commit.
|
||||
- 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 with the shared Excalidraw runtime. React components and individual `ExcalidrawView` instances must not configure or dispose them.
|
||||
- Adapter methods must read live plugin state instead of capturing settings snapshots during registration.
|
||||
- `PackageManager` owns the complete lifetime: dispose registrations before releasing the shared runtime, make cleanup idempotent, and roll back all registrations if configuring either adapter fails.
|
||||
|
||||
A closure that references the plugin is not itself a memory leak. The risk is allowing a registry, listener, or evaluated runtime retaining that closure to outlive its owning `PackageManager` registration.
|
||||
|
||||
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.
|
||||
- `src/core/managers/PackageManager.ts` combines the plugin bundle's one private React/ReactDOM runtime with one evaluated Excalidraw artifact in the main application realm and leases that package to every view.
|
||||
- A lease retains the view's actual acquisition window for migration and persistence decisions; package evaluation ownership must never substitute for that identity.
|
||||
- Popouts receive only a temporary `window.ExcalidrawLib` compatibility alias. Remove it after the final lease for that window while keeping the shared runtime alive until plugin unload.
|
||||
- React and ReactDOM are bundled normally from their official npm entry points and kept in plugin/package lexical scope. Do not restore a compressed/evaluated React bootstrap or assign React or ReactDOM to `window`; only the documented `window.ExcalidrawLib` compatibility surface remains global.
|
||||
- Every Excalidraw root must receive its stable owning document. Rendering, DOM ownership, events, observers, portals, realm constructors, fonts, timers, and React roots must derive from the owning view document/window where appropriate; do not turn the shared runtime into a mutable "current window" singleton.
|
||||
- Treat `HTMLElement.onWindowMigrated()` as a destructive runtime boundary. Its callback runs after Obsidian has moved the view container to another document, while the existing React root and Excalidraw API still belong to the source window runtime.
|
||||
- For a dirty migration, synchronously capture every API-owned value needed for persistence and unmount the source React root **before the first `await`**. Do not move synchronization, compression, Vault/native file access, `closeLeafView()`, or another asynchronous step ahead of that unmount. On macOS/Electron, doing so reproducibly allowed the source popout window to be destroyed before `root.unmount()`, freezing Obsidian and disconnecting DevTools.
|
||||
- Cancel deferred initialization and scene-file loaders before migration unmount, and require delayed loader callbacks to match the exact API instance and file path that started them. Component-owned image decoding can still outlive a synchronous `addFiles()` call, so the Excalidraw runtime must also stop after an awaited decode when its editor has unmounted; never delay migration unmount to wait for image work.
|
||||
- The migration callback owns the single persistence flush. Generic `onClose()` and `onUnloadFile()` safeguards must not start duplicate migration saves, and the retired source view must reject blur-save side effects and vault-modify synchronization after its API is unmounted.
|
||||
- A popout-to-main migration may serialize from a synchronously captured drawing snapshot, but the replacement main-window view must perform the final drawing-file write. Never initiate the final Vault/native write from the source popout callback.
|
||||
|
||||
### Main-Window Persistent Storage
|
||||
|
||||
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.
|
||||
|
||||
### IndexedDB And Cache Schema Changes
|
||||
|
||||
- Classify every affected store as disposable derived cache or durable user
|
||||
data before changing its schema. Image previews may be rebuilt; drawing
|
||||
backups must not be deleted as cache migration cleanup.
|
||||
- Create current stores and remove obsolete disposable stores in one IndexedDB
|
||||
version-change transaction. Prefer lazy cache rebuilding over deserializing
|
||||
and rewriting a large legacy cache during startup.
|
||||
- If opening or upgrading fails, close and clear unusable database handles and
|
||||
readiness promises. A closed legacy connection must never make the cache
|
||||
report itself as ready.
|
||||
- Use browser APIs such as `Blob` and `FileReader` for in-memory payload
|
||||
conversion so the path remains mobile-safe. Vault file access must still use
|
||||
Obsidian's Vault API.
|
||||
- Validate cold upgrade, preservation of durable stores, first cold rebuild,
|
||||
warm reopen, clear, timed purge, plugin reload, and one mobile run. Persistent
|
||||
plugin data remains owned by the main application window; popouts need a
|
||||
usage smoke test, not a separate database.
|
||||
|
||||
### MathJax Subproject
|
||||
|
||||
@@ -244,6 +328,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 +395,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
|
||||
|
||||
@@ -315,10 +410,10 @@ Backwards compatibility is a strong requirement in this repository.
|
||||
|
||||
## React Runtime Import Model
|
||||
|
||||
React usage in this repository is special because React and ReactDOM are package-managed per window to support Obsidian popout windows and runtime package injection.
|
||||
React usage in this repository is special because one normally bundled private React/ReactDOM runtime is package-managed across main-window and popout roots.
|
||||
|
||||
- It is fine to import React for types, component definitions, JSX compilation, and nearby established patterns.
|
||||
- Do not assume a single global React/ReactDOM runtime is safe for rendering, root creation, or view-owned objects.
|
||||
- Import React, ReactDOM, and JSX runtime entry points normally. Rollup must bundle them into the main plugin but keep them external in the library build and in the separately built Excalidraw artifact.
|
||||
- The shared runtime is safe only because each root and Excalidraw instance receives stable owner-document state. Never recover view ownership from the runtime's lexical main window.
|
||||
- For view-bound rendering and roots, follow `src/view/ExcalidrawView.ts` and use `view.packages.react` and `view.packages.reactDOM` through the package-manager flow.
|
||||
- For view-owned React objects such as refs or runtime-created elements, follow neighboring patterns such as `src/view/components/menu/ToolsPanel.tsx` and `src/view/components/CustomEmbeddable.tsx`, which intentionally use the package-managed React instance.
|
||||
- Do not introduce a new direct `ReactDOM.createRoot()` path outside the package-manager model unless you have verified popout-window safety.
|
||||
@@ -334,7 +429,7 @@ Use this routing guide before editing.
|
||||
- Commands and command registration: `src/core/managers/CommandManager.ts`
|
||||
- Vault or workspace event handling: `src/core/managers/EventManager.ts` and `src/core/managers/FileManager.ts`
|
||||
- Markdown rendering or markdown embeds: `src/core/managers/MarkdownPostProcessor.ts`
|
||||
- Package/runtime loading across windows: `src/core/managers/PackageManager.ts`
|
||||
- Shared package/runtime loading and per-window leases: `src/core/managers/PackageManager.ts`
|
||||
- Styling setup and style injection: `src/core/managers/StylesManager.ts`, `styles.css`, `src/utils/dynamicStyling.ts`
|
||||
- Main canvas/editor behavior: `src/view/ExcalidrawView.ts`
|
||||
- Sidepanel behavior: `src/view/sidepanel/`
|
||||
@@ -357,6 +452,21 @@ If a task changes persisted settings, inspect all relevant pieces.
|
||||
|
||||
Settings changes are often incomplete if only one of these surfaces is updated.
|
||||
|
||||
## Declarative Settings And Persistence
|
||||
|
||||
The plugin supports Obsidian 1.8.7 while optionally using the declarative settings API introduced in Obsidian 1.13. Preserve both compatibility paths.
|
||||
|
||||
- Do not bump the `obsidian` dependency or `minAppVersion` merely to consume declarative settings. Gate the runtime path with `requireApiVersion("1.13.0")` and keep conservative placeholder declarations for the newer API.
|
||||
- `getSettingDefinitions()` must return the complete tree only when the runtime supports declarative settings and the restart-applied compatibility preference enables them. Returning an empty array is the intentional fallback to the legacy renderer.
|
||||
- The settings page model is the canonical hierarchy for declarative rendering, legacy single-page rendering, descriptions, search aliases, breadcrumbs, cross-page navigation, and Markdown export. Do not create separate setting lists or behavior implementations for the two layouts.
|
||||
- Controls that change each other's options, visibility, or disabled state must share one integrated component or one shared configurator. Apply dependent state during initial render as well as after changes. Scope captured control references to one rendered definition tree; generating an export-only tree must never replace bindings used by the mounted UI.
|
||||
- On Obsidian 1.13+, do not call `display()` to refresh a declarative page. Update the mounted controls through their binding/configurator path or ask Obsidian to rebuild definitions only when the definition tree itself changed.
|
||||
- Declarative page navigation uses guarded unpublished Obsidian APIs. Prefer `openPagePath`; retain the checked `findTabById`/`navigateToPage` fallback, derive localized paths from the canonical page model, and degrade to non-navigating text when the API is unavailable.
|
||||
- Route all settings writes through `PluginSettingsManager` and its serialized stable-snapshot writer. Save when values change; never make plugin shutdown or settings-tab closure the primary persistence boundary because Obsidian may not await asynchronous writes during termination. Avoid competing direct `saveData()` calls.
|
||||
- Missing and invalid `data.json` states are different. A first installation with no file is valid; a missing file with a recovery snapshot requires a restore-or-defaults choice; invalid startup data should restore a valid device-local snapshot or ask the user how to proceed; invalid data arriving during a running session must be rejected and repaired from the valid in-memory settings.
|
||||
- The last-known-good recovery snapshot is durable, device-local IndexedDB data owned by the main application window. Refresh it after every valid load or save, do not store large snapshots in `localStorage`, and do not create independent recovery databases for popouts.
|
||||
- Preserve unknown persisted keys. Do not derive a sanitizer from the TypeScript settings interface or treat unfamiliar keys as corruption.
|
||||
|
||||
## Script Engine And Automation Notes
|
||||
|
||||
- Excalidraw Automate is a major public surface of this project.
|
||||
@@ -380,7 +490,7 @@ These areas require extra care:
|
||||
- `rollup.config.mjs`: payload injection, localization, manifest/versioning, CSS bundling
|
||||
- `src/core/main.ts`: lifecycle order, settings migration, startup initialization
|
||||
- `src/view/ExcalidrawView.ts`: very large, stateful, performance-sensitive, and central to user behavior
|
||||
- `src/core/managers/PackageManager.ts`: cross-window package loading and runtime evaluation
|
||||
- `src/core/managers/PackageManager.ts`: shared runtime evaluation, host registration, and cross-window lease/alias lifetime
|
||||
- `src/lang/helpers.ts`: build-token compatibility for compressed locales
|
||||
- AI/provider settings and persisted credentials handling
|
||||
- PDF/export code paths and Electron/Obsidian-specific integrations
|
||||
@@ -412,6 +522,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 +530,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 +550,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 +559,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 +647,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 +709,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.
|
||||
|
||||
|
||||
+96
-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,38 +11,78 @@ 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)
|
||||
|
||||
Desktop mobile emulation is useful for checking responsive layout, but it does not reproduce every touch event, synthesized click, focus, scroll gesture, or mobile WebView behavior. If a change affects an interactive mobile control, validate it on at least one physical phone or tablet.
|
||||
|
||||
Use a risk-based test plan rather than a generic smoke test. Every change should identify the most likely regression and whether it needs separate coverage in:
|
||||
|
||||
- the main Obsidian window
|
||||
- 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
|
||||
|
||||
For UI and CSS changes:
|
||||
|
||||
- Use semantic controls and Obsidian's event helpers. Link-like navigation should use a real anchor; custom navigation handlers should use `onClickEvent`.
|
||||
- Keep accessible names in `aria-label`. If a styled tooltip is already present, omit the HTML `title` attribute to avoid a second native browser tooltip.
|
||||
- Run Obsidian CodeScanner and resolve compatibility warnings against the supported Obsidian baseline. Prefer simple, broadly supported CSS when advanced styling is only decorative.
|
||||
|
||||
Timers, observers, autosave coordination, and undocumented Obsidian API workarounds may exist for platform behavior outside the plugin's control. Trace their purpose before simplifying them.
|
||||
|
||||
## 🪵 Logging Requirement
|
||||
|
||||
- **Do not use direct `console.log(...)` calls in project code.** Use the shared logging helper exported as `log` from `src/utils/debugHelper.ts`.
|
||||
- If you are working in a Node script where importing `src/utils/debugHelper.ts` is not practical, define and use a local `log` wrapper instead of calling `console.log(...)` directly.
|
||||
- Temporary performance diagnostics must use a unique searchable prefix and
|
||||
produce copyable string lines rather than expandable console objects. Keep
|
||||
instrumentation separate from functional behavior, avoid vault contents,
|
||||
and include filenames only when per-file attribution is explicitly needed.
|
||||
- Remove temporary diagnostics before committing. Search both `src/` and the
|
||||
built `dist/main.js` for the prefix so timing callbacks and bundled log code
|
||||
are not left behind.
|
||||
|
||||
## 🏗️ Architecture & Sub-components
|
||||
|
||||
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.
|
||||
The plugin bundles one private React/ReactDOM runtime and combines it with one evaluated Excalidraw runtime. Every main-window and popout view leases that shared package while supplying its own stable `ownerDocument`.
|
||||
- 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.
|
||||
- React and its JSX runtimes are bundled normally from official npm entry points. They must remain external to the separately built Excalidraw artifact and to the plugin's library build so neither path creates a second React copy.
|
||||
- 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 +90,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 +127,58 @@ 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.
|
||||
|
||||
Keep component commit readiness, local integration readiness, and durable
|
||||
consumer handoff separate. A copied artifact can validate the pair locally,
|
||||
but a plugin change that consumes a new fork API is not release-ready until the
|
||||
published package is installed and `package.json` plus `package-lock.json`
|
||||
reference that version.
|
||||
|
||||
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.
|
||||
|
||||
### 6. Settings UI and persistence
|
||||
|
||||
The plugin keeps Obsidian 1.8.7 compatibility while using searchable declarative settings on Obsidian 1.13 and newer.
|
||||
|
||||
- Do not bump the Obsidian dependency or minimum version just to use the declarative API. Gate it at runtime; returning an empty definition array is the intentional legacy fallback.
|
||||
- Maintain one canonical settings hierarchy and shared control behavior for both the declarative multi-page and legacy single-page layouts, including descriptions and Markdown export. Do not fork the two experiences into independent implementations.
|
||||
- Keep interdependent controls together and apply their visibility, options, and disabled state during initial render as well as after changes.
|
||||
- Persist settings through `PluginSettingsManager`; do not add independent `saveData()` calls or rely on plugin shutdown to finish an asynchronous save.
|
||||
- Treat a missing `data.json`, invalid/corrupted data, and a valid externally synchronized update as separate cases. Preserve the device-local recovery workflow and unknown forward-compatible setting keys.
|
||||
|
||||
## 🌍 Localization & User-Facing Text
|
||||
|
||||
- **No hardcoded strings:** There should be no hardcoded English strings directly in the UI components or logic.
|
||||
- **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
|
||||
|
||||
|
||||
+1318
-58
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,231 @@
|
||||
# Excalidraw Automate scripting support plan
|
||||
|
||||
Status: active as of 2026-08-29.
|
||||
|
||||
This plan tracks the modernization of ExcalidrawAutomate AI support material while preserving compatibility with the long-lived training entrypoint.
|
||||
|
||||
Scope summary:
|
||||
- Keep [docs/AITrainingData](docs/AITrainingData) as the canonical output location.
|
||||
- Keep [docs/AITrainingData/ExcalidrawAutomate full library for LLM training.md](docs/AITrainingData/ExcalidrawAutomate%20full%20library%20for%20LLM%20training.md) as a stable entrypoint, but curate it as a router to skill-first references.
|
||||
- Use one unified generator behind `npm run doc`.
|
||||
- Keep [ea-scripts/index-new.md](ea-scripts/index-new.md) manually curated.
|
||||
- Keep skill generation manually triggered by maintainer workflows (no automatic watcher/CI updates in this phase).
|
||||
- Add strict naming rules for script preview images under [images](images).
|
||||
|
||||
## Decisions captured
|
||||
|
||||
1. Unified generation command
|
||||
- `npm run doc` is the single maintainer command for documentation generation.
|
||||
- If a script-template repository is present in the current VS Code workspace, `npm run doc` should also refresh template-project references/artifacts.
|
||||
|
||||
2. Legacy entrypoint behavior
|
||||
- The legacy training file remains the stable public entrypoint.
|
||||
- It must warn AI tools that generated code quality may fail if linked skill/reference URLs are inaccessible (for example: URL access disabled in some chat tools).
|
||||
|
||||
3. Script library publishing guidance
|
||||
- `index-new.md` remains manual.
|
||||
- Agents should be guided to open a proper PR for publishing scripts in this repository instead of trying to bypass the normal contribution workflow.
|
||||
- Every publishing PR (new script or script update) must update [ea-scripts/directory-info.json](ea-scripts/directory-info.json).
|
||||
- For updates, the `mtime` value for the updated script file must be refreshed so the plugin can detect local update availability.
|
||||
|
||||
4. Template repository direction
|
||||
- A separate repository will be created first.
|
||||
- Proposed name: `ea-script-template`.
|
||||
- Once added to this workspace, the unified generator can optionally update it.
|
||||
- Repository availability status: present and accessible at [../ea-script-template](../ea-script-template).
|
||||
|
||||
5. Image naming
|
||||
- Adopt strict naming convention for script preview images, aligned to current patterns but enforceable.
|
||||
|
||||
6. Experimental script policy
|
||||
- Scripts under [ea-scripts](ea-scripts) are treated as validated examples.
|
||||
- No experimental bucket is introduced in this phase.
|
||||
- Very large scripts (for example Mindmap Builder) are still valid; they should be tagged as "advanced/large-reference" rather than experimental.
|
||||
|
||||
7. Skill generation trigger
|
||||
- Keep manual generation trigger. No automated regeneration in this phase.
|
||||
|
||||
## Progress tracking
|
||||
|
||||
Target branch: `improved-scripting-skills`.
|
||||
|
||||
| Phase | Status | Current outcome |
|
||||
| --- | --- | --- |
|
||||
| Baseline audit and constraints capture | Complete | Existing generators, outputs, and maintainer decisions captured in this plan |
|
||||
| Create planning artifact in repository | Complete | Added [ScriptSupportPlan.md](ScriptSupportPlan.md) with phases, decisions, and action log |
|
||||
| Unify generator implementation behind `npm run doc` | Complete | Added shared generator core at [scripts/excalidraw-docs-generator-core.mjs](scripts/excalidraw-docs-generator-core.mjs); both [scripts/generate-script-library.mjs](scripts/generate-script-library.mjs) and [scripts/skill-builder.mjs](scripts/skill-builder.mjs) are thin wrappers over one code path |
|
||||
| Ensure canonical pen type completeness in generated docs | Complete | Generated references now include canonical Obsidian pen stroke type definitions plus the full public `src/types` and `lib/types` declaration surface |
|
||||
| Curate legacy training entrypoint warning and routing | Complete | Legacy training entrypoint now warns about inaccessible references, names the master repository, and routes agents to the curated skill/reference set with absolute GitHub URLs |
|
||||
| Add PR publishing workflow guidance for scripting agents | Complete | Generated skill guidance now directs script publishing through PRs, keeps `index-new.md` manual, and requires `directory-info.json` mtime updates |
|
||||
| Add strict image naming and validation | Complete | Generator now warns on non-conforming preview filenames and documents the `scripts-{slug}.{ext}` rule in generated publishing guidance |
|
||||
| Optional template-repo sync from `npm run doc` | Complete | `npm run doc` now refreshes a co-located `ea-script-template` bootstrap under `.ai/excalidraw-automate/` when the sibling repo is present |
|
||||
|
||||
## Implementation checkpoints
|
||||
|
||||
### Checkpoint 1: Shared generator core and single command
|
||||
Objective:
|
||||
- Introduce a shared generator module and keep lightweight wrappers for backward command compatibility.
|
||||
|
||||
Planned changes:
|
||||
- Consolidate duplicated logic currently split between:
|
||||
- [scripts/generate-script-library.mjs](scripts/generate-script-library.mjs)
|
||||
- [scripts/skill-builder.mjs](scripts/skill-builder.mjs)
|
||||
- Keep `npm run doc` as the single entrypoint command for maintainers.
|
||||
- Keep manual run model. Do not add auto-run hooks in this phase.
|
||||
|
||||
Acceptance:
|
||||
- One command (`npm run doc`) generates both legacy and skill outputs exactly once.
|
||||
- Output files stay under [docs/AITrainingData](docs/AITrainingData).
|
||||
|
||||
### Checkpoint 2: Fix type-definition completeness regression
|
||||
Objective:
|
||||
- Ensure generated type references remain concrete after alias migrations.
|
||||
|
||||
Problem to solve:
|
||||
- `lib/types/penTypes.d.ts` now aliases fork-owned types, and top import stripping can hide canonical shapes in generated docs.
|
||||
|
||||
Planned changes:
|
||||
- Include canonical Obsidian type declarations from the fork type surface in generated reference outputs.
|
||||
- Add a post-generation guard that fails if `ObsidianPenStrokeOptions` shape is missing.
|
||||
|
||||
Acceptance:
|
||||
- Both:
|
||||
- [docs/AITrainingData/Excalidraw Automate library and related type definitions.md](docs/AITrainingData/Excalidraw%20Automate%20library%20and%20related%20type%20definitions.md)
|
||||
- [docs/AITrainingData/ExcalidrawAutomate full library for LLM training.md](docs/AITrainingData/ExcalidrawAutomate%20full%20library%20for%20LLM%20training.md)
|
||||
include concrete stroke option structure, not alias-only references.
|
||||
|
||||
Status:
|
||||
- Complete.
|
||||
- The generator now includes all declaration files under [src/types](src/types) and [lib/types](lib/types), plus the canonical fork-owned `obsidianTypes.d.ts` source for `ObsidianPenStrokeOptions`.
|
||||
|
||||
### Checkpoint 3: Curated legacy entrypoint messaging
|
||||
Objective:
|
||||
- Keep stable legacy entrypoint while steering agents to curated skill references.
|
||||
|
||||
Planned changes:
|
||||
- Add a prominent warning that script generation can fail if linked references are not accessible.
|
||||
- Include concrete note about environments requiring explicit URL enablement.
|
||||
- Add short routing section pointing to curated skill/reference materials.
|
||||
|
||||
Acceptance:
|
||||
- Legacy file remains backward compatible as an entrypoint.
|
||||
- Warning is clear and placed before the main usage workflow.
|
||||
|
||||
Status:
|
||||
- Complete.
|
||||
- The generated legacy entrypoint now includes a top-level routing warning, the master repository URL, and direct absolute links to the curated skill and reference files.
|
||||
|
||||
### Checkpoint 4: Script publishing workflow guidance for agents
|
||||
Objective:
|
||||
- Teach agents to publish scripts through normal repository contribution workflow.
|
||||
|
||||
Planned changes:
|
||||
- Add concise maintainer-approved workflow guidance in skill docs:
|
||||
- add script to [ea-scripts](ea-scripts)
|
||||
- add image to [images](images)
|
||||
- update [ea-scripts/index-new.md](ea-scripts/index-new.md) manually
|
||||
- update [ea-scripts/directory-info.json](ea-scripts/directory-info.json) in the same PR
|
||||
- for script updates, refresh the target script `mtime` entry in [ea-scripts/directory-info.json](ea-scripts/directory-info.json)
|
||||
- keep AI training material updates out of script publishing PRs
|
||||
- open PR with focused diff and validation notes
|
||||
- Explicitly avoid automating `index-new.md`.
|
||||
|
||||
Acceptance:
|
||||
- Publishing workflow appears in generated skill material.
|
||||
- Guidance is PR-centric and does not suggest direct pushes.
|
||||
|
||||
Status:
|
||||
- Complete.
|
||||
- The generated skill file now includes a dedicated publishing workflow section with absolute repository links, PR-only guidance, manual `index-new.md` curation, and `directory-info.json` update requirements.
|
||||
|
||||
### Checkpoint 5: Strict image naming convention and validator
|
||||
Objective:
|
||||
- Keep existing style while making naming consistent and enforceable.
|
||||
|
||||
Proposed naming rule:
|
||||
- `scripts-{slug}.{ext}` where:
|
||||
- `slug` = lowercase words joined by hyphen
|
||||
- only `a-z`, `0-9`, `-`
|
||||
- extensions allowed: `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, `.svg`
|
||||
|
||||
Examples:
|
||||
- `scripts-add-link-to-existing-file-and-open.jpg`
|
||||
- `scripts-boolean-operations-showcase.png`
|
||||
|
||||
Planned changes:
|
||||
- Add validation in generator flow with clear error output.
|
||||
- Keep compatibility mode for pre-existing files during initial rollout (warn-only first, strict fail in follow-up if desired).
|
||||
|
||||
Acceptance:
|
||||
- New/updated script previews follow the naming contract.
|
||||
- Validation output is actionable for contributors.
|
||||
|
||||
Status:
|
||||
- Complete.
|
||||
- The generator now warns on non-conforming preview filenames and surfaces the naming rule in the generated publishing workflow guidance.
|
||||
|
||||
### Checkpoint 6: Optional template repository sync
|
||||
Objective:
|
||||
- Allow `npm run doc` to refresh a co-located script-template repo if present.
|
||||
|
||||
Planned behavior:
|
||||
- Detect a workspace folder named `ea-script-template` (or configurable path).
|
||||
- If found, update agreed generated reference artifacts in that repo.
|
||||
- If absent, continue without failure.
|
||||
|
||||
Current status:
|
||||
- Repository now exists and is readable at [../ea-script-template](../ea-script-template).
|
||||
- Checkpoint is considered unblocked and ready for scoped implementation once approved.
|
||||
|
||||
Design note: AI support files in template repo
|
||||
- Preferred default: synchronized local snapshot under `.ai/excalidraw-automate/`, copied from canonical generated references in this repository.
|
||||
- Routing note: keep canonical GitHub links in SKILL content, but ensure local references and script examples are present for environments without URL access.
|
||||
- Reasoning: local snapshot gives immediate offline usability while preserving canonical source of truth in plugin-generated outputs.
|
||||
|
||||
Design note: template usage model
|
||||
- Recommended model: single `ea-script-template` repository used as a multi-script workspace (one folder per script project) with shared utilities.
|
||||
- Why: easier maintenance of common helpers, lint/build rules, and shared abstractions across scripts like Mindmap Builder, Slideshow, and Shade Master.
|
||||
- Alternative supported pattern: per-script clones for strict isolation (useful for publishing independent repos), but this should be optional rather than the default path.
|
||||
|
||||
Acceptance:
|
||||
- `npm run doc` succeeds in both cases:
|
||||
- template repo present
|
||||
- template repo absent
|
||||
|
||||
Status:
|
||||
- Complete.
|
||||
- `npm run doc` now refreshes a full local skill snapshot in the sibling `ea-script-template` workspace under `.ai/excalidraw-automate/` when the repo is available.
|
||||
|
||||
## Validation approach
|
||||
|
||||
For each implementation checkpoint:
|
||||
- Run `npm run doc` from repository root.
|
||||
- Verify generated files changed only in intended outputs.
|
||||
- For script/reference changes, inspect key generated artifacts manually.
|
||||
- Keep [ea-scripts/index-new.md](ea-scripts/index-new.md) untouched unless explicitly edited by maintainer.
|
||||
|
||||
## Risks and mitigations
|
||||
|
||||
Risk: duplicate logic drifts again across scripts.
|
||||
- Mitigation: one shared generator core and wrapper entrypoints.
|
||||
|
||||
Risk: type aliasing hides critical concrete structures again.
|
||||
- Mitigation: required-symbol guard (`ObsidianPenStrokeOptions`) and explicit canonical-source inclusion.
|
||||
|
||||
Risk: stricter image naming breaks existing contributions.
|
||||
- Mitigation: staged rollout (warn-first) and clear remediation examples.
|
||||
|
||||
Risk: template sync introduces hard dependency on external repo.
|
||||
- Mitigation: optional detection; never fail when repo is absent.
|
||||
|
||||
## Action log
|
||||
|
||||
| Date | Action | Outcome | Validation |
|
||||
| --- | --- | --- | --- |
|
||||
| 2026-08-29 | Captured maintainer decisions for scripting support modernization | Decisions documented for unified generator, manual index curation, PR workflow guidance, strict image naming, and optional template sync | Plan file created at [ScriptSupportPlan.md](ScriptSupportPlan.md) |
|
||||
| 2026-08-29 | Confirmed template repository workspace availability and expanded publishing requirements | Verified [../ea-script-template](../ea-script-template) is present and readable; added mandatory [ea-scripts/directory-info.json](ea-scripts/directory-info.json) update rules to publishing workflow and checkpoint details | Directory listing succeeded for [../ea-script-template](../ea-script-template); plan updated |
|
||||
| 2026-08-29 | Implemented checkpoint 1 unified generator | Consolidated duplicated generation logic into [scripts/excalidraw-docs-generator-core.mjs](scripts/excalidraw-docs-generator-core.mjs), with wrapper entrypoints preserved at [scripts/generate-script-library.mjs](scripts/generate-script-library.mjs) and [scripts/skill-builder.mjs](scripts/skill-builder.mjs) | `npm run doc` completed successfully and regenerated legacy + skill outputs from one code path |
|
||||
| 2026-08-29 | Implemented checkpoint 5 image naming validator | Added warning-only preview filename validation and surfaced the `scripts-{slug}.{ext}` rule in generated publishing guidance | `npm run doc` completed successfully and emitted the expected warning for legacy preview names |
|
||||
| 2026-08-29 | Implemented checkpoint 6 template bootstrap sync | `npm run doc` now refreshes a link-first bootstrap in the sibling `ea-script-template` workspace under `.ai/excalidraw-automate/` | `npm run doc` completed successfully and refreshed the sibling template bootstrap files |
|
||||
| 2026-08-29 | Hardened checkpoint 6 for offline and advanced script authoring | Template sync now mirrors full generated references and script examples instead of only link stubs | `npm run doc` and `npm run sync-refs` now produce local skill + references + scripts snapshot in `.ai/excalidraw-automate/` |
|
||||
| 2026-08-29 | Aligned template script extensions and build output | Template-only reference snapshots now use `.js` filenames with rewritten local links; the template build emits executable `.md` scripts with purpose metadata and editable configuration constants before the bundle | `npm run doc` preserves `.js` reference filenames; template `npm run build`, `npm run check`, and package validation pass on Node 22 |
|
||||
+3375
-1389
File diff suppressed because it is too large.
Load diff
@@ -12,7 +12,7 @@ Content structure:
|
||||
2. The curated script overview (index-new.md)
|
||||
3. Raw source of every *.md script in /ea-scripts (each fenced code block is auto-closed to ensure well-formed aggregation)
|
||||
|
||||
Generated on: 2026-07-12T12:50:29.769Z
|
||||
Generated on: 2026-08-30T12:07:47.389Z
|
||||
|
||||
---
|
||||
|
||||
@@ -120,6 +120,7 @@ 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/Mindmap%20Builder.svg"/></div>|[[#Mindmap Builder]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20format.svg"/></div>|[[#Mindmap format]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Printable%20Layout%20Wizard.svg"/></div>|[[#Printable Layout Wizard]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/VoronoiDiagramGenerator.svg"/></div>|[[#Voronoi Diagram Generator]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Zoom%20to%20Fit%20Selected%20Elements.svg"/></div>|[[#Zoom to Fit Selected Elements]]|
|
||||
|
||||
## Connectors and Arrows
|
||||
@@ -756,6 +757,23 @@ 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/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/Printable%20Layout%20Wizard.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Export Excalidraw to PDF Pages: Define printable page areas using frames, then export each frame as a separate page in a multi-page PDF. Perfect for turning your Excalidraw drawings into printable notes, handouts, or booklets. Supports standard and custom page sizes, margins, and easy frame arrangement.<br><a href="https://www.youtube.com/watch?v=29EWeglRm7s" target="_blank"><img src ="https://i.ytimg.com/vi/29EWeglRm7s/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/29EWeglRm7s' target='_blank'>Link to video on YouTube</a><br><a href="https://www.youtube.com/watch?v=DqDnzCOoYMc" target="_blank"><img src ="https://i.ytimg.com/vi/DqDnzCOoYMc/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/DqDnzCOoYMc' target='_blank'>Link to video on YouTube</a><br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-01.png" style="max-width: 400px;"><br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-02.png" style="max-width: 400px;"></td></tr></table>
|
||||
|
||||
## Voronoi Diagram Generator
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/VoronoiDiagramGenerator.md
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/FreeCutter'>@FreeCutter</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/VoronoiDiagramGenerator.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script generates a Voronoi diagram from selected elements on the drawing canvas.
|
||||
|
||||
The following parameters can be set in 'Voronoi Settings' window pop-up once the script is started:
|
||||
- Frame width (default: 100)
|
||||
- Roughness (default: 0)
|
||||
- Stroke width (default: 2)
|
||||
- Grouping (default: checked)
|
||||
|
||||
Setting parameters could be set back to default values by click on button 'Default'.
|
||||
|
||||
See background information about [Voronoi diagram](https://en.wikipedia.org/wiki/Voronoi_diagram) at Wikipedia.
|
||||
|
||||
Comments and discussion are welcomed in the [Sketch Your Mind Community](https://community.sketch-your-mind.com)<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/Voronoi_diagram_example.svg'></td></tr></table>
|
||||
|
||||
## Zoom to Fit Selected Elements
|
||||
```excalidraw-script-install
|
||||
@@ -798,6 +816,7 @@ elements.forEach((el)=>{
|
||||
ea.addToGroup([el.id,ellipseId]);
|
||||
});
|
||||
await ea.addElementsToView(false,false,true);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -870,6 +889,7 @@ if(openInCurrentPane) {
|
||||
return;
|
||||
}
|
||||
ea.openFileInNewOrAdjacentLeaf(file);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -967,6 +987,7 @@ if(openInCurrentPane) {
|
||||
return;
|
||||
}
|
||||
ea.openFileInNewOrAdjacentLeaf(file);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -1902,6 +1923,7 @@ function applyTranformationMatrix(vectors, transformationMatrix) {
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -2090,6 +2112,7 @@ function recalculateEndPointOfLine(line, el) {
|
||||
line.points[line.points.length - 1] = [intersectA[0][0] - line.x, intersectA[0][1] - line.y];
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -5162,6 +5185,7 @@ if (elements.length>0) {
|
||||
ea.copyViewElementsToEAforEditing(editedElements);
|
||||
|
||||
ea.addElementsToView(false,false);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -7336,6 +7360,7 @@ async function main() {
|
||||
|
||||
// Execute Script
|
||||
main();
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -7826,6 +7851,7 @@ if(element.type === 'arrow') {
|
||||
appState.currentItemStartArrowhead = element.startArrowhead;
|
||||
appState.currentItemEndArrowhead = element.endArrowhead;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -7854,6 +7880,7 @@ const fname = await utils.inputPrompt("Filename for new file","Filename",folder)
|
||||
const file = await app.fileManager.createAndOpenMarkdownFile(fname,true);
|
||||
await ea.addImage(0,0,file);
|
||||
ea.addElementsToView(true,true);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -8017,6 +8044,7 @@ for (const el of ea.getElements()) {
|
||||
}
|
||||
}
|
||||
await ea.addElementsToView(false, false);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -8455,6 +8483,7 @@ for (const line of lines) {
|
||||
|
||||
ea.copyViewElementsToEAforEditing(lines);
|
||||
await ea.addElementsToView(false,false);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -8523,6 +8552,7 @@ id = ea.addEllipse(
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
ea.addToGroup([id].concat(elements.map((el)=>el.id)));
|
||||
ea.addElementsToView(false,false);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -11475,6 +11505,8 @@ const openConfigModal = () => {
|
||||
};
|
||||
|
||||
openConfigModal();
|
||||
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -11810,6 +11842,7 @@ const outfile = await app.vault.create(outputPath,result);
|
||||
setTimeout(()=>{
|
||||
ea.openFileInNewOrAdjacentLeaf(outfile);
|
||||
}, 250);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -13565,6 +13598,7 @@ function recalculateEndPointOfLine(line, el) {
|
||||
line.points[line.points.length - 1] = [intersectA[0][0] - line.x, intersectA[0][1] - line.y];
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -13646,6 +13680,7 @@ for(var i=0; i<groups.length; i++) {
|
||||
}
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
await ea.addElementsToView(false, false);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -13780,6 +13815,7 @@ else if(fromBorder === 'right') {
|
||||
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
await ea.addElementsToView(false, false);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -13856,6 +13892,7 @@ for(var i=0; i<groups.length; i++) {
|
||||
}
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
await ea.addElementsToView(false, false);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -14015,6 +14052,7 @@ for(var i=0; i<groups.length; i++) {
|
||||
}
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
await ea.addElementsToView(false, false);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -14195,6 +14233,7 @@ do {
|
||||
|
||||
|
||||
await ea.addElementsToView(false, false, true);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -14951,6 +14990,7 @@ try {
|
||||
} catch (err) {
|
||||
_ = new Notice(err.toString())
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -17794,7 +17834,8 @@ try {
|
||||
} catch (error) {
|
||||
console.error("Error showing completion message:", error);
|
||||
new Notice("Operation completed with some errors");
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -17923,6 +17964,7 @@ ea.viewUpdateScene({
|
||||
elements: ea.getElements(),
|
||||
storeAction: "capture" // Ensures the change is saved and added to the undo/redo history.
|
||||
});
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -17982,6 +18024,7 @@ for (const el of ea.getElements()) {
|
||||
}
|
||||
}
|
||||
await ea.addElementsToView(false, false);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -18198,6 +18241,7 @@ const bottomHeaderY = START_Y + 160 + (12 * (CELL_HEIGHT + ROW_SPACING)) + 40;
|
||||
drawDayHeaders(bottomHeaderY);
|
||||
|
||||
await ea.addElementsToView(false, false, true);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -21594,11 +21638,36 @@ const zoomToFit = (mode) => {
|
||||
elementID: sel.id,
|
||||
level: nextLevel
|
||||
}
|
||||
api().scrollToContent([sel], {
|
||||
fitToViewport: true,
|
||||
viewportZoomFactor: getZoom(nextLevel),
|
||||
animate: true
|
||||
});
|
||||
|
||||
const targetZoom = getZoom(nextLevel);
|
||||
|
||||
// Fallback for older versions vs new Excalidraw 2.26.0+ Viewport API
|
||||
if (!ea.verifyMinimumPluginVersion("2.26.0")) {
|
||||
api().scrollToContent([sel], {
|
||||
fitToViewport: true,
|
||||
viewportZoomFactor: targetZoom,
|
||||
animate: true
|
||||
});
|
||||
} else {
|
||||
// For the new API, we calculate a target rect centered on the element
|
||||
// with dimensions that will force 'fit: "contain"' to reach our target zoom.
|
||||
const appState = api().getAppState();
|
||||
const targetW = appState.width / targetZoom;
|
||||
const targetH = appState.height / targetZoom;
|
||||
const cx = sel.x + sel.width / 2;
|
||||
const cy = sel.y + sel.height / 2;
|
||||
|
||||
api().setViewport({
|
||||
target: {
|
||||
x: cx - targetW / 2,
|
||||
y: cy - targetH / 2,
|
||||
width: targetW,
|
||||
height: targetH
|
||||
},
|
||||
fit: "contain",
|
||||
animation: true
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21627,10 +21696,20 @@ const focusSelected = () => {
|
||||
|
||||
if (!sel) return;
|
||||
|
||||
api().scrollToContent(sel, {
|
||||
fitToContent: false,
|
||||
animate: true,
|
||||
});
|
||||
// Fallback for older versions vs new Excalidraw 2.26.0+ Viewport API
|
||||
if (!ea.verifyMinimumPluginVersion("2.26.0")) {
|
||||
api().scrollToContent(sel, {
|
||||
fitToContent: false,
|
||||
animate: true,
|
||||
});
|
||||
} else {
|
||||
// fit: "none" recenters at the current zoom without changing it
|
||||
api().setViewport({
|
||||
target: [sel],
|
||||
fit: "none",
|
||||
animation: true
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const getMindmapOrder = (node) => {
|
||||
@@ -32328,6 +32407,7 @@ else {
|
||||
}
|
||||
|
||||
await ea.addElementsToView(false,false,true);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -32705,6 +32785,7 @@ generateTree(elements);
|
||||
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
await ea.addElementsToView(false, false);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -33740,6 +33821,7 @@ async function run() {
|
||||
}
|
||||
|
||||
run();
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -34654,6 +34736,7 @@ async function run() {
|
||||
}
|
||||
|
||||
run();
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -34829,6 +34912,7 @@ for(i of img) {
|
||||
await app.fileManager.renameFile(file,`${newPath}.${file.extension}`);
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -34952,6 +35036,7 @@ for(let i=0; i<repeatNum; i++) {
|
||||
}
|
||||
|
||||
await ea.addElementsToView(false, false, true);
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -35054,6 +35139,8 @@ for(let i=0; i<repeatNum; i++) {
|
||||
}
|
||||
|
||||
await ea.addElementsToView(false, false, true);
|
||||
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -36149,6 +36236,7 @@ ea.copyViewElementsToEAforEditing(elements);
|
||||
ea.getElements().forEach((el)=>el.strokeWidth=width);
|
||||
await ea.addElementsToView(false,false);
|
||||
ea.viewUpdateScene({appState: {currentItemStrokeWidth: width}});
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -37935,6 +38023,7 @@ if(
|
||||
|
||||
window.ExcalidrawSlideshowStartTimer = window.setTimeout(start,500);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -40417,6 +40506,240 @@ ea.getElements().forEach(el=>{
|
||||
const ids = ea.getElements().map(el=>el.id);
|
||||
await ea.addElementsToView(false,true);
|
||||
ea.getExcalidrawAPI().updateContainerSize(ea.getViewElements().filter(el=>ids.contains(el.id)));
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## VoronoiDiagramGenerator.md
|
||||
<!-- Source: ea-scripts/VoronoiDiagramGenerator.md -->
|
||||
|
||||
/*
|
||||
This script generates a Voronoi diagram from selected elements on the drawing canvas.
|
||||
|
||||
The following parameters can be set in 'Voronoi Settings' window pop-up once the script is started:
|
||||
- Frame width (default: 100)
|
||||
- Roughness (default: 0)
|
||||
- Stroke width (default: 2)
|
||||
- Grouping (default: checked)
|
||||
|
||||
Setting parameters could be set back to default values by click on button 'Default'.
|
||||
Check info button for howto help during applying the script.
|
||||
|
||||
See background information about Voronoi diagram at Wikipedia : https://en.wikipedia.org/wiki/Voronoi_diagram
|
||||
|
||||
Comments and discussion are welcomed in the Sketch-Your-Mind community: https://community.sketch-your-mind.com
|
||||
|
||||
```js*/
|
||||
// ExcalidrawAutomate: Voronoi Diagram Generator
|
||||
ea.clear();
|
||||
|
||||
const DEFAULTS = {
|
||||
frameWidth: 100,
|
||||
roughness: 0,
|
||||
strokeWidth: 2,
|
||||
groupVoronoi: true
|
||||
};
|
||||
|
||||
let config = ea.getScriptSettings() || { ...DEFAULTS };
|
||||
|
||||
// --- UI SETTINGS MODAL ---
|
||||
async function openSettings() {
|
||||
return new Promise((resolve) => {
|
||||
const modal = new ea.obsidian.Modal(app);
|
||||
modal.contentEl.style.padding = "20px";
|
||||
|
||||
// Header container with Title and Info Button
|
||||
const headerContainer = modal.contentEl.createDiv();
|
||||
headerContainer.style.display = "flex";
|
||||
headerContainer.style.justifyContent = "space-between";
|
||||
headerContainer.style.alignItems = "center";
|
||||
headerContainer.style.marginBottom = "20px";
|
||||
|
||||
headerContainer.createEl("h2", { text: "Settings - Voronoi Diagram Generator", cls: "mod-header" }).style.margin = "0";
|
||||
|
||||
// Info button using Obsidian's native icon
|
||||
const btnInfo = headerContainer.createEl("button", { cls: "clickable-icon" });
|
||||
btnInfo.setAttribute("aria-label", "Information & Help");
|
||||
btnInfo.innerHTML = ea.obsidian.getIcon("info").outerHTML;
|
||||
|
||||
// Info modal content on click
|
||||
btnInfo.onclick = () => {
|
||||
const infoModal = new ea.obsidian.Modal(app);
|
||||
infoModal.contentEl.style.padding = "20px";
|
||||
infoModal.contentEl.createEl("h3", { text: "About - Voronoi Diagram Generator" });
|
||||
|
||||
// Native Obsidian Icon as HTML string
|
||||
const chatIcon = ea.obsidian.getIcon("message-square").outerHTML;
|
||||
|
||||
const p = infoModal.contentEl.createEl("p");
|
||||
p.innerHTML = `
|
||||
This script generates a Voronoi diagram from selected elements on the drawing canvas.<br><br>
|
||||
<h4 style="margin: 5px 0 5px 0; font-size: 1.1em;">HowTo & Parameters:</h4>
|
||||
<div line-height: 1.4;">
|
||||
<div style="margin-bottom: 10px;">1. <b>Select</b> at least 2 elements on your canvas.</div>
|
||||
<div style="margin-bottom: 4px;">2. <b>Run</b> the script and adjust your settings:</div>
|
||||
<div style="margin: 2px 0 10px 15px; line-height: 1.2;">
|
||||
- <b>Frame width:</b> Spacing around the diagram.<br>
|
||||
- <b>Roughness:</b> Hand-drawn effect (0-3).<br>
|
||||
- <b>Stroke width:</b> Line thickness.<br>
|
||||
- <b>Grouping:</b> Group generated cells together.<br>
|
||||
</div>
|
||||
<div style="margin-bottom: 15px;">3. Click <b>OK</b> to generate.</div>
|
||||
</div><br>
|
||||
<span style="display: inline-flex; align-items: center; gap: 6px; vertical-align: middle;"> ${chatIcon} Feedback & chat: <a href="https://community.sketch-your-mind.com" target="_blank">Sketch Your Mind Community</a>
|
||||
</span>
|
||||
`;
|
||||
infoModal.open();
|
||||
};
|
||||
|
||||
const inputs = {};
|
||||
|
||||
// Helper function to create input rows
|
||||
const createInput = (label, key, type = "number") => {
|
||||
const container = modal.contentEl.createDiv();
|
||||
container.style.marginBottom = "15px";
|
||||
|
||||
container.createEl("label", { text: label });
|
||||
const input = container.createEl("input", { type: type });
|
||||
input.style.display = "block";
|
||||
input.style.marginTop = "5px";
|
||||
input.value = config[key];
|
||||
input.onchange = (e) => config[key] = type === "number" ? Number(e.target.value) : e.target.checked;
|
||||
inputs[key] = input;
|
||||
};
|
||||
|
||||
createInput("Frame width:", "frameWidth");
|
||||
createInput("Roughness (0-3):", "roughness");
|
||||
createInput("Stroke width:", "strokeWidth");
|
||||
|
||||
const checkContainer = modal.contentEl.createDiv();
|
||||
checkContainer.style.marginBottom = "25px";
|
||||
checkContainer.createEl("label", { text: "Grouping: " });
|
||||
inputs.groupVoronoi = checkContainer.createEl("input", { type: "checkbox" });
|
||||
inputs.groupVoronoi.checked = config.groupVoronoi;
|
||||
inputs.groupVoronoi.onchange = (e) => config.groupVoronoi = e.target.checked;
|
||||
|
||||
// Button container
|
||||
const btnContainer = modal.contentEl.createDiv();
|
||||
btnContainer.style.display = "flex";
|
||||
btnContainer.style.gap = "10px";
|
||||
btnContainer.style.justifyContent = "flex-end";
|
||||
|
||||
const btnDefault = btnContainer.createEl("button", { text: "Default" });
|
||||
const btnOk = btnContainer.createEl("button", { text: "OK" });
|
||||
|
||||
btnDefault.onclick = () => {
|
||||
config = { ...DEFAULTS };
|
||||
inputs.frameWidth.value = config.frameWidth;
|
||||
inputs.roughness.value = config.roughness;
|
||||
inputs.strokeWidth.value = config.strokeWidth;
|
||||
inputs.groupVoronoi.checked = config.groupVoronoi;
|
||||
new Notice("Settings reset to default");
|
||||
};
|
||||
|
||||
btnOk.onclick = () => {
|
||||
ea.setScriptSettings(config);
|
||||
modal.close();
|
||||
resolve(true);
|
||||
};
|
||||
|
||||
modal.open();
|
||||
});
|
||||
}
|
||||
|
||||
// Wait for user to configure settings
|
||||
const proceed = await openSettings();
|
||||
if (!proceed) return;
|
||||
|
||||
// --- ALGORITHM & EXECUTION ---
|
||||
const els = ea.getViewSelectedElements();
|
||||
|
||||
if (els.length < 2) {
|
||||
new Notice("Please select at least two items!");
|
||||
return;
|
||||
}
|
||||
|
||||
const seeds = els.map(el => ({ x: el.x + el.width / 2, y: el.y + el.height / 2 }));
|
||||
|
||||
if (seeds.length < 2) {
|
||||
new Notice("Please select at least two items!");
|
||||
return;
|
||||
}
|
||||
|
||||
const minX = Math.min(...seeds.map(s => s.x)) - config.frameWidth;
|
||||
const minY = Math.min(...seeds.map(s => s.y)) - config.frameWidth;
|
||||
const maxX = Math.max(...seeds.map(s => s.x)) + config.frameWidth;
|
||||
const maxY = Math.max(...seeds.map(s => s.y)) + config.frameWidth;
|
||||
|
||||
const bbox = [
|
||||
{ x: minX, y: minY },
|
||||
{ x: maxX, y: minY },
|
||||
{ x: maxX, y: maxY },
|
||||
{ x: minX, y: maxY }
|
||||
];
|
||||
|
||||
function clipPolygon(poly, p1, p2) {
|
||||
const mid = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
|
||||
const n = { x: p2.x - p1.x, y: p2.y - p1.y };
|
||||
const isInside = (p) => (p.x - mid.x) * n.x + (p.y - mid.y) * n.y <= 0;
|
||||
|
||||
const intersect = (a, b) => {
|
||||
const num = (a.x - mid.x) * n.x + (a.y - mid.y) * n.y;
|
||||
const den = (b.x - a.x) * n.x + (b.y - a.y) * n.y;
|
||||
if (den === 0) return null;
|
||||
const t = -num / den;
|
||||
return { x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y) };
|
||||
};
|
||||
|
||||
const result = [];
|
||||
for (let i = 0; i < poly.length; i++) {
|
||||
const cur = poly[i];
|
||||
const prev = poly[(i - 1 + poly.length) % poly.length];
|
||||
const curIn = isInside(cur);
|
||||
const prevIn = isInside(prev);
|
||||
|
||||
if (curIn !== prevIn) {
|
||||
const ix = intersect(prev, cur);
|
||||
if (ix) result.push(ix);
|
||||
}
|
||||
if (curIn) result.push(cur);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const polygons = seeds.map((s, i) => {
|
||||
let poly = [...bbox];
|
||||
seeds.forEach((_, j) => {
|
||||
if (i !== j) poly = clipPolygon(poly, seeds[i], seeds[j]);
|
||||
});
|
||||
return poly;
|
||||
});
|
||||
|
||||
ea.style.roughness = config.roughness;
|
||||
ea.style.strokeWidth = config.strokeWidth;
|
||||
ea.style.backgroundColor = "transparent";
|
||||
|
||||
const ids = [];
|
||||
|
||||
for (const poly of polygons) {
|
||||
if (poly.length < 3) continue;
|
||||
const points = poly.map(p => [p.x, p.y]);
|
||||
points.push(points[0]);
|
||||
ids.push(ea.addLine(points));
|
||||
}
|
||||
|
||||
if (config.groupVoronoi && ids.length > 0) {
|
||||
ea.addToGroup(ids);
|
||||
}
|
||||
|
||||
await ea.addElementsToView(false, false);
|
||||
|
||||
// Clear selection so nothing remains selected on the canvas
|
||||
const view = app.workspace.activeLeaf.view; if (view && view.excalidrawAPI) { view.excalidrawAPI.updateScene({ appState: { selectedElementIds: {} } }); }
|
||||
|
||||
new Notice("Voronoi diagram created!");
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
@@ -40439,4 +40762,5 @@ https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.h
|
||||
elements = ea.getViewSelectedElements();
|
||||
api = ea.getExcalidrawAPI();
|
||||
api.zoomToFit(elements,10);
|
||||
|
||||
```
|
||||
File diff suppressed because it is too large.
Load diff
@@ -9,8 +9,17 @@ Excalidraw-Obsidian is an Obsidian.md plugins that is built on the open source E
|
||||
|
||||
Read the information below and respond with I'm ready. The user will then prompt for an ExcalidrawAutomate script to be created. Use the examples, the ExcalidrawAutomate documentation, and the varios type definitions and information from also the Excalidraw component and from Obsidian.md to generate the script based on the user's requirements.
|
||||
|
||||
**Routing note:** Prefer the curated skill package and reference set first. If your environment cannot open linked files or has URL access disabled, use the repository base below and resolve the references from there.
|
||||
|
||||
- Master repository: https://github.com/zsviczian/obsidian-excalidraw-plugin
|
||||
- Start with: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/SKILL.md
|
||||
- Type definitions: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/type-definitions.md
|
||||
- API usage index: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/api-usage-index.md
|
||||
- ExcalidrawLib signatures: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/excalidraw-lib-functions.md
|
||||
- Startup examples: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/startup-scripts.md
|
||||
|
||||
In addition to ExcalidrawAutomate, you can also use two other sources of functions:
|
||||
- The Excalidraw API available via `ea.getExcalidrawAPI()`. Note: the API is only available if `ea.targetView` is set. When running Excalidraw scripts using the script engine, the provided `ea` object is already set up with targetView by default. Otherwise you need to first run `ea.setView()`.
|
||||
- The Excalidraw API available via `ea.getExcalidrawAPI()`. Note: the API is only available if `ea.targetView` is set. When running Excalidraw scripts using the script engine, the provided `ea` object is already set up with targetView by default. Otherwise call `ea.setView()` to select a sensible default or `ea.setView(view)` to bind explicitly. Calling `ea.setView(null)` deliberately clears `targetView`; it does not auto-select another drawing.
|
||||
- `window.ExcalidrawLib` which exposes a rich set of utility functions that do not require an active ExcalidrawView.
|
||||
|
||||
**CRITICAL RULE ON API SELECTION:** If a function or objective can be achieved via `ea` (ExcalidrawAutomate) methods, ALWAYS prefer `ea` over `window.ExcalidrawLib`. `ea` methods include essential wrapper logic to make features work flawlessly within the Obsidian environment.
|
||||
@@ -23,10 +32,17 @@ For a reference, follow the implementation pattern used in the "Printable Layout
|
||||
- Elements can be hidden by setting their opacity to 0. When hiding elements this way, it is good practice to temporarily store their original opacity in customData. This allows for easy restoration of the original opacity later.
|
||||
- Elements can be deleted from the scene by setting their isDeleted property to true.
|
||||
- The Obsidian.md module is available on `ea.obsidian`.
|
||||
- Version checks are distinct: use `ea.verifyMinimumPluginVersion()` for the Excalidraw plugin and `ea.verifyMinAppVersion()` only for the Obsidian application version.
|
||||
- `utils.executionSource` describes why the current top-level invocation happened. Supported values are `"manual"`, `"plugin-startup"`, `"view-autostart"`, `"sidepanel-restore"`, `"sidepanel-reload"`, and `"drawing-onload"`. It does not indicate whether code came from the compilation cache or whether the script has run before.
|
||||
- `ea.registerAutostart(message?)` requests view-autostart permission. The script is automatically attached once to each ExcalidrawView, while manual toolbar/command/hotkey invocation remains independently repeatable. The optional explanation appears as the second paragraph of the permission prompt; do not imply that the script's main interactive action starts automatically when only its tools/providers do.
|
||||
- `ea.registerCleanup(cleanup)` registers synchronous cleanup owned by the current EA instance. Use it for external listeners, timers, observers, and subscriptions; the cleanup runs when that EA is destroyed.
|
||||
- `ea.registerElementActionProvider()` action descriptors take an Obsidian/Lucide icon name such as `"presentation"`, not serialized SVG markup. For buttons a script renders itself, obtain the SVG with `ea.obsidian.getIcon()` and recreate it in the button's owning document when popout support matters.
|
||||
- When an Excalidraw API method requires an element, pass the known typed scene element. For example, call `api.startLineEditor(line, pointIndices)`; do not re-read selection state when the intended line is already known.
|
||||
- For persistent workbench mutations, await `ea.addElementsToView()` with saving enabled (the default). Prefer this public EA save path over unpublished methods on `ea.targetView`.
|
||||
|
||||
**Sidepanels and multi-view tooling:**
|
||||
- Sidepanels are for scripts that must stay open while users hop between multiple Excalidraw views. They should implement the SidepanelTab hooks (`onOpen`, `onFocus(view)`, `onClose`, `onExcalidrawViewClosed`) and manage their own `ea.targetView` explicitly.
|
||||
- Persisted sidepanel scripts are launched during plugin startup (e.g., Obsidian restart, plugin update) with `ea.targetView === null`. Scripts must handle this by deferring view-bound work until `onFocus` delivers a view; call `ea.setView(view)` when you decide to bind.
|
||||
- Persisted sidepanel scripts are restored lazily when the Excalidraw sidepanel initializes (often during startup, but not necessarily) with `ea.targetView === null`. Scripts must handle this by deferring view-bound work until `onFocus` delivers a view; call `ea.setView(view)` when you decide to bind. When `onFocus` supplies `null` or focus moves to a non-Excalidraw view, call `ea.setView(null)` to make the unbound state explicit and prevent later view operations from targeting a stale drawing.
|
||||
- Each `ea` instance may host a single `sidepanelTab`. This sidepanel tab is stored in `ea.sidepanelTab`. Create the tab with `ea.createSidepanelTab(title, persist=false, reveal=true)`; the returned `ea.sidepanelTab` exposes `contentEl`, `setContent`, `setTitle`, `setDisabled`, `setCloseCallback`, `open/close`, and focus lifecycle hooks. Note auto-reveal during tab creation via `ea.createSidepanelTab()` is disabled during plugin startup. You can reveal a tab with `ea.sidepanelTab?.open()`. You can persist with `ea.persistSidepanelTab()` (tabs are restored and scripts re-run on next startup). Close with `ea.sidepanelTab?.close()`.
|
||||
- Mobile UX: sidepanels slide in without disturbing canvas layout and are better for longer forms than floating modals. Prefer them for complex inputs, especially on phones.
|
||||
- Auto-closing patterns: For scripts that use sidepanels but perform operations that are single-`ExcalidrawView` relevant, they can call `ea.closeSidepanelTab()` after completing the operation, and/or inside `ea.sidepanelTab.onFocus = (view) => { if (view !== ea.targetView) { ea.sidepanelTab?.close(); } }` to shut down when the user leaves the originating view.
|
||||
@@ -64,14 +80,32 @@ To keep this training file concise, large external type definitions are not incl
|
||||
|
||||
#### **1. The Core Workflow: Handling Element Immutability**
|
||||
|
||||
* **Central Rule:** Elements in the Excalidraw scene are immutable and should never be modified directly. Always use the ExcalidrawAutomate (EA) "workbench" pattern for modifications.
|
||||
* **Central Rule:** Elements returned from the Excalidraw scene are immutable and should never be modified directly. EA owns a stateful, in-memory "workbench" (`elementsDict` and `imagesDict`) where a script stages one coherent persistent or temporary operation independently of the scene.
|
||||
* **The Workflow:**
|
||||
1. Get elements from the current view using `ea.getViewElements()` or `ea.getViewSelectedElements()`.
|
||||
2. Copy these elements into the EA workbench for editing using `ea.copyViewElementsToEAforEditing(elements)`.
|
||||
3. Modify the properties of the element copies that are now in the EA workbench (e.g., `ea.getElement(id).locked = true;`).
|
||||
4. Commit the changes back to the scene using `await ea.addElementsToView()`.
|
||||
1. Start an independent transaction with `ea.clear()`. This clears only the workbench; it does not delete scene elements or reset style.
|
||||
2. Read existing scene elements using `ea.getViewElements()` or `ea.getViewSelectedElements()`.
|
||||
3. To work with mutable copies of those same scene elements, copy them into the workbench with `ea.copyViewElementsToEAforEditing(elements)`. Their IDs are preserved.
|
||||
4. Modify the workbench copies retrieved by their original IDs (e.g., `ea.getElement(id).locked = true;`).
|
||||
5. For a persistent scene edit, commit once with `await ea.addElementsToView()`; saving is enabled by default. For temporary transformations such as export or preview preparation, pass the workbench elements to the relevant EA operation without committing them to the scene.
|
||||
6. Call `ea.clear()` after the operation to discard the workbench copies, preferably in a `finally` block when an awaited operation can fail.
|
||||
* **Temporary workbench example:**
|
||||
```javascript
|
||||
ea.clear();
|
||||
try {
|
||||
const sceneElements = ea.getViewElements();
|
||||
ea.copyViewElementsToEAforEditing(sceneElements);
|
||||
ea.getElement(pathId).opacity = 0;
|
||||
// elementsOverride replaces the export scene, so pass the complete workbench.
|
||||
const svg = await ea.createViewSVG({ elementsOverride: ea.getElements() });
|
||||
// Use svg. The live scene was never changed.
|
||||
} finally {
|
||||
ea.clear();
|
||||
}
|
||||
```
|
||||
* **`elementsOverride` is a complete replacement:** In `createViewSVG()`, this option replaces the view's element array; it is not merged with the scene and is not a patch by element ID. The array must contain every element that should appear in the SVG. When temporarily modifying an existing scene for export, the simplest safe workflow is to copy the complete desired export set into EA, modify the workbench copy, and pass `ea.getElements()` as the override.
|
||||
* **Identity is the boundary:** `copyViewElementsToEAforEditing()` is the standard way to obtain mutable, identity-preserving copies of existing scene elements for both persistent edits and temporary EA operations. By contrast, `ea.cloneElement()` and `ea.cloneElements()` deliberately generate new IDs and are only for creating genuine duplicate scene elements. Never use them to obtain editable workbench copies of existing elements.
|
||||
* **One workbench transaction at a time:** The workbench is shared mutable state on an EA instance. Do not interleave asynchronous preview/export preparation and scene mutation through the same workbench. Await the operation, then clear the workbench before starting another transaction.
|
||||
* **Deletion:** To delete an element, set its `isDeleted` property to `true` on the workbench copy (`ea.getElement(id).isDeleted = true;`) and then commit with `await ea.addElementsToView()`.
|
||||
* **Cleanup:** Use `ea.clear()` at the beginning of a script if you are creating a completely new set of elements, to ensure the EA workbench is empty and doesn't contain artifacts from a previous run.
|
||||
|
||||
#### **2. User Interaction: Prompts and Dialogs**
|
||||
|
||||
@@ -125,11 +159,27 @@ To keep this training file concise, large external type definitions are not incl
|
||||
* To permanently remove an element from the scene, set `element.isDeleted = true`.
|
||||
* **Image Handling:** When dealing with image elements, use `ea.getViewFileForImageElement(imageElement)` to get the corresponding `TFile` from the Obsidian vault. This is necessary for any logic that needs to read or manipulate the source image file.
|
||||
|
||||
#### **6.1. Tests in a Multi-Script Workspace**
|
||||
|
||||
* **Tests are part of implementation:** Add or update focused automated tests for behavior changes. When fixing a regression, reproduce it with a failing test first when practical.
|
||||
* **Co-locate by ownership:** Put script tests in `src/scripts/{slug}/__tests__/*.test.ts` and shared utility tests in `src/sharedUtils/__tests__/*.test.ts`. Do not maintain a separate root test tree that mirrors dozens of scripts.
|
||||
* **Never import executable entrypoints:** `main.ts` runs immediately against the globals injected by Obsidian. Keep it as a thin bootstrap and move testable orchestration to `run.ts` or another import-safe module.
|
||||
* **Use the universal runner:** Use Vitest. Run a focused suite while iterating, then run `npm run check`; the repository gate includes TypeScript, ESLint, and all test suites. Use `npm run test:watch` for continuous feedback.
|
||||
* **Test behavior, not bundler details:** Prefer pure domain functions and narrow fakes for `ea`, the Excalidraw API, Obsidian globals, timers, and DOM boundaries. Build and perform an Obsidian smoke test for integration behavior automation cannot prove.
|
||||
|
||||
#### **6.2. Per-Script Localization**
|
||||
|
||||
* **Catalogs belong to the script:** Store strings in `src/scripts/{slug}/lang/`, with one file per locale. Never create one language catalog shared across unrelated scripts.
|
||||
* **English defines the contract:** `lang/en.ts` is the typed source of truth. Maintain `de.ts`, `es.ts`, `fr.ts`, `ru.ts`, and `zh-cn.ts`; incomplete reviewed catalogs may rely on English fallback.
|
||||
* **Use the shared helper:** Register catalogs in `lang/index.ts` with `createTranslator`. Resolve the locale with `ea.obsidian.moment.locale()` and pass the translator into import-safe script logic.
|
||||
* **Interpolate by name:** Use placeholders such as `{count}` instead of string concatenation. Do not use dynamically constructed regular expressions for interpolation.
|
||||
* **Keep UI copy out of logic:** Add user-visible strings to the script catalog rather than embedding them in controllers, runners, or helpers.
|
||||
|
||||
#### **7. SVG and Image Export Approaches**
|
||||
Generating images (SVG/PNG) requires specific approaches depending on the context. Follow these three rules strictly to avoid performance issues and missing assets:
|
||||
1. **Exporting elements currently in the EA workbench:** Use `await ea.createSVG(null, ...)` or `await ea.createPNG(null, ...)` (passing `null` as the `templatePath`).
|
||||
2. **Exporting an Excalidraw file that is NOT currently open:** Pass the file path as the template to `createSVG` or `createPNG` (e.g., `await ea.createSVG(file.path, ...)`). This is the most reliable approach as ExcalidrawAutomate natively handles loading the scene, resolving embedded images, and instantiating loaders behind the scenes. **Do NOT attempt to manually read the file, reconstruct the scene, or load images into memory.**
|
||||
3. **Exporting the currently active `ExcalidrawView`:** Use `await ea.createViewSVG(...)`. This is specifically for the open view. You can use the `elementsOverride` parameter to inject temporary elements (like transparent sizing rectangles) into the exported image without modifying the actual scene.
|
||||
3. **Exporting the currently active `ExcalidrawView`:** Use `await ea.createViewSVG(...)`. This is specifically for the open view. Its `elementsOverride` parameter is a complete replacement for the exported element array, not an additive injection or a patch by ID. If supplied, include every existing or temporary element that should appear in the SVG. For temporary changes to existing elements, copy the complete desired export set into the EA workbench, modify it there, and pass `ea.getElements()`.
|
||||
|
||||
#### **8. Custom Pens and Perfect Freehand**
|
||||
|
||||
@@ -230,11 +280,23 @@ Example freedraw element carrying `customData.strokeOptions`:
|
||||
|
||||
## References
|
||||
The `references/` directory contains supporting documentation necessary for writing scripts:
|
||||
- `references/type-definitions.md`: Core type definitions for ExcalidrawAutomate.
|
||||
- `references/excalidraw-lib-functions.md`: Function signatures for `window.ExcalidrawLib`.
|
||||
- `references/startup-scripts.md`: ExcalidrawStartup script template and examples.
|
||||
- `references/api-usage-index.md`: A highly useful index mapping every API method (ea.*, api.*, ExcalidrawLib.*) to the specific example scripts that utilize them.
|
||||
- `references/scripts/`: A folder containing all the raw, real-world example scripts.
|
||||
- [type-definitions.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/type-definitions.md): Core type definitions for ExcalidrawAutomate.
|
||||
- [excalidraw-lib-functions.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/excalidraw-lib-functions.md): Function signatures for `window.ExcalidrawLib`.
|
||||
- [startup-scripts.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/startup-scripts.md): ExcalidrawStartup script template and examples.
|
||||
- [api-usage-index.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/AITrainingData/excalidraw-automate/references/api-usage-index.md): A highly useful index mapping every API method (ea.*, api.*, ExcalidrawLib.*) to the specific example scripts that utilize them.
|
||||
- [scripts/](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/docs/AITrainingData/excalidraw-automate/references/scripts): A folder containing all the raw, real-world example scripts.
|
||||
|
||||
## Publishing Workflow
|
||||
Use the normal repository contribution flow when publishing or updating scripts.
|
||||
The AI training material is maintained independently from publishing PRs; do not bundle regenerated training artifacts into the script PR.
|
||||
- Preview images must follow `scripts-{slug}.{ext}`, where `slug` uses lowercase `a-z`, `0-9`, and hyphens only.
|
||||
|
||||
- Add or update the script under [ea-scripts](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts).
|
||||
- Add or update the preview image under [images](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/images).
|
||||
- Keep [ea-scripts/index-new.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/index-new.md) manually curated; do not automate it.
|
||||
- Update [ea-scripts/directory-info.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/directory-info.json) in the same PR.
|
||||
- For script updates, refresh the matching entry's `mtime` in [ea-scripts/directory-info.json](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/directory-info.json) so the plugin can detect the newer local version.
|
||||
- Keep the PR focused on the script and its generated references.
|
||||
|
||||
### How to use the Script Examples
|
||||
If you need to implement a specific function (e.g., `ea.addElementsToView`), do NOT guess its implementation context. Instead:
|
||||
|
||||
@@ -9,23 +9,23 @@ 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 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)
|
||||
- **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), [VoronoiDiagramGenerator.mLine truncated
|
||||
- **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 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)
|
||||
- **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), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
|
||||
- **addMermaid**: [ExcaliAI.md](scripts/ExcaliAI.md)
|
||||
- **addRect**: [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Box Selected Elements.md](scripts/Box%20Selected%20Elements.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), [ExcaliAI.md](scripts/ExcaliAI.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Slideshow.md](scripts/Slideshow.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md)
|
||||
- **addText**: [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Linear Calendar Generator.md](scripts/Linear%20Calendar%20Generator.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Split text by lines.md](scripts/Split%20text%20by%20lines.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md)
|
||||
- **addToGroup**: [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), [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), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.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), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md)
|
||||
- **addToGroup**: [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), [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), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.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), [Text Aura.md](scripts/Text%20Aura.md), [Text to Path.md](scripts/Text%20to%20Path.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
|
||||
- **analyzeAIImage**: [ExcaliAI.md](scripts/ExcaliAI.md)
|
||||
- **attachInlineLinkSuggester**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
|
||||
- **canvas**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md)
|
||||
- **checkAndCreateFolder**: [Capture Note.md](scripts/Capture%20Note.md)
|
||||
- **checkForActiveSidepanelTabForScript**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Shade Master.md](scripts/Shade%20Master.md)
|
||||
- **clear**: [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md)
|
||||
- **clear**: [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
|
||||
- **cloneElement**: [Repeat Elements.md](scripts/Repeat%20Elements.md), [Repeat Texts.md](scripts/Repeat%20Texts.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), [Slideshow.md](scripts/Slideshow.md), [Text Aura.md](scripts/Text%20Aura.md)
|
||||
- **cloneElements**: [Capture Note.md](scripts/Capture%20Note.md)
|
||||
- **colorNameToHex**: [Darken background color.md](scripts/Darken%20background%20color.md), [Lighten background color.md](scripts/Lighten%20background%20color.md), [Repeat Elements.md](scripts/Repeat%20Elements.md)
|
||||
@@ -71,7 +71,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
|
||||
- **getPathForImageFileId**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
|
||||
- **getPolyBool**: [Boolean Operations.md](scripts/Boolean%20Operations.md)
|
||||
- **getSceneFromFile**: [Palette loader.md](scripts/Palette%20loader.md)
|
||||
- **getScriptSettings**: [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), [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), [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), [Icon Library.md](scripts/Icon%20Library.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), [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), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.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), [Shade Master.md](scripts/Shade%20Master.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md)
|
||||
- **getScriptSettings**: [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), [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), [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), [Icon Library.md](scripts/Icon%20Library.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), [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), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.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), [Shade Master.md](scripts/Shade%20Master.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
|
||||
- **getScriptSettingValue**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
|
||||
- **getSidepanelLeaf**: [Capture Note.md](scripts/Capture%20Note.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
|
||||
- **getSVGColorInfoForImgElement**: [Shade Master.md](scripts/Shade%20Master.md)
|
||||
@@ -79,7 +79,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
|
||||
- **getViewElements**: [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.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), [Elbow connectors.md](scripts/Elbow%20connectors.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.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), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Invert colors.md](scripts/Invert%20colors.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.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), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.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), [Slideshow.md](scripts/Slideshow.md), [Split Ellipse.md](scripts/Split%20Ellipse.md), [Text to Path.md](scripts/Text%20to%20Path.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [Uniform size.md](scripts/Uniform%20size.md)
|
||||
- **getViewFileForImageElement**: [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [PDF Page Text to Clipboard.md](scripts/PDF%20Page%20Text%20to%20Clipboard.md), [Shade Master.md](scripts/Shade%20Master.md)
|
||||
- **getViewSelectedElement**: [Capture Note.md](scripts/Capture%20Note.md), [Copy Selected Element Styles to Global.md](scripts/Copy%20Selected%20Element%20Styles%20to%20Global.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.md), [Set Stroke Width of Selected Elements.md](scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md), [Slideshow.md](scripts/Slideshow.md), [To Line.md](scripts/To%20Line.md)
|
||||
- **getViewSelectedElements**: [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 text to link with folder and alias.md](scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.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 Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.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), [Image Occlusion.md](scripts/Image%20Occlusion.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), [PDF Page Text to Clipboard.md](scripts/PDF%20Page%20Text%20to%20Clipboard.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), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.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), [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), [Uniform size.md](scripts/Uniform%20size.md), [Zoom to Fit Selected Elements.md](scripts/Zoom%20to%20Fit%20Selected%20Elements.md)
|
||||
- **getViewSelectedElements**: [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 text to link with folder and alias.md](scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.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 Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.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), [Image Occlusion.md](scripts/Image%20Occlusion.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), [PDF Page Text to Clipboard.md](scripts/PDF%20Page%20Text%20to%20Clipboard.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), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.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), [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), [Uniform size.md](scripts/Uniform%20size.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md), [Zoom to Fit Selected Elements.md](scripts/Zoom%20to%20Fit%20Selected%20Elements.md)
|
||||
- **imagesDict**: [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Image Occlusion.md](scripts/Image%20Occlusion.md)
|
||||
- **importSVG**: [ExcaliAI.md](scripts/ExcaliAI.md)
|
||||
- **intersectElementWithLine**: [Auto Layout.md](scripts/Auto%20Layout.md), [Box Each Selected Groups.md](scripts/Box%20Each%20Selected%20Groups.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), [Normalize Selected Arrows.md](scripts/Normalize%20Selected%20Arrows.md)
|
||||
@@ -90,7 +90,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
|
||||
- **measureText**: [Add Next Step in Process.md](scripts/Add%20Next%20Step%20in%20Process.md), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Text to Path.md](scripts/Text%20to%20Path.md)
|
||||
- **Modal**: [Image Occlusion.md](scripts/Image%20Occlusion.md)
|
||||
- **moveViewElementToZIndex**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.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)
|
||||
- **obsidian**: [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.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)
|
||||
- **obsidian**: [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [ExcaliAI.md](scripts/ExcaliAI.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.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), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
|
||||
- **onLinkClickHook**: [Slideshow.md](scripts/Slideshow.md)
|
||||
- **onSceneChangeHook**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Shade Master.md](scripts/Shade%20Master.md)
|
||||
- **openFileInNewOrAdjacentLeaf**: [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), [Capture Note.md](scripts/Capture%20Note.md), [Deconstruct selected elements into new drawing.md](scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.md), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md)
|
||||
@@ -100,7 +100,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
|
||||
- **reset**: [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md)
|
||||
- **saveScriptSettings**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
|
||||
- **selectElementsInView**: [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), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.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), [ExcaliMath.md](scripts/ExcaliMath.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Organic Line Legacy.md](scripts/Organic%20Line%20Legacy.md), [Organic Line.md](scripts/Organic%20Line.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Select Elements of Type.md](scripts/Select%20Elements%20of%20Type.md), [Select Similar Elements.md](scripts/Select%20Similar%20Elements.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), [Slideshow.md](scripts/Slideshow.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md)
|
||||
- **setScriptSettings**: [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), [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), [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), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.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), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.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), [Shade Master.md](scripts/Shade%20Master.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md)
|
||||
- **setScriptSettings**: [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), [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), [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), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Lighten background color.md](scripts/Lighten%20background%20color.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), [Palette loader.md](scripts/Palette%20loader.md), [Palm Guard.md](scripts/Palm%20Guard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.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), [Shade Master.md](scripts/Shade%20Master.md), [Text to Sticky Notes.md](scripts/Text%20to%20Sticky%20Notes.md), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
|
||||
- **setScriptSettingValue**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
|
||||
- **setStrokeSharpness**: [Scribble Helper.md](scripts/Scribble%20Helper.md)
|
||||
- **setValue**: [ExcaliAI.md](scripts/ExcaliAI.md)
|
||||
@@ -110,7 +110,7 @@ This index maps methods and properties from ExcalidrawAutomate (`ea`), Excalidra
|
||||
- **showColorPicker**: [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Shade Master.md](scripts/Shade%20Master.md)
|
||||
- **sidepanelTab**: [Icon Library.md](scripts/Icon%20Library.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Shade Master.md](scripts/Shade%20Master.md)
|
||||
- **skipSidepanelScriptRestore**: [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md)
|
||||
- **style**: [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), [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), [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), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.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), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.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 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)
|
||||
- **style**: [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), [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), [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), [Crop Vintage Mask.md](scripts/Crop%20Vintage%20Mask.md), [Ellipse Selected Elements.md](scripts/Ellipse%20Selected%20Elements.md), [ExcaliAI.md](scripts/ExcaliAI.md), [Full-Year Calendar Generator.md](scripts/Full-Year%20Calendar%20Generator.md), [Golden Ratio.md](scripts/Golden%20Ratio.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), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Scribble Helper.md](scripts/Scribble%20Helper.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 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), [VoronoiDiagramGenerator.md](scripts/VoronoiDiagramGenerator.md)
|
||||
- **targetView**: [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), [Capture Note.md](scripts/Capture%20Note.md), [Comicbook Callout Editor.md](scripts/Comicbook%20Callout%20Editor.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), [Excalidraw Writing Machine.md](scripts/Excalidraw%20Writing%20Machine.md), [ExcaliMath.md](scripts/ExcaliMath.md), [Folder Note Core - Make Current Drawing a Folder.md](scripts/Folder%20Note%20Core%20-%20Make%20Current%20Drawing%20a%20Folder.md), [Golden Ratio.md](scripts/Golden%20Ratio.md), [Icon Library.md](scripts/Icon%20Library.md), [Image Occlusion.md](scripts/Image%20Occlusion.md), [Mindmap Builder.js.md](scripts/Mindmap%20Builder.js.md), [Palm Guard.md](scripts/Palm%20Guard.md), [PDF Page Text to Clipboard.md](scripts/PDF%20Page%20Text%20to%20Clipboard.md), [Printable Layout Wizard.md](scripts/Printable%20Layout%20Wizard.md), [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md), [Scribble Helper.md](scripts/Scribble%20Helper.md), [Shade Master.md](scripts/Shade%20Master.md), [Slideshow.md](scripts/Slideshow.md), [Text to Path.md](scripts/Text%20to%20Path.md)
|
||||
- **tex2dataURL**: [Reset LaTeX Size.md](scripts/Reset%20LaTeX%20Size.md)
|
||||
- **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)
|
||||
|
||||
@@ -84,7 +84,7 @@ export declare const getCommonBoundingBox: (elements: readonly ExcalidrawElement
|
||||
/* ************************************** */
|
||||
/* @excalidraw/element/groups -> node_modules/@zsviczian/excalidraw/types/element/src/groups.d.ts */
|
||||
/* ************************************** */
|
||||
export declare const getMaximumGroups: (elements: ExcalidrawElement[], elementsMap: ElementsMap) => ExcalidrawElement[][];
|
||||
export declare const getMaximumGroups: <T extends NonDeletedExcalidrawElement | ExcalidrawElement>(elements: T[], elementsMap: ElementsMap) => T[][];
|
||||
|
||||
/* ************************************** */
|
||||
/* @excalidraw/element/textMeasurements -> node_modules/@zsviczian/excalidraw/types/element/src/textMeasurements.d.ts */
|
||||
@@ -101,7 +101,7 @@ export declare const wrapText: (text: string, font: FontString, maxWidth: number
|
||||
/* @excalidraw/element/textElement -> node_modules/@zsviczian/excalidraw/types/element/src/textElement.d.ts */
|
||||
/* ************************************** */
|
||||
export declare const getBoundTextMaxWidth: (container: ExcalidrawElement, boundTextElement: ExcalidrawTextElement | null) => number;
|
||||
export declare const getContainerElement: (element: ExcalidrawTextElement | null, elementsMap: ElementsMap) => ExcalidrawTextContainer | null;
|
||||
export declare const getContainerElement: <T extends ExcalidrawTextElement, R extends ExcalidrawTextContainer>(element: T | null, elementsMap: ElementsMap) => R | null;
|
||||
|
||||
/* ************************************** */
|
||||
/* ./components/TTDDialog/MermaidToExcalidrawLib -> node_modules/@zsviczian/excalidraw/types/excalidraw/components/TTDDialog/MermaidToExcalidrawLib.d.ts */
|
||||
@@ -223,21 +223,20 @@ export declare const TTDDialog: {
|
||||
/* ************************************** */
|
||||
/* ./components/TTDDialog/utils/TTDStreamFetch -> node_modules/@zsviczian/excalidraw/types/excalidraw/components/TTDDialog/utils/TTDStreamFetch.d.ts */
|
||||
/* ************************************** */
|
||||
export declare function parseSSEStream(reader: ReadableStreamDefaultReader<Uint8Array>): AsyncGenerator<string, void, unknown>;
|
||||
export declare function TTDStreamFetch(options: StreamingOptions): Promise<TTTDDialog.OnTextSubmitRetValue>;
|
||||
|
||||
/* ************************************** */
|
||||
/* ./actions/actionCanvas -> node_modules/@zsviczian/excalidraw/types/excalidraw/actions/actionCanvas.d.ts */
|
||||
/* ./viewport -> node_modules/@zsviczian/excalidraw/types/excalidraw/viewport.d.ts */
|
||||
/* ************************************** */
|
||||
export declare const zoomToFitBounds: ({ bounds, appState, canvasOffsets, fitToViewport, viewportZoomFactor, minZoom, maxZoom, }: {
|
||||
export declare const zoomToFitBounds: ({ bounds, appState, canvasOffsets, fit, minZoom, maxZoom, steppedZoom, }: {
|
||||
bounds: SceneBounds;
|
||||
canvasOffsets?: Offsets;
|
||||
appState: Readonly<AppState>;
|
||||
/** whether to fit content to viewport (beyond >100%) */
|
||||
fitToViewport: boolean;
|
||||
/** zoom content to cover X of the viewport, when fitToViewport=true */
|
||||
viewportZoomFactor?: number;
|
||||
fit?: SetViewportOptions["fit"];
|
||||
minZoom?: number;
|
||||
maxZoom?: number;
|
||||
steppedZoom?: boolean;
|
||||
}) => {
|
||||
appState: {
|
||||
scrollX: number;
|
||||
@@ -254,4 +253,36 @@ export declare const DiagramToCodePlugin: (props: {
|
||||
/* ************************************** */
|
||||
export declare const CommandPalette: ((props: CommandPaletteProps) => import("react/jsx-runtime").JSX.Element | null) & {
|
||||
defaultItems: typeof defaultItems;
|
||||
|
||||
/* ************************************** */
|
||||
/* ./obsidianExcalidrawHost -> node_modules/@zsviczian/excalidraw/types/excalidraw/obsidianExcalidrawHost.d.ts */
|
||||
/* ************************************** */
|
||||
export declare const OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION: 2;
|
||||
/** Keyboard-blocking lifecycle returned by the host's inline suggester. */
|
||||
export interface ObsidianKeyBlocker {
|
||||
isBlockingKeys(): boolean;
|
||||
close(): void;
|
||||
}
|
||||
/** Plugin-wide capabilities consumed by the Excalidraw package. */
|
||||
export interface ObsidianExcalidrawHostAdapter {
|
||||
readonly protocolVersion: typeof OBSIDIAN_EXCALIDRAW_HOST_PROTOCOL_VERSION;
|
||||
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): ObsidianKeyBlocker;
|
||||
}
|
||||
/** Idempotent cleanup returned when a package host is configured. */
|
||||
export type ObsidianExcalidrawHostDisposer = () => void;
|
||||
```
|
||||
@@ -3378,11 +3378,36 @@ const zoomToFit = (mode) => {
|
||||
elementID: sel.id,
|
||||
level: nextLevel
|
||||
}
|
||||
api().scrollToContent([sel], {
|
||||
fitToViewport: true,
|
||||
viewportZoomFactor: getZoom(nextLevel),
|
||||
animate: true
|
||||
});
|
||||
|
||||
const targetZoom = getZoom(nextLevel);
|
||||
|
||||
// Fallback for older versions vs new Excalidraw 2.26.0+ Viewport API
|
||||
if (!ea.verifyMinimumPluginVersion("2.26.0")) {
|
||||
api().scrollToContent([sel], {
|
||||
fitToViewport: true,
|
||||
viewportZoomFactor: targetZoom,
|
||||
animate: true
|
||||
});
|
||||
} else {
|
||||
// For the new API, we calculate a target rect centered on the element
|
||||
// with dimensions that will force 'fit: "contain"' to reach our target zoom.
|
||||
const appState = api().getAppState();
|
||||
const targetW = appState.width / targetZoom;
|
||||
const targetH = appState.height / targetZoom;
|
||||
const cx = sel.x + sel.width / 2;
|
||||
const cy = sel.y + sel.height / 2;
|
||||
|
||||
api().setViewport({
|
||||
target: {
|
||||
x: cx - targetW / 2,
|
||||
y: cy - targetH / 2,
|
||||
width: targetW,
|
||||
height: targetH
|
||||
},
|
||||
fit: "contain",
|
||||
animation: true
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3411,10 +3436,20 @@ const focusSelected = () => {
|
||||
|
||||
if (!sel) return;
|
||||
|
||||
api().scrollToContent(sel, {
|
||||
fitToContent: false,
|
||||
animate: true,
|
||||
});
|
||||
// Fallback for older versions vs new Excalidraw 2.26.0+ Viewport API
|
||||
if (!ea.verifyMinimumPluginVersion("2.26.0")) {
|
||||
api().scrollToContent(sel, {
|
||||
fitToContent: false,
|
||||
animate: true,
|
||||
});
|
||||
} else {
|
||||
// fit: "none" recenters at the current zoom without changing it
|
||||
api().setViewport({
|
||||
target: [sel],
|
||||
fit: "none",
|
||||
animation: true
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const getMindmapOrder = (node) => {
|
||||
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
/*
|
||||
This script generates a Voronoi diagram from selected elements on the drawing canvas.
|
||||
|
||||
The following parameters can be set in 'Voronoi Settings' window pop-up once the script is started:
|
||||
- Frame width (default: 100)
|
||||
- Roughness (default: 0)
|
||||
- Stroke width (default: 2)
|
||||
- Grouping (default: checked)
|
||||
|
||||
Setting parameters could be set back to default values by click on button 'Default'.
|
||||
Check info button for howto help during applying the script.
|
||||
|
||||
See background information about Voronoi diagram at Wikipedia : https://en.wikipedia.org/wiki/Voronoi_diagram
|
||||
|
||||
Comments and discussion are welcomed in the Sketch-Your-Mind community: https://community.sketch-your-mind.com
|
||||
|
||||
```js*/
|
||||
// ExcalidrawAutomate: Voronoi Diagram Generator
|
||||
ea.clear();
|
||||
|
||||
const DEFAULTS = {
|
||||
frameWidth: 100,
|
||||
roughness: 0,
|
||||
strokeWidth: 2,
|
||||
groupVoronoi: true
|
||||
};
|
||||
|
||||
let config = ea.getScriptSettings() || { ...DEFAULTS };
|
||||
|
||||
// --- UI SETTINGS MODAL ---
|
||||
async function openSettings() {
|
||||
return new Promise((resolve) => {
|
||||
const modal = new ea.obsidian.Modal(app);
|
||||
modal.contentEl.style.padding = "20px";
|
||||
|
||||
// Header container with Title and Info Button
|
||||
const headerContainer = modal.contentEl.createDiv();
|
||||
headerContainer.style.display = "flex";
|
||||
headerContainer.style.justifyContent = "space-between";
|
||||
headerContainer.style.alignItems = "center";
|
||||
headerContainer.style.marginBottom = "20px";
|
||||
|
||||
headerContainer.createEl("h2", { text: "Settings - Voronoi Diagram Generator", cls: "mod-header" }).style.margin = "0";
|
||||
|
||||
// Info button using Obsidian's native icon
|
||||
const btnInfo = headerContainer.createEl("button", { cls: "clickable-icon" });
|
||||
btnInfo.setAttribute("aria-label", "Information & Help");
|
||||
btnInfo.innerHTML = ea.obsidian.getIcon("info").outerHTML;
|
||||
|
||||
// Info modal content on click
|
||||
btnInfo.onclick = () => {
|
||||
const infoModal = new ea.obsidian.Modal(app);
|
||||
infoModal.contentEl.style.padding = "20px";
|
||||
infoModal.contentEl.createEl("h3", { text: "About - Voronoi Diagram Generator" });
|
||||
|
||||
// Native Obsidian Icon as HTML string
|
||||
const chatIcon = ea.obsidian.getIcon("message-square").outerHTML;
|
||||
|
||||
const p = infoModal.contentEl.createEl("p");
|
||||
p.innerHTML = `
|
||||
This script generates a Voronoi diagram from selected elements on the drawing canvas.<br><br>
|
||||
<h4 style="margin: 5px 0 5px 0; font-size: 1.1em;">HowTo & Parameters:</h4>
|
||||
<div line-height: 1.4;">
|
||||
<div style="margin-bottom: 10px;">1. <b>Select</b> at least 2 elements on your canvas.</div>
|
||||
<div style="margin-bottom: 4px;">2. <b>Run</b> the script and adjust your settings:</div>
|
||||
<div style="margin: 2px 0 10px 15px; line-height: 1.2;">
|
||||
- <b>Frame width:</b> Spacing around the diagram.<br>
|
||||
- <b>Roughness:</b> Hand-drawn effect (0-3).<br>
|
||||
- <b>Stroke width:</b> Line thickness.<br>
|
||||
- <b>Grouping:</b> Group generated cells together.<br>
|
||||
</div>
|
||||
<div style="margin-bottom: 15px;">3. Click <b>OK</b> to generate.</div>
|
||||
</div><br>
|
||||
<span style="display: inline-flex; align-items: center; gap: 6px; vertical-align: middle;"> ${chatIcon} Feedback & chat: <a href="https://community.sketch-your-mind.com" target="_blank">Sketch Your Mind Community</a>
|
||||
</span>
|
||||
`;
|
||||
infoModal.open();
|
||||
};
|
||||
|
||||
const inputs = {};
|
||||
|
||||
// Helper function to create input rows
|
||||
const createInput = (label, key, type = "number") => {
|
||||
const container = modal.contentEl.createDiv();
|
||||
container.style.marginBottom = "15px";
|
||||
|
||||
container.createEl("label", { text: label });
|
||||
const input = container.createEl("input", { type: type });
|
||||
input.style.display = "block";
|
||||
input.style.marginTop = "5px";
|
||||
input.value = config[key];
|
||||
input.onchange = (e) => config[key] = type === "number" ? Number(e.target.value) : e.target.checked;
|
||||
inputs[key] = input;
|
||||
};
|
||||
|
||||
createInput("Frame width:", "frameWidth");
|
||||
createInput("Roughness (0-3):", "roughness");
|
||||
createInput("Stroke width:", "strokeWidth");
|
||||
|
||||
const checkContainer = modal.contentEl.createDiv();
|
||||
checkContainer.style.marginBottom = "25px";
|
||||
checkContainer.createEl("label", { text: "Grouping: " });
|
||||
inputs.groupVoronoi = checkContainer.createEl("input", { type: "checkbox" });
|
||||
inputs.groupVoronoi.checked = config.groupVoronoi;
|
||||
inputs.groupVoronoi.onchange = (e) => config.groupVoronoi = e.target.checked;
|
||||
|
||||
// Button container
|
||||
const btnContainer = modal.contentEl.createDiv();
|
||||
btnContainer.style.display = "flex";
|
||||
btnContainer.style.gap = "10px";
|
||||
btnContainer.style.justifyContent = "flex-end";
|
||||
|
||||
const btnDefault = btnContainer.createEl("button", { text: "Default" });
|
||||
const btnOk = btnContainer.createEl("button", { text: "OK" });
|
||||
|
||||
btnDefault.onclick = () => {
|
||||
config = { ...DEFAULTS };
|
||||
inputs.frameWidth.value = config.frameWidth;
|
||||
inputs.roughness.value = config.roughness;
|
||||
inputs.strokeWidth.value = config.strokeWidth;
|
||||
inputs.groupVoronoi.checked = config.groupVoronoi;
|
||||
new Notice("Settings reset to default");
|
||||
};
|
||||
|
||||
btnOk.onclick = () => {
|
||||
ea.setScriptSettings(config);
|
||||
modal.close();
|
||||
resolve(true);
|
||||
};
|
||||
|
||||
modal.open();
|
||||
});
|
||||
}
|
||||
|
||||
// Wait for user to configure settings
|
||||
const proceed = await openSettings();
|
||||
if (!proceed) return;
|
||||
|
||||
// --- ALGORITHM & EXECUTION ---
|
||||
const els = ea.getViewSelectedElements();
|
||||
|
||||
if (els.length < 2) {
|
||||
new Notice("Please select at least two items!");
|
||||
return;
|
||||
}
|
||||
|
||||
const seeds = els.map(el => ({ x: el.x + el.width / 2, y: el.y + el.height / 2 }));
|
||||
|
||||
if (seeds.length < 2) {
|
||||
new Notice("Please select at least two items!");
|
||||
return;
|
||||
}
|
||||
|
||||
const minX = Math.min(...seeds.map(s => s.x)) - config.frameWidth;
|
||||
const minY = Math.min(...seeds.map(s => s.y)) - config.frameWidth;
|
||||
const maxX = Math.max(...seeds.map(s => s.x)) + config.frameWidth;
|
||||
const maxY = Math.max(...seeds.map(s => s.y)) + config.frameWidth;
|
||||
|
||||
const bbox = [
|
||||
{ x: minX, y: minY },
|
||||
{ x: maxX, y: minY },
|
||||
{ x: maxX, y: maxY },
|
||||
{ x: minX, y: maxY }
|
||||
];
|
||||
|
||||
function clipPolygon(poly, p1, p2) {
|
||||
const mid = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
|
||||
const n = { x: p2.x - p1.x, y: p2.y - p1.y };
|
||||
const isInside = (p) => (p.x - mid.x) * n.x + (p.y - mid.y) * n.y <= 0;
|
||||
|
||||
const intersect = (a, b) => {
|
||||
const num = (a.x - mid.x) * n.x + (a.y - mid.y) * n.y;
|
||||
const den = (b.x - a.x) * n.x + (b.y - a.y) * n.y;
|
||||
if (den === 0) return null;
|
||||
const t = -num / den;
|
||||
return { x: a.x + t * (b.x - a.x), y: a.y + t * (b.y - a.y) };
|
||||
};
|
||||
|
||||
const result = [];
|
||||
for (let i = 0; i < poly.length; i++) {
|
||||
const cur = poly[i];
|
||||
const prev = poly[(i - 1 + poly.length) % poly.length];
|
||||
const curIn = isInside(cur);
|
||||
const prevIn = isInside(prev);
|
||||
|
||||
if (curIn !== prevIn) {
|
||||
const ix = intersect(prev, cur);
|
||||
if (ix) result.push(ix);
|
||||
}
|
||||
if (curIn) result.push(cur);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const polygons = seeds.map((s, i) => {
|
||||
let poly = [...bbox];
|
||||
seeds.forEach((_, j) => {
|
||||
if (i !== j) poly = clipPolygon(poly, seeds[i], seeds[j]);
|
||||
});
|
||||
return poly;
|
||||
});
|
||||
|
||||
ea.style.roughness = config.roughness;
|
||||
ea.style.strokeWidth = config.strokeWidth;
|
||||
ea.style.backgroundColor = "transparent";
|
||||
|
||||
const ids = [];
|
||||
|
||||
for (const poly of polygons) {
|
||||
if (poly.length < 3) continue;
|
||||
const points = poly.map(p => [p.x, p.y]);
|
||||
points.push(points[0]);
|
||||
ids.push(ea.addLine(points));
|
||||
}
|
||||
|
||||
if (config.groupVoronoi && ids.length > 0) {
|
||||
ea.addToGroup(ids);
|
||||
}
|
||||
|
||||
await ea.addElementsToView(false, false);
|
||||
|
||||
// Clear selection so nothing remains selected on the canvas
|
||||
const view = app.workspace.activeLeaf.view; if (view && view.excalidrawAPI) { view.excalidrawAPI.updateScene({ appState: { selectedElementIds: {} } }); }
|
||||
|
||||
new Notice("Voronoi diagram created!");
|
||||
|
||||
```
|
||||
@@ -1,13 +1,23 @@
|
||||
# Excalidraw Startup Script
|
||||
|
||||
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs automatically when the Excalidraw plugin is loaded to Obsidian. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
|
||||
|
||||
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs once per Excalidraw plugin load using the plugin-global EA and utils.executionSource === 'plugin-startup'. Use ea.registerCleanup() for external listeners, timers, observers, or subscriptions that must be released when Excalidraw unloads. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
|
||||
|
||||
### Template
|
||||
```js
|
||||
/*
|
||||
#exclude
|
||||
```js*/
|
||||
/**
|
||||
* Startup scripts receive the plugin-global EA for the plugin lifetime and
|
||||
* utils.executionSource === "plugin-startup". Register cleanup for resources
|
||||
* outside EA so plugin reload/unload cannot accumulate them.
|
||||
*/
|
||||
// const ref = app.workspace.on("file-open", (file) => {});
|
||||
// ea.registerCleanup(() => app.workspace.offref(ref));
|
||||
//
|
||||
// const interval = window.setInterval(() => {}, 1000);
|
||||
// ea.registerCleanup(() => window.clearInterval(interval));
|
||||
|
||||
/**
|
||||
* If set, this callback is triggered when the user closes an Excalidraw view.
|
||||
* onViewUnloadHook: (view: ExcalidrawView) => void = null;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -17,11 +17,49 @@ You will be able to access your scripts from Excalidraw via the Obsidian Command
|
||||
|
||||

|
||||
|
||||
This will allow you to assign hotkeys to your favorite scripts just like to any other Obsidian command.
|
||||
|
||||

|
||||
|
||||
## Script development
|
||||
This will allow you to assign hotkeys to your favorite scripts just like to any other Obsidian command.
|
||||
|
||||

|
||||
|
||||
## EA script execution lifecycles
|
||||
|
||||
`utils.executionSource` describes why the current top-level script invocation
|
||||
happened. It does not indicate whether the source was compiled previously,
|
||||
whether the script has run before, or whether runtime state was retained.
|
||||
|
||||
| Trigger | `utils.executionSource` | EA received | Approximate lifetime |
|
||||
| --- | --- | --- | --- |
|
||||
| Script button, command, or hotkey | `manual` | fresh view EA | existing ordinary script/view lifecycle |
|
||||
| Plugin startup script | `plugin-startup` | global plugin EA | plugin lifetime |
|
||||
| `registerAutostart()` attachment | `view-autostart` | fresh view-local EA | view lifetime |
|
||||
| Persisted sidepanel reconstruction | `sidepanel-restore` | sidepanel host EA | sidepanel tab lifetime |
|
||||
| Sidepanel script reload | `sidepanel-reload` | reloaded sidepanel host EA | sidepanel tab lifetime |
|
||||
| `excalidraw-onload-script` | `drawing-onload` | view-local EA | drawing/view lifetime |
|
||||
|
||||
Compilation caching is transparent: compiled JavaScript may be shared while
|
||||
unchanged, but each invocation retains its existing EA ownership and execution
|
||||
semantics. Manual execution remains repeatable even for a script that also uses
|
||||
view autostart.
|
||||
|
||||
Use `ea.registerCleanup()` for resources that EA does not own directly:
|
||||
|
||||
```js
|
||||
const ref = app.workspace.on("file-open", handler);
|
||||
ea.registerCleanup(() => app.workspace.offref(ref));
|
||||
|
||||
window.addEventListener("resize", handler);
|
||||
ea.registerCleanup(() => window.removeEventListener("resize", handler));
|
||||
|
||||
const interval = window.setInterval(callback, 1000);
|
||||
ea.registerCleanup(() => window.clearInterval(interval));
|
||||
```
|
||||
|
||||
Cleanup runs when that particular EA instance is destroyed, so its exact
|
||||
lifetime depends on whether it is the plugin-startup EA, a view-local EA, or a
|
||||
sidepanel host EA. The function returned by `registerCleanup()` unregisters the
|
||||
callback without executing it.
|
||||
|
||||
## Script development
|
||||
An Excalidraw script will automatically receive two objects:
|
||||
- `ea`: The Script Engine will initialize the `ea` object including setting the active view to the View from which the script was called.
|
||||
- `utils`: I have borrowed functions exposed on utils from [QuickAdd](https://github.com/chhoumann/quickadd/blob/master/docs/QuickAddAPI.md), though currently not all QuickAdd utility functions are implemented in Excalidraw. As of now, these are the available functions. See the example below for details.
|
||||
|
||||
@@ -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.27.0-beta.0",
|
||||
"version": "2.27.0-rc.2",
|
||||
"minAppVersion": "1.8.7",
|
||||
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
Generated
+4
-33
@@ -13,7 +13,7 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.120",
|
||||
"@zsviczian/excalidraw": "0.18.130",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
@@ -53,7 +53,6 @@
|
||||
"@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",
|
||||
"cssnano": "^6.0.2",
|
||||
"eslint": "^9.39.4",
|
||||
@@ -5255,9 +5254,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@zsviczian/excalidraw": {
|
||||
"version": "0.18.120",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.120.tgz",
|
||||
"integrity": "sha512-J0J3pYZZIRabdkWkZ7OH6VsJBE/dfZmNSJtL6X/lRIY/NEV52x3H3PMkx17z9Siu4D2C82qpNibFnltVkZJmow==",
|
||||
"version": "0.18.130",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.130.tgz",
|
||||
"integrity": "sha512-+qsJ0B/qFWkT8ZZrgPn+FodZPko93NLIRsCrVqLG5fKFAqoEY22/IXcIRc72jion6D0XkN4wbJtBu/l6HtL7GQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@braintree/sanitize-url": "6.0.2",
|
||||
@@ -5342,26 +5341,6 @@
|
||||
"integrity": "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@zsviczian/rollup-plugin-postprocess": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/rollup-plugin-postprocess/-/rollup-plugin-postprocess-1.0.3.tgz",
|
||||
"integrity": "sha512-W3t9TgbjNnZ07h+Vg78qAo0lFkYoovdlp5ojbiSP6aMswDIDdkvwrt4qQataN2kJ9UlkcvKB0pwsd1NWze8bqg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"magic-string": "^0.25.7"
|
||||
}
|
||||
},
|
||||
"node_modules/@zsviczian/rollup-plugin-postprocess/node_modules/magic-string": {
|
||||
"version": "0.25.9",
|
||||
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.9.tgz",
|
||||
"integrity": "sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"sourcemap-codec": "^1.4.8"
|
||||
}
|
||||
},
|
||||
"node_modules/acorn": {
|
||||
"version": "8.16.0",
|
||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
|
||||
@@ -12205,14 +12184,6 @@
|
||||
"source-map": "^0.6.0"
|
||||
}
|
||||
},
|
||||
"node_modules/sourcemap-codec": {
|
||||
"version": "1.4.8",
|
||||
"resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz",
|
||||
"integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==",
|
||||
"deprecated": "Please use @jridgewell/sourcemap-codec instead",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/speech-rule-engine": {
|
||||
"version": "4.1.4",
|
||||
"resolved": "https://registry.npmjs.org/speech-rule-engine/-/speech-rule-engine-4.1.4.tgz",
|
||||
|
||||
+1
-2
@@ -30,7 +30,7 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.120",
|
||||
"@zsviczian/excalidraw": "0.18.130",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
@@ -70,7 +70,6 @@
|
||||
"@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",
|
||||
"cssnano": "^6.0.2",
|
||||
"eslint": "^9.39.4",
|
||||
|
||||
+11
-29
@@ -8,12 +8,10 @@ import copy from "rollup-plugin-copy";
|
||||
import typescript from "@rollup/plugin-typescript";
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import postprocess from '@zsviczian/rollup-plugin-postprocess';
|
||||
import cssnano from 'cssnano';
|
||||
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
|
||||
@@ -85,16 +83,6 @@ 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);
|
||||
|
||||
// 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");
|
||||
@@ -133,7 +121,7 @@ const packageString = isLib
|
||||
' ' + pako_pkg + '\n' +
|
||||
' return module.exports;\n' +
|
||||
'})();\n' +
|
||||
// Define the dependency-free inflater before React participates in bootstrap.
|
||||
// Define the dependency-free inflater used by compressed runtime payloads.
|
||||
'const unpackBase64Deflate = (b64) => {\n' +
|
||||
' const binStr = atob(b64);\n' +
|
||||
' const len = binStr.length;\n' +
|
||||
@@ -142,11 +130,7 @@ 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, 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,
|
||||
@@ -168,7 +152,7 @@ const packageString = isLib
|
||||
//Moved here since the Obsidian code scanner warning to avoid unnecessary logging appears
|
||||
//to users, creating the impression that there is unnecessary logging. There isn't.
|
||||
//Errors and debug information is logged. Nothing else.
|
||||
`const consoleLog = console["log"].bind(console);\n` +
|
||||
`const consoleLog = console["log"].bind(console);\n` +
|
||||
//Obsidian code scanner fails if document.createElement rule is ignored using the eslint-ignore comment
|
||||
//the code scanner also does not allow creating style elements and guides plugins to use style.css
|
||||
//the code scanner does not recognize valid cases such as creating canvas elements for image generation
|
||||
@@ -195,8 +179,13 @@ const BASE_CONFIG = {
|
||||
'@lezer/lr',
|
||||
'obsidian',
|
||||
'@zsviczian/excalidraw',
|
||||
'react',
|
||||
'react-dom'
|
||||
...(isLib ? [
|
||||
'react',
|
||||
'react-dom',
|
||||
'react-dom/client',
|
||||
'react/jsx-runtime',
|
||||
'react/jsx-dev-runtime',
|
||||
] : []),
|
||||
],
|
||||
};
|
||||
|
||||
@@ -227,6 +216,7 @@ const BUILD_CONFIG = {
|
||||
format: 'cjs',
|
||||
exports: 'default',
|
||||
inlineDynamicImports: true, // Add this line only
|
||||
banner: packageString,
|
||||
},
|
||||
plugins: getRollupPlugins(
|
||||
{
|
||||
@@ -241,21 +231,13 @@ const BUILD_CONFIG = {
|
||||
comments: false, // Remove all comments
|
||||
},
|
||||
}),
|
||||
postprocess([
|
||||
[
|
||||
/(var[^;]*?),\s*React\s*=\s*require\(["']react["']\)([^;]*;)/,
|
||||
(_, g1, g2) => `${g1}${g2}${packageString}`
|
||||
],
|
||||
]),
|
||||
/*visualizer({
|
||||
filename: 'bundle-analysis.html',
|
||||
open: true, // Automatically opens in your browser when the build finishes
|
||||
gzipSize: true,
|
||||
brotliSize: true,
|
||||
}),*/
|
||||
] : [
|
||||
postprocess([[/var React = require\('react'\);/, packageString]]),
|
||||
]),
|
||||
] : []),
|
||||
copy({
|
||||
targets: [{ src: 'manifest.json', dest: DIST_FOLDER }],
|
||||
verbose: true,
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
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();
|
||||
}
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,304 @@
|
||||
#!/usr/bin/env bash
|
||||
# generate-repository-zip.sh
|
||||
#
|
||||
# Run from the root of a repository:
|
||||
#
|
||||
# bash generate-repository-zip.sh
|
||||
#
|
||||
# Generates:
|
||||
# ./repository.zip
|
||||
#
|
||||
# The ZIP preserves the repository-relative directory structure while excluding:
|
||||
# - node_modules, dist, and other ignored folders
|
||||
# - __MACOSX folders
|
||||
# - .DS_Store and other ignored filenames
|
||||
# - common binary/media/archive/executable file types
|
||||
# - files detected as binary even if their extension is unknown
|
||||
#
|
||||
# Requirements:
|
||||
# - bash
|
||||
# - find
|
||||
# - file
|
||||
# - zip
|
||||
#
|
||||
# Edit IGNORE_DIRS, IGNORE_FILENAMES, and IGNORE_EXTENSIONS below to customize.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
OUTPUT="repository.zip"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Folder exclusions
|
||||
# ---------------------------------------------------------------------------
|
||||
# Folder names are matched at any depth.
|
||||
IGNORE_DIRS=(
|
||||
".git"
|
||||
".svn"
|
||||
".hg"
|
||||
|
||||
"node_modules"
|
||||
"dist"
|
||||
|
||||
".next"
|
||||
".nuxt"
|
||||
".cache"
|
||||
".parcel-cache"
|
||||
".turbo"
|
||||
".idea"
|
||||
".vscode"
|
||||
".tools"
|
||||
|
||||
"coverage"
|
||||
"build"
|
||||
"out"
|
||||
"output"
|
||||
|
||||
"secrets"
|
||||
".claude"
|
||||
|
||||
"__MACOSX"
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Filename exclusions
|
||||
# ---------------------------------------------------------------------------
|
||||
# Exact filenames are matched at any depth.
|
||||
IGNORE_FILENAMES=(
|
||||
".DS_Store"
|
||||
"Thumbs.db"
|
||||
|
||||
"REPOSITORY_STRUCTURE.md"
|
||||
"REPOSITORY_CONTENTS.md"
|
||||
|
||||
# Never package a previously generated repository archive.
|
||||
"repository.zip"
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# File-type exclusions
|
||||
# ---------------------------------------------------------------------------
|
||||
# Extensions are lowercase and include the leading dot.
|
||||
IGNORE_EXTENSIONS=(
|
||||
# Images
|
||||
".png"
|
||||
".jpg"
|
||||
".jpeg"
|
||||
".gif"
|
||||
".webp"
|
||||
".bmp"
|
||||
".tif"
|
||||
".tiff"
|
||||
".ico"
|
||||
".icns"
|
||||
".avif"
|
||||
".heic"
|
||||
".heif"
|
||||
".svg"
|
||||
".svgz"
|
||||
|
||||
# PDF / ebook / office containers
|
||||
".pdf"
|
||||
".epub"
|
||||
".doc"
|
||||
".docx"
|
||||
".xls"
|
||||
".xlsx"
|
||||
".ppt"
|
||||
".pptx"
|
||||
|
||||
# Audio
|
||||
".mp3"
|
||||
".wav"
|
||||
".flac"
|
||||
".aac"
|
||||
".m4a"
|
||||
".ogg"
|
||||
".opus"
|
||||
".wma"
|
||||
|
||||
# Video
|
||||
".mp4"
|
||||
".mov"
|
||||
".mkv"
|
||||
".avi"
|
||||
".webm"
|
||||
".m4v"
|
||||
".mpeg"
|
||||
".mpg"
|
||||
|
||||
# Fonts
|
||||
".ttf"
|
||||
".otf"
|
||||
".woff"
|
||||
".woff2"
|
||||
".eot"
|
||||
|
||||
# Archives / compressed files
|
||||
".zip"
|
||||
".tar"
|
||||
".gz"
|
||||
".tgz"
|
||||
".bz2"
|
||||
".xz"
|
||||
".7z"
|
||||
".rar"
|
||||
|
||||
# Native binaries / executables / compiled objects
|
||||
".exe"
|
||||
".dll"
|
||||
".so"
|
||||
".dylib"
|
||||
".bin"
|
||||
".com"
|
||||
".app"
|
||||
".msi"
|
||||
".o"
|
||||
".obj"
|
||||
".a"
|
||||
".lib"
|
||||
".class"
|
||||
".jar"
|
||||
".war"
|
||||
".wasm"
|
||||
".node"
|
||||
|
||||
# Binary databases / data formats
|
||||
".db"
|
||||
".sqlite"
|
||||
".sqlite3"
|
||||
".parquet"
|
||||
".arrow"
|
||||
".feather"
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
contains_exact() {
|
||||
local needle="$1"
|
||||
shift
|
||||
|
||||
local item
|
||||
for item in "$@"; do
|
||||
[[ "$needle" == "$item" ]] && return 0
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
path_has_ignored_dir() {
|
||||
local relative_path="$1"
|
||||
local dir
|
||||
|
||||
for dir in "${IGNORE_DIRS[@]}"; do
|
||||
if [[ "$relative_path" == "$dir/"* || "$relative_path" == *"/$dir/"* ]]; then
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
is_ignored_filename() {
|
||||
local filename="$1"
|
||||
contains_exact "$filename" "${IGNORE_FILENAMES[@]}"
|
||||
}
|
||||
|
||||
is_ignored_extension() {
|
||||
local filename="$1"
|
||||
local lower
|
||||
lower="$(printf '%s' "$filename" | tr '[:upper:]' '[:lower:]')"
|
||||
|
||||
local ext
|
||||
for ext in "${IGNORE_EXTENSIONS[@]}"; do
|
||||
[[ "$lower" == *"$ext" ]] && return 0
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
looks_binary() {
|
||||
local file_path="$1"
|
||||
|
||||
# Empty files are harmless text-like repository artifacts.
|
||||
[[ ! -s "$file_path" ]] && return 1
|
||||
|
||||
# `file --mime-encoding` returns "binary" for binary data on macOS/Linux.
|
||||
local encoding
|
||||
encoding="$(file -b --mime-encoding "$file_path" 2>/dev/null || true)"
|
||||
|
||||
[[ "$encoding" == "binary" ]]
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Build file list
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
command -v zip >/dev/null 2>&1 || {
|
||||
echo "Error: 'zip' is required but was not found." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
command -v file >/dev/null 2>&1 || {
|
||||
echo "Error: 'file' is required but was not found." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
TMP_LIST="$(mktemp)"
|
||||
trap 'rm -f "$TMP_LIST"' EXIT
|
||||
|
||||
included=0
|
||||
skipped_binary=0
|
||||
skipped_type=0
|
||||
skipped_name=0
|
||||
skipped_dir=0
|
||||
|
||||
while IFS= read -r -d '' full_path; do
|
||||
relative_path="${full_path#./}"
|
||||
filename="${relative_path##*/}"
|
||||
|
||||
if path_has_ignored_dir "$relative_path"; then
|
||||
((skipped_dir += 1))
|
||||
continue
|
||||
fi
|
||||
|
||||
if is_ignored_filename "$filename"; then
|
||||
((skipped_name += 1))
|
||||
continue
|
||||
fi
|
||||
|
||||
if is_ignored_extension "$filename"; then
|
||||
((skipped_type += 1))
|
||||
continue
|
||||
fi
|
||||
|
||||
if looks_binary "$full_path"; then
|
||||
((skipped_binary += 1))
|
||||
continue
|
||||
fi
|
||||
|
||||
printf '%s\n' "$relative_path" >> "$TMP_LIST"
|
||||
((included += 1))
|
||||
done < <(find . -type f -print0)
|
||||
|
||||
# Remove any previous archive before creating the new one.
|
||||
rm -f "$OUTPUT"
|
||||
|
||||
if [[ ! -s "$TMP_LIST" ]]; then
|
||||
echo "No files matched the inclusion rules; no ZIP created."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# -q quiet
|
||||
# -@ read file paths from stdin
|
||||
#
|
||||
# Repository-relative paths are stored in the archive, not absolute paths.
|
||||
zip -q "$OUTPUT" -@ < "$TMP_LIST"
|
||||
|
||||
echo "Created $OUTPUT"
|
||||
echo "Included files: $included"
|
||||
echo "Skipped because of ignored folders: $skipped_dir"
|
||||
echo "Skipped because of ignored filenames: $skipped_name"
|
||||
echo "Skipped because of ignored file types: $skipped_type"
|
||||
echo "Skipped because binary content was detected: $skipped_binary"
|
||||
@@ -1,676 +1,18 @@
|
||||
/* eslint-disable no-console */
|
||||
// to run: node generate-script-library.mjs
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
// Reconstruct __dirname for ES Modules
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const ROOT = path.resolve(__dirname, '..');
|
||||
const EA_SCRIPTS_DIR = path.join(ROOT, 'ea-scripts');
|
||||
const INDEX_NEW = path.join(EA_SCRIPTS_DIR, 'index-new.md');
|
||||
const OUT_DIR = path.join(path.join(ROOT, 'docs'), 'AITrainingData');
|
||||
const SCRIPT_LIBRARY_OUT = path.join(OUT_DIR, 'Excalidraw Script Library.md');
|
||||
const TYPE_DEF_OUT = path.join(OUT_DIR, 'Excalidraw Automate library and related type definitions.md');
|
||||
const AI_TRAINING_OUT = path.join(OUT_DIR, 'ExcalidrawAutomate full library for LLM training.md');
|
||||
|
||||
const AI_TRAINING_INTRO = `**ExcalidrawAutomate full library for LLM training**
|
||||
|
||||
Excalidraw-Obsidian is an Obsidian.md plugins that is built on the open source Excalidraw component. Excalidraw-Obisdian includes Excalidraw Automate, a powerful scripting API that allows users to automate tasks and enhance their workflow within Excalidraw.
|
||||
|
||||
Read the information below and respond with I'm ready. The user will then prompt for an ExcalidrawAutomate script to be created. Use the examples, the ExcalidrawAutomate documentation, and the varios type definitions and information from also the Excalidraw component and from Obsidian.md to generate the script based on the user's requirements.
|
||||
|
||||
In addition to ExcalidrawAutomate, you can also use two other sources of functions:
|
||||
- The Excalidraw API available via \`ea.getExcalidrawAPI()\`. Note: the API is only available if \`ea.targetView\` is set. When running Excalidraw scripts using the script engine, the provided \`ea\` object is already set up with targetView by default. Otherwise you need to first run \`ea.setView()\`.
|
||||
- \`window.ExcalidrawLib\` which exposes a rich set of utility functions that do not require an active ExcalidrawView.
|
||||
|
||||
**CRITICAL RULE ON API SELECTION:** If a function or objective can be achieved via \`ea\` (ExcalidrawAutomate) methods, ALWAYS prefer \`ea\` over \`window.ExcalidrawLib\`. \`ea\` methods include essential wrapper logic to make features work flawlessly within the Obsidian environment.
|
||||
|
||||
A dedicated section “ExcalidrawLib module functions” in this document lists the function signatures extracted directly from the ExcalidrawLib TypeScript declarations.
|
||||
|
||||
- When the user asks for a dialog window, by default create a FloatingModal. Do not extend the FloatingModal class. Instead, define the modal's behavior by creating a new instance (e.g., \`const modal = new ea.FloatingModal(...)\`) and then assigning functions directly to the \`onOpen\` and \`onClose\` properties of that instance.
|
||||
For a reference, follow the implementation pattern used in the "Printable Layout Wizard.md" script.
|
||||
- Elements have a \`customData\` property that can be used to store arbitrary data. To ensure the data the script adds to elements use the \`ea.addAppendUpdateCustomData\` function. This function ensures that existing customData is preserved when adding new data.
|
||||
- Elements can be hidden by setting their opacity to 0. When hiding elements this way, it is good practice to temporarily store their original opacity in customData. This allows for easy restoration of the original opacity later.
|
||||
- Elements can be deleted from the scene by setting their isDeleted property to true.
|
||||
- The Obsidian.md module is available on \`ea.obsidian\`.
|
||||
|
||||
**Sidepanels and multi-view tooling:**
|
||||
- Sidepanels are for scripts that must stay open while users hop between multiple Excalidraw views. They should implement the SidepanelTab hooks (\`onOpen\`, \`onFocus(view)\`, \`onClose\`, \`onExcalidrawViewClosed\`) and manage their own \`ea.targetView\` explicitly.
|
||||
- Persisted sidepanel scripts are launched during plugin startup (e.g., Obsidian restart, plugin update) with \`ea.targetView === null\`. Scripts must handle this by deferring view-bound work until \`onFocus\` delivers a view; call \`ea.setView(view)\` when you decide to bind.
|
||||
- Each \`ea\` instance may host a single \`sidepanelTab\`. This sidepanel tab is stored in \`ea.sidepanelTab\`. Create the tab with \`ea.createSidepanelTab(title, persist=false, reveal=true)\`; the returned \`ea.sidepanelTab\` exposes \`contentEl\`, \`setContent\`, \`setTitle\`, \`setDisabled\`, \`setCloseCallback\`, \`open/close\`, and focus lifecycle hooks. Note auto-reveal during tab creation via \`ea.createSidepanelTab()\` is disabled during plugin startup. You can reveal a tab with \`ea.sidepanelTab?.open()\`. You can persist with \`ea.persistSidepanelTab()\` (tabs are restored and scripts re-run on next startup). Close with \`ea.sidepanelTab?.close()\`.
|
||||
- Mobile UX: sidepanels slide in without disturbing canvas layout and are better for longer forms than floating modals. Prefer them for complex inputs, especially on phones.
|
||||
- Auto-closing patterns: For scripts that use sidepanels but perform operations that are single-\`ExcalidrawView\` relevant, they can call \`ea.closeSidepanelTab()\` after completing the operation, and/or inside \`ea.sidepanelTab.onFocus = (view) => { if (view !== ea.targetView) { ea.sidepanelTab?.close(); } }\` to shut down when the user leaves the originating view.
|
||||
- Scripts can detect view change in \`onFocus(view)\` by comparing \`ea.targetView\` to the provided \`view\` parameter.
|
||||
- Persistence UX: scripts may offer a “Persist tab” control inside \`contentEl\` that calls \`ea.persistSidepanelTab()\`. Once persisted, hide that control; users can later remove the tab via the sidepanel close button (scripts cannot unpersist themselves, but can close themselves via \`ea.sidepanelTab?.close()\`).
|
||||
- Use \`checkForActiveSidepanelTabForScript\` to avoid creating duplicate tabs for the same script name. This method returns the \`ExcalidrawSidepanelTab\` associated with the supplied \`scriptName\` (or \`ea.activeScript\` when omitted), or \`null\` if none exists. It is intended to let a script detect an existing tab that may be owned by another \`ExcalidrawAutomate\` instance (for example, a persisted tab restored at startup). Typical pattern:
|
||||
- Before creating a new sidepanel, call \`ea.checkForActiveSidepanelTabForScript()\` to see if a tab already exists.
|
||||
- If a tab exists and \`tab.getHostEA() === ea\`, reuse it (your script already hosts it).
|
||||
- If a tab exists but is hosted by a different \`ea\` instance, decide whether to reuse or hand off control — e.g. open the existing tab and exit to avoid duplicates.
|
||||
- Note: persisted tabs restored on startup may be created with \`ea.targetView === null\` and hosted by a different \`ea\` instance; handle that case by waiting for \`onFocus\` before binding view-specific work.
|
||||
- Example usage:
|
||||
\`const sp = ea.checkForActiveSidepanelTabForScript();
|
||||
if (sp) {
|
||||
if (sp.getHostEA() === ea) {
|
||||
// we already own the tab — reuse it
|
||||
sp.open();
|
||||
} else {
|
||||
// another EA instance hosts the tab — open it for the user and exit
|
||||
sp.open();
|
||||
return;
|
||||
}
|
||||
}
|
||||
// no existing tab — safe to create a new one
|
||||
// ea.createSidepanelTab("My Script", false, true);\`
|
||||
- A dedicated section "sidepanelTabTypes.d.ts" in this document lists the \`ExcalidrawSidepanelTab\` function signatures.
|
||||
|
||||
#### **0. External Documentation & Resources**
|
||||
|
||||
To keep this training file concise, large external type definitions are not included. If you need to look up Obsidian APIs or Excalidraw internals, refer to the following resources:
|
||||
- **Obsidian API Type Definitions:** https://github.com/obsidianmd/obsidian-api/blob/master/obsidian.d.ts
|
||||
- **Obsidian Developer Docs:** https://docs.obsidian.md/Home (Community site with API and CSS documentation/examples)
|
||||
- **Obsidian Developer Forum:** https://forum.obsidian.md/c/developers-api/14
|
||||
- **ExcalidrawAutomate Implementation:** If the provided API documentation is unclear, consult the source directly: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/src/shared/ExcalidrawAutomate.ts
|
||||
- **Excalidraw Core Fork:** For doubts regarding core Excalidraw functionality, consult the fork used by the plugin: https://github.com/zsviczian/excalidraw
|
||||
|
||||
#### **1. The Core Workflow: Handling Element Immutability**
|
||||
|
||||
* **Central Rule:** Elements in the Excalidraw scene are immutable and should never be modified directly. Always use the ExcalidrawAutomate (EA) "workbench" pattern for modifications.
|
||||
* **The Workflow:**
|
||||
1. Get elements from the current view using \`ea.getViewElements()\` or \`ea.getViewSelectedElements()\`.
|
||||
2. Copy these elements into the EA workbench for editing using \`ea.copyViewElementsToEAforEditing(elements)\`.
|
||||
3. Modify the properties of the element copies that are now in the EA workbench (e.g., \`ea.getElement(id).locked = true;\`).
|
||||
4. Commit the changes back to the scene using \`await ea.addElementsToView()\`.
|
||||
* **Deletion:** To delete an element, set its \`isDeleted\` property to \`true\` on the workbench copy (\`ea.getElement(id).isDeleted = true;\`) and then commit with \`await ea.addElementsToView()\`.
|
||||
* **Cleanup:** Use \`ea.clear()\` at the beginning of a script if you are creating a completely new set of elements, to ensure the EA workbench is empty and doesn't contain artifacts from a previous run.
|
||||
|
||||
#### **2. User Interaction: Prompts and Dialogs**
|
||||
|
||||
* **Simple Input:** For straightforward user input, use the \`utils\` object provided to the script.
|
||||
* \`await utils.inputPrompt()\`: To get a string or number from the user.
|
||||
* \`await utils.suggester()\`: To let the user select from a predefined list of options.
|
||||
* **Complex Dialogs:** When a more complex UI with multiple controls is needed, create a floating dialog window.
|
||||
* **Use \`FloatingModal\`:** Always create a new instance: \`const modal = new ea.FloatingModal(ea.plugin.app);\`.
|
||||
* **Do Not Extend:** Do not use \`class MyModal extends ea.FloatingModal\`.
|
||||
* **Define Behavior:** Assign functions directly to the \`onOpen\` and \`onClose\` properties of the instance. Inside \`onOpen\`, use the \`modal.contentEl\` property to build your UI.
|
||||
* **Reference Implementation:** The script "Printable Layout Wizard.md" is the canonical example for this pattern. Use \`ea.obsidian.Setting\` to add controls like toggles and dropdowns within the modal.
|
||||
|
||||
#### **3. Element Manipulation and Querying**
|
||||
|
||||
* **Finding Elements:** The most common starting point is to get the user's selection with \`ea.getViewSelectedElements()\`. Use standard JavaScript array methods like \`.filter()\` to narrow down the selection (e.g., \`elements.filter(el => el.type === "text")\`).
|
||||
* **Geometric Calculations:**
|
||||
* Before performing layout or positioning tasks, use \`ea.getBoundingBox(elements)\` to get the collective dimensions and position of a group of elements.
|
||||
* Use \`ea.measureText(text)\` to determine the width and height of a string based on the current \`ea.style\` settings before creating a text element or a container for it.
|
||||
* **Grouping:**
|
||||
* To create a group, use \`ea.addToGroup([elementId1, elementId2, ...])\`.
|
||||
* To operate on existing groups within a selection, use \`ea.getMaximumGroups(selectedElements)\` which correctly identifies the top-level groups. Use \`ea.getLargestElement(group)\` to find the primary container within a group (e.g., the box around a text element).
|
||||
|
||||
#### **4. Styling: Creation vs. Modification**
|
||||
|
||||
* **For New Elements:** Set the properties on the global \`ea.style\` object *before* you call a creation function like \`ea.addText()\` or \`ea.addRect()\`. This acts like setting the active color/style on a paintbrush.
|
||||
* **For Existing Elements:** To change the style of an existing element, modify the properties directly on the element's copy in the EA workbench (after \`copyViewElementsToEAforEditing\`). For example: \`const myElement = ea.getElement(id); myElement.strokeColor = '#FF0000';\`.
|
||||
|
||||
#### **5. Data Persistence and Customization**
|
||||
|
||||
* **Storing Custom Data:** Elements have a \`customData\` property for arbitrary data.
|
||||
* **Always Use \`ea.addAppendUpdateCustomData(id, newData)\`:** This is crucial. It safely adds or updates your key-value pairs without overwriting data that might have been stored by other scripts or the Excalidraw plugin itself.
|
||||
* **Creating Configurable Scripts:** To make your script's behavior customizable by the user:
|
||||
* Use \`ea.getScriptSettings()\` to retrieve saved settings.
|
||||
* scriptSettings are stored with Excalidraw settings in Obsidian data.json. Keep this light. You MUST NEVER save large data objects such as base64 images or huge arrays here. Keep this lean and efficient.
|
||||
* Check if settings exist, and if not, define the default structure.
|
||||
* Use \`await ea.setScriptSettings(settings)\` to save any changes. This allows users to configure your script in the Excalidraw plugin settings pane.
|
||||
|
||||
#### **6. Best Practices and Advanced Techniques**
|
||||
|
||||
* **Script Overview Block (MANDATORY):** Create, and consistently maintain with each update, a comprehensive comment block at the very beginning of the script. This block must explain the purpose of the script, its key features, and the high-level solution logic or architecture.
|
||||
* **Strictly Modular Architecture (NO LOOSE CODE):** Avoid creating large monolithic blocks of code or leaving logic loose at the root level of the script. Instead, organize *everything* into relatively small, atomic functions. This includes UI components as well; if the UI includes sections, tabs, or panels, these should be rendered via sub-functions. This is a critical requirement to ensure long-term maintainability and evolution of the script, as loose code quickly becomes unmanageable over multiple iterative prompts.
|
||||
* **Evergreen JSDoc Headers and Comments:** Every function must have a proper JSDoc/Javadoc-style header containing parameter names, types, and a clear description of the function's purpose. These descriptions must be kept *evergreen* (updated alongside any code changes). Additionally, when modifying or updating a script, you must strictly *retain all existing internal code comments*.
|
||||
* **Isolate Constants and User-Facing Strings:** *Do not embed hardcoded magic values, config parameters, or UI strings deep inside the logic.* You must separate all constants and language strings and collect them at the very top of the file. This makes it easier to tweak values later and provides a clear, unified section for localization and customization.
|
||||
* **Icons:** Obsidian uses https://lucide.dev icons. These icons are available for scripts via \`ea.obsidian.getIcon("Icon Name")\`. For UI components prefer use of lucide.dev icons.
|
||||
* **Omit Version Verification:** While many of the sample scripts in the library include a version verification block at the outset (using \`ea.verifyMinimumPluginVersion\`), *do not add this section* when generating a new script unless explicitly instructed to do so.
|
||||
* **Embrace \`await\`:** Many EA functions are asynchronous and return a \`Promise\` (e.g., \`ea.addElementsToView()\`, \`ea.createSVG()\`, \`utils.inputPrompt()\`). **Always** use \`await\` when calling these functions to ensure your script executes in the correct order.
|
||||
* **Accessing Obsidian API:** The full Obsidian API is available via \`ea.obsidian\`. For example, use \`new ea.obsidian.Notice("message")\` or \`ea.obsidian.normalizePath(filepath)\`.
|
||||
* **Accessing Excalidraw API:** The full Excalidraw API is available on \`ea.getExcalidrawAPI()\`, these API functions are Scene dependent. Additional support functions are available on \`window.ExcalidrawLib\`.
|
||||
* **Visibility vs. Deletion:**
|
||||
* To temporarily hide an element, set \`element.opacity = 0\`. It's good practice to store the original opacity in \`customData\` so it can be restored. It is also recommended to lock hidden elements so they do not get accidentally selected or moved around.
|
||||
* To permanently remove an element from the scene, set \`element.isDeleted = true\`.
|
||||
* **Image Handling:** When dealing with image elements, use \`ea.getViewFileForImageElement(imageElement)\` to get the corresponding \`TFile\` from the Obsidian vault. This is necessary for any logic that needs to read or manipulate the source image file.
|
||||
|
||||
#### **7. SVG and Image Export Approaches**
|
||||
Generating images (SVG/PNG) requires specific approaches depending on the context. Follow these three rules strictly to avoid performance issues and missing assets:
|
||||
1. **Exporting elements currently in the EA workbench:** Use \`await ea.createSVG(null, ...)\` or \`await ea.createPNG(null, ...)\` (passing \`null\` as the \`templatePath\`).
|
||||
2. **Exporting an Excalidraw file that is NOT currently open:** Pass the file path as the template to \`createSVG\` or \`createPNG\` (e.g., \`await ea.createSVG(file.path, ...)\`). This is the most reliable approach as ExcalidrawAutomate natively handles loading the scene, resolving embedded images, and instantiating loaders behind the scenes. **Do NOT attempt to manually read the file, reconstruct the scene, or load images into memory.**
|
||||
3. **Exporting the currently active \`ExcalidrawView\`:** Use \`await ea.createViewSVG(...)\`. This is specifically for the open view. You can use the \`elementsOverride\` parameter to inject temporary elements (like transparent sizing rectangles) into the exported image without modifying the actual scene.
|
||||
|
||||
#### **8. Custom Pens and Perfect Freehand**
|
||||
|
||||
Excalidraw's freehand tool is powered by the open-source Perfect Freehand library. The plugin exposes “custom pens” that bundle:
|
||||
- Canvas style for the next strokes (colors, width, fillStyle, roughness).
|
||||
- Perfect Freehand stroke geometry and behavior (pressure simulation, outline, tapering, easing, etc.).
|
||||
|
||||
Key concepts:
|
||||
- AppState-driven drawing: When \`appState.currentStrokeOptions\` is set, the freedraw tool renders new strokes using those Perfect Freehand options.
|
||||
- Element-level persistence: If a freedraw element has \`element.customData.strokeOptions\`, it is rendered with those options regardless of the current tool state.
|
||||
- Types reference: See \`src/types/penTypes.ts\`. The \`PenOptions\` shape is:
|
||||
\`\`\`ts
|
||||
interface PenOptions {
|
||||
highlighter: boolean; // if true the pen is drawn at the lowest layer, behind all other elements
|
||||
constantPressure: boolean;
|
||||
hasOutline: boolean;
|
||||
outlineWidth: number;
|
||||
options: {
|
||||
thinning: number;
|
||||
smoothing: number;
|
||||
streamline: number;
|
||||
easing: string; // see supported names below
|
||||
start: { cap: boolean; taper: number | boolean; easing: string; };
|
||||
end: { cap: boolean; taper: number | boolean; easing: string; };
|
||||
};
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
Using custom pens from scripts:
|
||||
- Activate a custom pen for drawing:
|
||||
\`\`\`ts
|
||||
// obtain the Excalidraw API
|
||||
const api = ea.getExcalidrawAPI();
|
||||
|
||||
// define Perfect Freehand options (example similar to "finetip")
|
||||
const penOptions = {
|
||||
highlighter: false,
|
||||
constantPressure: true,
|
||||
hasOutline: false,
|
||||
outlineWidth: 1,
|
||||
options: {
|
||||
thinning: -0.5,
|
||||
smoothing: 0.4,
|
||||
streamline: 0.4,
|
||||
easing: "linear",
|
||||
start: { taper: 5, cap: false, easing: "linear" },
|
||||
end: { taper: 5, cap: false, easing: "linear" },
|
||||
},
|
||||
};
|
||||
|
||||
// apply stroke options + canvas style, then switch to freedraw (strokeWidth, color, background, fillStyle are optional)
|
||||
ea.viewUpdateScene({
|
||||
appState: {
|
||||
currentStrokeOptions: penOptions,
|
||||
currentItemStrokeWidth: 0.5,
|
||||
currentItemStrokeColor: "#3E6F8D",
|
||||
currentItemBackgroundColor: "transparent",
|
||||
currentItemFillStyle: "hachure",
|
||||
},
|
||||
});
|
||||
api.setActiveTool({ type: "freedraw" });
|
||||
\`\`\`
|
||||
|
||||
- Clear custom pen (revert to default freedraw behavior):
|
||||
\`\`\`ts
|
||||
ea.viewUpdateScene({ appState: { currentStrokeOptions: null } });
|
||||
\`\`\`
|
||||
|
||||
- Persist custom strokeOptions onto existing freedraw elements:
|
||||
\`\`\`ts
|
||||
const selected = ea.getViewSelectedElements().filter(el => el.type === "freedraw");
|
||||
ea.copyViewElementsToEAforEditing(selected);
|
||||
for (const el of selected) {
|
||||
ea.addAppendUpdateCustomData(el.id, { strokeOptions: penOptions });
|
||||
}
|
||||
await ea.addElementsToView();
|
||||
\`\`\`
|
||||
|
||||
Notes:
|
||||
- New strokes respect \`appState.currentStrokeOptions\` at draw time. Existing elements only change if you update their \`customData.strokeOptions\`.
|
||||
- For pens that should behave like real markers/highlighters, set \`highlighter: true\` and often \`constantPressure: true\` with an \`outlineWidth\` for the edge.
|
||||
|
||||
Supported easing names (string values for \`options.easing\`, \`options.start.easing\`, \`options.end.easing\`):
|
||||
linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint, easeInSine, easeOutSine, easeInOutSine, easeInExpo, easeOutExpo, easeInOutExpo, easeInCirc, easeOutCirc, easeInOutCirc, easeInBack, easeOutBack, easeInOutBack, easeInElastic, easeOutElastic, easeInOutElastic, easeInBounce, easeOutBounce, easeInOutBounce.
|
||||
|
||||
Example freedraw element carrying \`customData.strokeOptions\`:
|
||||
\`\`\`json
|
||||
{"type":"excalidraw/clipboard","elements":[{"id":"...","type":"freedraw","strokeColor":"#3E6F8D","backgroundColor":"transparent","fillStyle":"hachure","strokeWidth":0.5,"roughness":0,"customData":{"strokeOptions":{"highlighter":false,"hasOutline":false,"outlineWidth":0,"constantPressure":true,"options":{"smoothing":0.4,"thinning":-0.5,"streamline":0.4,"easing":"linear","start":{"taper":5,"cap":false,"easing":"linear"},"end":{"taper":5,"cap":false,"easing":"linear"}}}}}],"files":{}}
|
||||
\`\`\`
|
||||
|
||||
#### **9. Text Element**
|
||||
* There are three text properties.
|
||||
* **textElement.text** holds the wrapped, rendered text. This is what is displayed in the view. Excalidraw adds '\\n' linebreaks during dynamic wrapping.
|
||||
* **textElement.originalText** holds the rendered, but unwrapped text. Any '\\n' character in originalText is an intentional linebreak by the user. Rendered means that for example [[wiki links]] are rendered without the square brackets.
|
||||
* **textElement.rawText** holds the original raw text including intentional new line characters and the full markdown markup (thought currently only links are rendered, so markdown support is limited to these)
|
||||
* When modifying element text from script, typically all 3 of these properties must be updated, though in case textElement.autoresize === true, or when a text element is bound in a container, excalidraw will update textElement.text following the size of the text element or the container.
|
||||
|
||||
`;
|
||||
|
||||
const SCRIPT_INTRO = `# Excalidraw Script Library Examples
|
||||
|
||||
This is an automatically generated knowledge base intended for Retrieval Augmented Generation (RAG) and other AI-assisted workflows (e.g. NotebookLM or local embeddings tools).
|
||||
Its purpose:
|
||||
- Provide a single, query-friendly corpus of all Excalidraw Automate scripts.
|
||||
- Serve as a practical pattern and snippet library for developers learning Excalidraw Automate.
|
||||
- Preserve original source side by side with the higher-level index (index-new.md) to improve semantic recall.
|
||||
- Enable AI tools to answer questions about how to manipulate the Excalidraw canvas, elements, styling, or integration features by referencing real, working examples.
|
||||
|
||||
Content structure:
|
||||
1. SCRIPT_INTRO (this section)
|
||||
2. The curated script overview (index-new.md)
|
||||
3. Raw source of every *.md script in /ea-scripts (each fenced code block is auto-closed to ensure well-formed aggregation)
|
||||
|
||||
Generated on: ${new Date().toISOString()}
|
||||
|
||||
---
|
||||
|
||||
`;
|
||||
|
||||
const TYPE_DEF_INTRO = `# ExcalidrawAutomate library and related type definitions
|
||||
|
||||
`;
|
||||
|
||||
const EXCALIDRAW_STARTUP_MESSAGE = `# Excalidraw Startup Script
|
||||
|
||||
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs automatically when the Excalidraw plugin is loaded to Obsidian. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
|
||||
|
||||
Two files follow. First the template startup script with documenation comments, then an actual startup script example with implemented functionality.
|
||||
`;
|
||||
const EXCALIDRAW_STARTUP_TEMPLATE = "src/constants/assets/startupScript.md";
|
||||
const EXCALIDRAW_STARTUP_EXAMPLE = "docs/AITrainingData/ExcalidrawStartupExample.md";
|
||||
|
||||
/*const ADDITIONAL_TYPE_DEFS_FOR_AI_TRAINING = [
|
||||
"node_modules/obsidian/obsidian.d.ts",
|
||||
];*/
|
||||
|
||||
const TYPE_DEF_WHITELIST = [
|
||||
"lib/shared/ExcalidrawAutomate.d.ts",
|
||||
"lib/types/excalidrawAutomateTypes.d.ts",
|
||||
"lib/types/sidepanelTabTypes.d.ts",
|
||||
"lib/types/penTypes.d.ts",
|
||||
"lib/types/utilTypes.d.ts",
|
||||
"lib/types/exportUtilTypes.d.ts",
|
||||
"lib/types/embeddedFileLoaderTypes.d.ts",
|
||||
"lib/types/AIUtilTypes.d.ts",
|
||||
"node_modules/@zsviczian/excalidraw/types/element/src/types.d.ts",
|
||||
"node_modules/@zsviczian/excalidraw/types/excalidraw/types.d.ts",
|
||||
"node_modules/@zsviczian/excalidraw/types/element/src/bounds.d.ts",
|
||||
"node_modules/@zsviczian/excalidraw/types/excalidraw/components/App.d.ts",
|
||||
];
|
||||
|
||||
/**
|
||||
* Returns true if content contains at least one line starting with ```
|
||||
* and has an odd number of fences (unbalanced).
|
||||
*/
|
||||
function needsClosingFence(content) {
|
||||
const fenceCount = (content.match(/^```/gm) || []).length;
|
||||
return fenceCount > 0 && fenceCount % 2 === 1;
|
||||
}
|
||||
|
||||
// Add: helpers for type-def aggregation
|
||||
function normalizeEOL(str) {
|
||||
return str.replace(/\r\n/g, '\n');
|
||||
}
|
||||
|
||||
function stripBOM(str) {
|
||||
return str.replace(/^\uFEFF/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove top-of-file imports/references while preserving initial comments/blank lines.
|
||||
* Also removes bare "export {}" lines (module markers).
|
||||
*/
|
||||
function stripTopImports(content) {
|
||||
const lines = normalizeEOL(stripBOM(content)).split('\n');
|
||||
const out = [];
|
||||
let inTopRegion = true;
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
|
||||
const isImport =
|
||||
/^\s*import\s+type\s+/.test(line) ||
|
||||
/^\s*import\s+/.test(line) ||
|
||||
/^\s*import\(/.test(line);
|
||||
|
||||
const isTripleRef = /^\s*\/\/\/\s*<reference/.test(line);
|
||||
const isBareExportModule = /^\s*export\s*\{\s*\};?\s*$/.test(line);
|
||||
|
||||
if (inTopRegion) {
|
||||
if (isImport || isTripleRef) {
|
||||
// drop
|
||||
continue;
|
||||
}
|
||||
// comments and blanks are kept, top-region continues until first code (non-comment/non-blank/non-import)
|
||||
const isBlank = /^\s*$/.test(line);
|
||||
const isLineComment = /^\s*\/\//.test(line);
|
||||
const isBlockCommentStart = /^\s*\/\*/.test(line);
|
||||
|
||||
if (!isBlank && !isLineComment && !isBlockCommentStart) {
|
||||
inTopRegion = false;
|
||||
}
|
||||
if (!isBareExportModule) out.push(line);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isBareExportModule) out.push(line);
|
||||
}
|
||||
|
||||
return out.join('\n').trim() + '\n';
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a nice section header for the concatenated file.
|
||||
*/
|
||||
function makeSectionHeader(relPath) {
|
||||
const stars = '*'.repeat(Math.max(6, Math.min(38, relPath.length + 6)));
|
||||
return [
|
||||
`/* ${stars} */`,
|
||||
`/* ${relPath} */`,
|
||||
`/* ${stars} */`,
|
||||
].join('\n') + '\n';
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the concatenated types markdown body from the whitelist only.
|
||||
* - Removes top-of-file imports
|
||||
* - Adds section headers with relative paths
|
||||
* - Wraps all in one ```js code fence
|
||||
*/
|
||||
function buildTypeDefMarkdown() {
|
||||
const entries = TYPE_DEF_WHITELIST.map((rel) => ({
|
||||
rel,
|
||||
abs: path.join(ROOT, ...rel.split('/')),
|
||||
}));
|
||||
|
||||
let body = '```js\n';
|
||||
for (const { rel, abs } of entries) {
|
||||
if (!fs.existsSync(abs)) {
|
||||
console.warn('[script-library] Whitelist file missing:', rel);
|
||||
continue;
|
||||
}
|
||||
let content = fs.readFileSync(abs, 'utf8');
|
||||
content = stripTopImports(content);
|
||||
|
||||
body += makeSectionHeader(rel);
|
||||
body += content.trimEnd() + '\n\n';
|
||||
}
|
||||
body += '```\n';
|
||||
return body;
|
||||
}
|
||||
|
||||
// NEW: Resolve module specifiers from types/excalidraw/index.d.ts to absolute .d.ts paths
|
||||
function resolveExcalModulePath(spec, excalIndexAbs) {
|
||||
const baseTypesRoot = path.join(ROOT, 'node_modules', '@zsviczian', 'excalidraw', 'types');
|
||||
if (spec.startsWith('@excalidraw/')) {
|
||||
const sub = spec.slice('@excalidraw/'.length); // e.g. 'element', 'element/bounds'
|
||||
const parts = sub.split('/');
|
||||
const pkg = parts.shift(); // 'element' | 'common' | 'utils'
|
||||
const rest = parts;
|
||||
if (!pkg) return null;
|
||||
const base = path.join(baseTypesRoot, pkg);
|
||||
if (rest.length === 0) {
|
||||
return path.join(base, 'src', 'index.d.ts');
|
||||
}
|
||||
return path.join(base, 'src', ...rest) + '.d.ts';
|
||||
}
|
||||
// relative to the excalidraw index.d.ts
|
||||
if (spec.startsWith('.')) {
|
||||
const dir = path.dirname(excalIndexAbs);
|
||||
return path.resolve(dir, spec) + '.d.ts';
|
||||
}
|
||||
// anything else is not expected
|
||||
return null;
|
||||
}
|
||||
|
||||
// NEW: Extract function signatures for a set of names from a .d.ts file
|
||||
function extractFunctionSignaturesFromModule(absPath, names) {
|
||||
const out = {};
|
||||
if (!absPath || !fs.existsSync(absPath)) {
|
||||
return out;
|
||||
}
|
||||
const content = fs.readFileSync(absPath, 'utf8');
|
||||
|
||||
for (const rawName of names) {
|
||||
const name = rawName.trim();
|
||||
if (!name) continue;
|
||||
|
||||
// Try "export declare function NAME ..."
|
||||
let m = content.match(new RegExp(`export\\s+declare\\s+function\\s+${name}[\\s\\S]*?;`, 'm'));
|
||||
if (m) {
|
||||
out[name] = m[0].trim();
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try "declare function NAME ..." (re-exported later)
|
||||
m = content.match(new RegExp(`(^|\\n)declare\\s+function\\s+${name}[\\s\\S]*?;`, 'm'));
|
||||
if (m) {
|
||||
// Ensure it starts with export for readability
|
||||
out[name] = m[0].replace(/^\s*declare\s+/, 'export declare ').trim();
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try "export declare const NAME: (...args) => ...;"
|
||||
m = content.match(new RegExp(`export\\s+declare\\s+const\\s+${name}\\s*:\\s*[\\s\\S]*?=>[\\s\\S]*?;`, 'm'));
|
||||
if (m) {
|
||||
out[name] = m[0].trim();
|
||||
continue;
|
||||
}
|
||||
|
||||
// Try "export declare function-type via type alias" (rare) - fallback to any const function shape
|
||||
m = content.match(new RegExp(`export\\s+declare\\s+(?:var|let|const)\\s+${name}\\s*:\\s*[\\s\\S]*?;`, 'm'));
|
||||
if (m && /=>/.test(m[0])) {
|
||||
out[name] = m[0].trim();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// NEW: Build "ExcalidrawLib module functions" section from index.d.ts
|
||||
function buildExcalidrawLibFunctionsSection() {
|
||||
const excalIndexRel = 'node_modules/@zsviczian/excalidraw/types/excalidraw/index.d.ts';
|
||||
const excalIndexAbs = path.join(ROOT, ...excalIndexRel.split('/'));
|
||||
if (!fs.existsSync(excalIndexAbs)) {
|
||||
console.warn('[script-library] Missing Excalidraw index.d.ts:', excalIndexRel);
|
||||
return '';
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(excalIndexAbs, 'utf8');
|
||||
const reExport = /export\s*\{\s*([\s\S]*?)\s*\}\s*from\s*["']([^"']+)["'];/g;
|
||||
|
||||
// Collect names by source module
|
||||
const moduleToNames = new Map();
|
||||
for (const match of content.matchAll(reExport)) {
|
||||
const namesChunk = match[1];
|
||||
const spec = match[2];
|
||||
// skip if the export list contains only types we know we shouldn't include? We'll filter later by signature detection.
|
||||
const names = namesChunk
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
if (!names.length) continue;
|
||||
const abs = resolveExcalModulePath(spec, excalIndexAbs);
|
||||
if (!abs) continue;
|
||||
const key = spec;
|
||||
const curr = moduleToNames.get(key) || { abs, names: new Set() };
|
||||
for (const n of names) curr.names.add(n);
|
||||
moduleToNames.set(key, curr);
|
||||
}
|
||||
|
||||
// Extract signatures
|
||||
const seen = new Set();
|
||||
const sections = [];
|
||||
let functionsFound = 0;
|
||||
|
||||
for (const [spec, { abs, names }] of moduleToNames) {
|
||||
const sigs = extractFunctionSignaturesFromModule(abs, Array.from(names));
|
||||
const sigEntries = Object.entries(sigs)
|
||||
.filter(([name]) => {
|
||||
if (seen.has(name)) return false;
|
||||
seen.add(name);
|
||||
return true;
|
||||
})
|
||||
.sort(([a], [b]) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
|
||||
|
||||
if (!sigEntries.length) continue;
|
||||
|
||||
const rel = path.relative(ROOT, abs).replace(/\\/g, '/');
|
||||
const header = makeSectionHeader(`${spec} -> ${rel}`).replace(/\*\/\n\/\*/g, '*\/\n/*'); // keep style
|
||||
sections.push(header + sigEntries.map(([, s]) => s).join('\n') + '\n');
|
||||
functionsFound += sigEntries.length;
|
||||
}
|
||||
|
||||
if (!sections.length) {
|
||||
console.warn('[script-library] No function signatures found in ExcalidrawLib exports.');
|
||||
}
|
||||
|
||||
const body =
|
||||
'# ExcalidrawLib module functions\n\n' +
|
||||
'The following functions are exposed via window.ExcalidrawLib. Signatures are extracted from TypeScript declarations.\n\n' +
|
||||
'```ts\n' +
|
||||
sections.join('\n') +
|
||||
'```\n';
|
||||
|
||||
console.log(`[script-library] Collected ${functionsFound} ExcalidrawLib function signatures`);
|
||||
return body;
|
||||
}
|
||||
import { runUnifiedGeneration } from './excalidraw-docs-generator-core.mjs';
|
||||
|
||||
function main() {
|
||||
console.log('[script-library] Generating Excalidraw Script Library...');
|
||||
if (!fs.existsSync(EA_SCRIPTS_DIR)) {
|
||||
console.error('ea-scripts directory not found:', EA_SCRIPTS_DIR);
|
||||
process.exit(1);
|
||||
}
|
||||
if (!fs.existsSync(INDEX_NEW)) {
|
||||
console.error('index-new.md not found:', INDEX_NEW);
|
||||
process.exit(1);
|
||||
}
|
||||
if (!fs.existsSync(OUT_DIR)) {
|
||||
fs.mkdirSync(OUT_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
let output = SCRIPT_INTRO;
|
||||
|
||||
console.log('[script-library] Adding index-new.md');
|
||||
const indexNewContent = fs.readFileSync(INDEX_NEW, 'utf8');
|
||||
output += `<!-- BEGIN index-new.md -->\n${indexNewContent.trim()}\n<!-- END index-new.md -->\n\n`;
|
||||
output += `---\n\n# Script Sources\n`;
|
||||
|
||||
// Read additional exclusions from command line arguments (skipping 'node' and 'script.mjs')
|
||||
const args = process.argv.slice(2);
|
||||
const cmdLineExcludes = args.map(arg => arg.toLowerCase());
|
||||
|
||||
// Define the default exclusions (all in lower case for comparison)
|
||||
const defaultExcludes = [
|
||||
'index-new.md',
|
||||
'mindmap builder.md',
|
||||
'color scheme manager.md',
|
||||
'comic strip director.md'
|
||||
];
|
||||
|
||||
// Combine both into a single Set for easy lookup
|
||||
const exclusions = new Set([...defaultExcludes, ...cmdLineExcludes]);
|
||||
|
||||
// Collect *.md files (non-recursive) excluding our combined list
|
||||
const files = fs
|
||||
.readdirSync(EA_SCRIPTS_DIR, { withFileTypes: true })
|
||||
.filter(
|
||||
(d) =>
|
||||
d.isFile() &&
|
||||
(d.name.endsWith('.md') || d.name.toLowerCase() === "mindmap builder.js") &&
|
||||
!exclusions.has(d.name.toLowerCase())
|
||||
)
|
||||
.map((d) => d.name)
|
||||
.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
|
||||
|
||||
for (const file of files) {
|
||||
const full = path.join(EA_SCRIPTS_DIR, file);
|
||||
let content = fs.readFileSync(full, 'utf8');
|
||||
|
||||
output += `\n---\n\n## ${file}\n`;
|
||||
output += `<!-- Source: ea-scripts/${file} -->\n\n`;
|
||||
|
||||
// Normalize line endings
|
||||
content = content.replace(/\r\n/g, '\n');
|
||||
|
||||
output += content.trimEnd() + '\n';
|
||||
|
||||
if (needsClosingFence(content)) {
|
||||
output += '```\n';
|
||||
console.log(`[script-library] Added missing closing fence to ${file}`);
|
||||
} else {
|
||||
console.log(`[script-library] Added ${file} (no fence fix needed)`);
|
||||
}
|
||||
}
|
||||
|
||||
fs.writeFileSync(SCRIPT_LIBRARY_OUT, output, 'utf8');
|
||||
console.log('[script-library] Wrote:', SCRIPT_LIBRARY_OUT);
|
||||
|
||||
// Generate TYPE_DEF_OUT from whitelist
|
||||
try {
|
||||
console.log('[script-library] Generating Type Definition Library...');
|
||||
const typeDefs = TYPE_DEF_INTRO + '\n' + buildTypeDefMarkdown();
|
||||
fs.writeFileSync(TYPE_DEF_OUT, typeDefs, 'utf8');
|
||||
console.log('[script-library] Wrote:', TYPE_DEF_OUT);
|
||||
} catch (e) {
|
||||
console.error('[script-library] Failed to generate TYPE_DEF_OUT:', e);
|
||||
}
|
||||
|
||||
// NEW: Generate AI_TRAINING_OUT
|
||||
try {
|
||||
console.log('[script-library] Generating AI Training bundle...');
|
||||
const typeDefContent = fs.existsSync(TYPE_DEF_OUT)
|
||||
? fs.readFileSync(TYPE_DEF_OUT, 'utf8')
|
||||
: (TYPE_DEF_INTRO + '\n' + buildTypeDefMarkdown());
|
||||
const scriptLibContent = fs.existsSync(SCRIPT_LIBRARY_OUT)
|
||||
? fs.readFileSync(SCRIPT_LIBRARY_OUT, 'utf8')
|
||||
: '';
|
||||
|
||||
// NEW: load startup template and example
|
||||
const startupTemplatePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_TEMPLATE.split('/'));
|
||||
const startupExamplePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_EXAMPLE.split('/'));
|
||||
const startupTemplate = fs.existsSync(startupTemplatePath)
|
||||
? fs.readFileSync(startupTemplatePath, 'utf8').replace(/\r\n/g, '\n').trim()
|
||||
: (console.warn('[script-library] Missing startup template:', EXCALIDRAW_STARTUP_TEMPLATE), '');
|
||||
const startupExample = fs.existsSync(startupExamplePath)
|
||||
? fs.readFileSync(startupExamplePath, 'utf8').replace(/\r\n/g, '\n').trim()
|
||||
: (console.warn('[script-library] Missing startup example:', EXCALIDRAW_STARTUP_EXAMPLE), '');
|
||||
|
||||
const startupSection =
|
||||
'\n---\n\n' +
|
||||
EXCALIDRAW_STARTUP_MESSAGE +
|
||||
'\n' +
|
||||
(startupTemplate
|
||||
? `<!-- ${EXCALIDRAW_STARTUP_TEMPLATE} -->\n${startupTemplate}\n\n`
|
||||
: '') +
|
||||
(startupExample
|
||||
? `<!-- ${EXCALIDRAW_STARTUP_EXAMPLE} -->\n${startupExample}\n`
|
||||
: '');
|
||||
|
||||
// NEW: Build ExcalidrawLib functions section
|
||||
const excalidrawLibFunctionsSection = buildExcalidrawLibFunctionsSection();
|
||||
|
||||
const combined =
|
||||
(AI_TRAINING_INTRO +
|
||||
'\n---\n\n' +
|
||||
typeDefContent.trim() +
|
||||
'\n\n---\n\n' +
|
||||
excalidrawLibFunctionsSection +
|
||||
'\n---\n\n' +
|
||||
scriptLibContent.trim() +
|
||||
startupSection +
|
||||
'\n')
|
||||
.replaceAll("https://youtu.be/", "YouTube: ")
|
||||
.replaceAll("https://www.youtube.com/watch?v=", "YouTube: ")
|
||||
.replaceAll("https://www.youtube.com/", "YouTube: "); // prevent accidental link triggering
|
||||
|
||||
fs.writeFileSync(AI_TRAINING_OUT, combined, 'utf8');
|
||||
console.log('[script-library] Wrote:', AI_TRAINING_OUT);
|
||||
} catch (e) {
|
||||
console.error('[script-library] Failed to generate AI_TRAINING_OUT:', e);
|
||||
}
|
||||
|
||||
console.log('[script-library] Done.');
|
||||
console.log('[script-library] Running unified documentation generator (full mode)...');
|
||||
const result = runUnifiedGeneration({
|
||||
mode: 'full',
|
||||
args: process.argv.slice(2),
|
||||
});
|
||||
console.log('[script-library] Wrote outputs:', result.generated);
|
||||
console.log('[script-library] Processed scripts:', result.scriptsProcessed);
|
||||
}
|
||||
|
||||
// ESM equivalent of `if (require.main === module)`
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
try {
|
||||
main();
|
||||
@@ -678,4 +20,4 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
console.error('[script-library] Failed:', e);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
/**
|
||||
* 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 };
|
||||
+9
-632
@@ -1,641 +1,18 @@
|
||||
/* eslint-disable no-console */
|
||||
// to run: node skill-builder.mjs
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
// Reconstruct __dirname for ES Modules
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const ROOT = path.resolve(__dirname, '..');
|
||||
const EA_SCRIPTS_DIR = path.join(ROOT, 'ea-scripts');
|
||||
const OUT_DIR = path.join(ROOT, 'docs', 'AITrainingData');
|
||||
|
||||
// Agent Skills Specific Definitions
|
||||
const SKILL_NAME = 'excalidraw-automate';
|
||||
const SKILL_DIR = path.join(OUT_DIR, SKILL_NAME);
|
||||
const SKILL_REFERENCES_DIR = path.join(SKILL_DIR, 'references');
|
||||
const SKILL_SCRIPTS_DIR = path.join(SKILL_REFERENCES_DIR, 'scripts');
|
||||
|
||||
const AI_TRAINING_INTRO = `**ExcalidrawAutomate full library for LLM training**
|
||||
|
||||
Excalidraw-Obsidian is an Obsidian.md plugins that is built on the open source Excalidraw component. Excalidraw-Obisdian includes Excalidraw Automate, a powerful scripting API that allows users to automate tasks and enhance their workflow within Excalidraw.
|
||||
|
||||
Read the information below and respond with I'm ready. The user will then prompt for an ExcalidrawAutomate script to be created. Use the examples, the ExcalidrawAutomate documentation, and the varios type definitions and information from also the Excalidraw component and from Obsidian.md to generate the script based on the user's requirements.
|
||||
|
||||
In addition to ExcalidrawAutomate, you can also use two other sources of functions:
|
||||
- The Excalidraw API available via \`ea.getExcalidrawAPI()\`. Note: the API is only available if \`ea.targetView\` is set. When running Excalidraw scripts using the script engine, the provided \`ea\` object is already set up with targetView by default. Otherwise you need to first run \`ea.setView()\`.
|
||||
- \`window.ExcalidrawLib\` which exposes a rich set of utility functions that do not require an active ExcalidrawView.
|
||||
|
||||
**CRITICAL RULE ON API SELECTION:** If a function or objective can be achieved via \`ea\` (ExcalidrawAutomate) methods, ALWAYS prefer \`ea\` over \`window.ExcalidrawLib\`. \`ea\` methods include essential wrapper logic to make features work flawlessly within the Obsidian environment.
|
||||
|
||||
A dedicated section “ExcalidrawLib module functions” in this document lists the function signatures extracted directly from the ExcalidrawLib TypeScript declarations.
|
||||
|
||||
- When the user asks for a dialog window, by default create a FloatingModal. Do not extend the FloatingModal class. Instead, define the modal's behavior by creating a new instance (e.g., \`const modal = new ea.FloatingModal(...)\`) and then assigning functions directly to the \`onOpen\` and \`onClose\` properties of that instance.
|
||||
For a reference, follow the implementation pattern used in the "Printable Layout Wizard.md" script.
|
||||
- Elements have a \`customData\` property that can be used to store arbitrary data. To ensure the data the script adds to elements use the \`ea.addAppendUpdateCustomData\` function. This function ensures that existing customData is preserved when adding new data.
|
||||
- Elements can be hidden by setting their opacity to 0. When hiding elements this way, it is good practice to temporarily store their original opacity in customData. This allows for easy restoration of the original opacity later.
|
||||
- Elements can be deleted from the scene by setting their isDeleted property to true.
|
||||
- The Obsidian.md module is available on \`ea.obsidian\`.
|
||||
|
||||
**Sidepanels and multi-view tooling:**
|
||||
- Sidepanels are for scripts that must stay open while users hop between multiple Excalidraw views. They should implement the SidepanelTab hooks (\`onOpen\`, \`onFocus(view)\`, \`onClose\`, \`onExcalidrawViewClosed\`) and manage their own \`ea.targetView\` explicitly.
|
||||
- Persisted sidepanel scripts are launched during plugin startup (e.g., Obsidian restart, plugin update) with \`ea.targetView === null\`. Scripts must handle this by deferring view-bound work until \`onFocus\` delivers a view; call \`ea.setView(view)\` when you decide to bind.
|
||||
- Each \`ea\` instance may host a single \`sidepanelTab\`. This sidepanel tab is stored in \`ea.sidepanelTab\`. Create the tab with \`ea.createSidepanelTab(title, persist=false, reveal=true)\`; the returned \`ea.sidepanelTab\` exposes \`contentEl\`, \`setContent\`, \`setTitle\`, \`setDisabled\`, \`setCloseCallback\`, \`open/close\`, and focus lifecycle hooks. Note auto-reveal during tab creation via \`ea.createSidepanelTab()\` is disabled during plugin startup. You can reveal a tab with \`ea.sidepanelTab?.open()\`. You can persist with \`ea.persistSidepanelTab()\` (tabs are restored and scripts re-run on next startup). Close with \`ea.sidepanelTab?.close()\`.
|
||||
- Mobile UX: sidepanels slide in without disturbing canvas layout and are better for longer forms than floating modals. Prefer them for complex inputs, especially on phones.
|
||||
- Auto-closing patterns: For scripts that use sidepanels but perform operations that are single-\`ExcalidrawView\` relevant, they can call \`ea.closeSidepanelTab()\` after completing the operation, and/or inside \`ea.sidepanelTab.onFocus = (view) => { if (view !== ea.targetView) { ea.sidepanelTab?.close(); } }\` to shut down when the user leaves the originating view.
|
||||
- Scripts can detect view change in \`onFocus(view)\` by comparing \`ea.targetView\` to the provided \`view\` parameter.
|
||||
- Persistence UX: scripts may offer a “Persist tab” control inside \`contentEl\` that calls \`ea.persistSidepanelTab()\`. Once persisted, hide that control; users can later remove the tab via the sidepanel close button (scripts cannot unpersist themselves, but can close themselves via \`ea.sidepanelTab?.close()\`).
|
||||
- Use \`checkForActiveSidepanelTabForScript\` to avoid creating duplicate tabs for the same script name. This method returns the \`ExcalidrawSidepanelTab\` associated with the supplied \`scriptName\` (or \`ea.activeScript\` when omitted), or \`null\` if none exists. It is intended to let a script detect an existing tab that may be owned by another \`ExcalidrawAutomate\` instance (for example, a persisted tab restored at startup). Typical pattern:
|
||||
- Before creating a new sidepanel, call \`ea.checkForActiveSidepanelTabForScript()\` to see if a tab already exists.
|
||||
- If a tab exists and \`tab.getHostEA() === ea\`, reuse it (your script already hosts it).
|
||||
- If a tab exists but is hosted by a different \`ea\` instance, decide whether to reuse or hand off control — e.g. open the existing tab and exit to avoid duplicates.
|
||||
- Note: persisted tabs restored on startup may be created with \`ea.targetView === null\` and hosted by a different \`ea\` instance; handle that case by waiting for \`onFocus\` before binding view-specific work.
|
||||
- Example usage:
|
||||
\`const sp = ea.checkForActiveSidepanelTabForScript();
|
||||
if (sp) {
|
||||
if (sp.getHostEA() === ea) {
|
||||
// we already own the tab — reuse it
|
||||
sp.open();
|
||||
} else {
|
||||
// another EA instance hosts the tab — open it for the user and exit
|
||||
sp.open();
|
||||
return;
|
||||
}
|
||||
}
|
||||
// no existing tab — safe to create a new one
|
||||
// ea.createSidepanelTab("My Script", false, true);\`
|
||||
- A dedicated section "sidepanelTabTypes.d.ts" in this document lists the \`ExcalidrawSidepanelTab\` function signatures.
|
||||
|
||||
#### **0. External Documentation & Resources**
|
||||
|
||||
To keep this training file concise, large external type definitions are not included. If you need to look up Obsidian APIs or Excalidraw internals, refer to the following resources:
|
||||
- **Obsidian API Type Definitions:** https://github.com/obsidianmd/obsidian-api/blob/master/obsidian.d.ts
|
||||
- **Obsidian Developer Docs:** https://docs.obsidian.md/Home (Community site with API and CSS documentation/examples)
|
||||
- **Obsidian Developer Forum:** https://forum.obsidian.md/c/developers-api/14
|
||||
- **ExcalidrawAutomate Implementation:** If the provided API documentation is unclear, consult the source directly: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/src/shared/ExcalidrawAutomate.ts
|
||||
- **Excalidraw Core Fork:** For doubts regarding core Excalidraw functionality, consult the fork used by the plugin: https://github.com/zsviczian/excalidraw
|
||||
|
||||
#### **1. The Core Workflow: Handling Element Immutability**
|
||||
|
||||
* **Central Rule:** Elements in the Excalidraw scene are immutable and should never be modified directly. Always use the ExcalidrawAutomate (EA) "workbench" pattern for modifications.
|
||||
* **The Workflow:**
|
||||
1. Get elements from the current view using \`ea.getViewElements()\` or \`ea.getViewSelectedElements()\`.
|
||||
2. Copy these elements into the EA workbench for editing using \`ea.copyViewElementsToEAforEditing(elements)\`.
|
||||
3. Modify the properties of the element copies that are now in the EA workbench (e.g., \`ea.getElement(id).locked = true;\`).
|
||||
4. Commit the changes back to the scene using \`await ea.addElementsToView()\`.
|
||||
* **Deletion:** To delete an element, set its \`isDeleted\` property to \`true\` on the workbench copy (\`ea.getElement(id).isDeleted = true;\`) and then commit with \`await ea.addElementsToView()\`.
|
||||
* **Cleanup:** Use \`ea.clear()\` at the beginning of a script if you are creating a completely new set of elements, to ensure the EA workbench is empty and doesn't contain artifacts from a previous run.
|
||||
|
||||
#### **2. User Interaction: Prompts and Dialogs**
|
||||
|
||||
* **Simple Input:** For straightforward user input, use the \`utils\` object provided to the script.
|
||||
* \`await utils.inputPrompt()\`: To get a string or number from the user.
|
||||
* \`await utils.suggester()\`: To let the user select from a predefined list of options.
|
||||
* **Complex Dialogs:** When a more complex UI with multiple controls is needed, create a floating dialog window.
|
||||
* **Use \`FloatingModal\`:** Always create a new instance: \`const modal = new ea.FloatingModal(ea.plugin.app);\`.
|
||||
* **Do Not Extend:** Do not use \`class MyModal extends ea.FloatingModal\`.
|
||||
* **Define Behavior:** Assign functions directly to the \`onOpen\` and \`onClose\` properties of the instance. Inside \`onOpen\`, use the \`modal.contentEl\` property to build your UI.
|
||||
* **Reference Implementation:** The script "Printable Layout Wizard.md" is the canonical example for this pattern. Use \`ea.obsidian.Setting\` to add controls like toggles and dropdowns within the modal.
|
||||
|
||||
#### **3. Element Manipulation and Querying**
|
||||
|
||||
* **Finding Elements:** The most common starting point is to get the user's selection with \`ea.getViewSelectedElements()\`. Use standard JavaScript array methods like \`.filter()\` to narrow down the selection (e.g., \`elements.filter(el => el.type === "text")\`).
|
||||
* **Geometric Calculations:**
|
||||
* Before performing layout or positioning tasks, use \`ea.getBoundingBox(elements)\` to get the collective dimensions and position of a group of elements.
|
||||
* Use \`ea.measureText(text)\` to determine the width and height of a string based on the current \`ea.style\` settings before creating a text element or a container for it.
|
||||
* **Grouping:**
|
||||
* To create a group, use \`ea.addToGroup([elementId1, elementId2, ...])\`.
|
||||
* To operate on existing groups within a selection, use \`ea.getMaximumGroups(selectedElements)\` which correctly identifies the top-level groups. Use \`ea.getLargestElement(group)\` to find the primary container within a group (e.g., the box around a text element).
|
||||
|
||||
#### **4. Styling: Creation vs. Modification**
|
||||
|
||||
* **For New Elements:** Set the properties on the global \`ea.style\` object *before* you call a creation function like \`ea.addText()\` or \`ea.addRect()\`. This acts like setting the active color/style on a paintbrush.
|
||||
* **For Existing Elements:** To change the style of an existing element, modify the properties directly on the element's copy in the EA workbench (after \`copyViewElementsToEAforEditing\`). For example: \`const myElement = ea.getElement(id); myElement.strokeColor = '#FF0000';\`.
|
||||
|
||||
#### **5. Data Persistence and Customization**
|
||||
|
||||
* **Storing Custom Data:** Elements have a \`customData\` property for arbitrary data.
|
||||
* **Always Use \`ea.addAppendUpdateCustomData(id, newData)\`:** This is crucial. It safely adds or updates your key-value pairs without overwriting data that might have been stored by other scripts or the Excalidraw plugin itself.
|
||||
* **Creating Configurable Scripts:** To make your script's behavior customizable by the user:
|
||||
* Use \`ea.getScriptSettings()\` to retrieve saved settings.
|
||||
* scriptSettings are stored with Excalidraw settings in Obsidian data.json. Keep this light. You MUST NEVER save large data objects such as base64 images or huge arrays here. Keep this lean and efficient.
|
||||
* Check if settings exist, and if not, define the default structure.
|
||||
* Use \`await ea.setScriptSettings(settings)\` to save any changes. This allows users to configure your script in the Excalidraw plugin settings pane.
|
||||
|
||||
#### **6. Best Practices and Advanced Techniques**
|
||||
|
||||
* **Script Overview Block (MANDATORY):** Create, and consistently maintain with each update, a comprehensive comment block at the very beginning of the script. This block must explain the purpose of the script, its key features, and the high-level solution logic or architecture.
|
||||
* **Strictly Modular Architecture (NO LOOSE CODE):** Avoid creating large monolithic blocks of code or leaving logic loose at the root level of the script. Instead, organize *everything* into relatively small, atomic functions. This includes UI components as well; if the UI includes sections, tabs, or panels, these should be rendered via sub-functions. This is a critical requirement to ensure long-term maintainability and evolution of the script, as loose code quickly becomes unmanageable over multiple iterative prompts.
|
||||
* **Evergreen JSDoc Headers and Comments:** Every function must have a proper JSDoc/Javadoc-style header containing parameter names, types, and a clear description of the function's purpose. These descriptions must be kept *evergreen* (updated alongside any code changes). Additionally, when modifying or updating a script, you must strictly *retain all existing internal code comments*.
|
||||
* **Isolate Constants and User-Facing Strings:** *Do not embed hardcoded magic values, config parameters, or UI strings deep inside the logic.* You must separate all constants and language strings and collect them at the very top of the file. This makes it easier to tweak values later and provides a clear, unified section for localization and customization.
|
||||
* **Icons:** Obsidian uses https://lucide.dev icons. These icons are available for scripts via \`ea.obsidian.getIcon("Icon Name")\`. For UI components prefer use of lucide.dev icons.
|
||||
* **Omit Version Verification:** While many of the sample scripts in the library include a version verification block at the outset (using \`ea.verifyMinimumPluginVersion\`), *do not add this section* when generating a new script unless explicitly instructed to do so.
|
||||
* **Embrace \`await\`:** Many EA functions are asynchronous and return a \`Promise\` (e.g., \`ea.addElementsToView()\`, \`ea.createSVG()\`, \`utils.inputPrompt()\`). **Always** use \`await\` when calling these functions to ensure your script executes in the correct order.
|
||||
* **Accessing Obsidian API:** The full Obsidian API is available via \`ea.obsidian\`. For example, use \`new ea.obsidian.Notice("message")\` or \`ea.obsidian.normalizePath(filepath)\`.
|
||||
* **Accessing Excalidraw API:** The full Excalidraw API is available on \`ea.getExcalidrawAPI()\`, these API functions are Scene dependent. Additional support functions are available on \`window.ExcalidrawLib\`.
|
||||
* **Visibility vs. Deletion:**
|
||||
* To temporarily hide an element, set \`element.opacity = 0\`. It's good practice to store the original opacity in \`customData\` so it can be restored. It is also recommended to lock hidden elements so they do not get accidentally selected or moved around.
|
||||
* To permanently remove an element from the scene, set \`element.isDeleted = true\`.
|
||||
* **Image Handling:** When dealing with image elements, use \`ea.getViewFileForImageElement(imageElement)\` to get the corresponding \`TFile\` from the Obsidian vault. This is necessary for any logic that needs to read or manipulate the source image file.
|
||||
|
||||
#### **7. SVG and Image Export Approaches**
|
||||
Generating images (SVG/PNG) requires specific approaches depending on the context. Follow these three rules strictly to avoid performance issues and missing assets:
|
||||
1. **Exporting elements currently in the EA workbench:** Use \`await ea.createSVG(null, ...)\` or \`await ea.createPNG(null, ...)\` (passing \`null\` as the \`templatePath\`).
|
||||
2. **Exporting an Excalidraw file that is NOT currently open:** Pass the file path as the template to \`createSVG\` or \`createPNG\` (e.g., \`await ea.createSVG(file.path, ...)\`). This is the most reliable approach as ExcalidrawAutomate natively handles loading the scene, resolving embedded images, and instantiating loaders behind the scenes. **Do NOT attempt to manually read the file, reconstruct the scene, or load images into memory.**
|
||||
3. **Exporting the currently active \`ExcalidrawView\`:** Use \`await ea.createViewSVG(...)\`. This is specifically for the open view. You can use the \`elementsOverride\` parameter to inject temporary elements (like transparent sizing rectangles) into the exported image without modifying the actual scene.
|
||||
|
||||
#### **8. Custom Pens and Perfect Freehand**
|
||||
|
||||
Excalidraw's freehand tool is powered by the open-source Perfect Freehand library. The plugin exposes “custom pens” that bundle:
|
||||
- Canvas style for the next strokes (colors, width, fillStyle, roughness).
|
||||
- Perfect Freehand stroke geometry and behavior (pressure simulation, outline, tapering, easing, etc.).
|
||||
|
||||
Key concepts:
|
||||
- AppState-driven drawing: When \`appState.currentStrokeOptions\` is set, the freedraw tool renders new strokes using those Perfect Freehand options.
|
||||
- Element-level persistence: If a freedraw element has \`element.customData.strokeOptions\`, it is rendered with those options regardless of the current tool state.
|
||||
- Types reference: See \`src/types/penTypes.ts\`. The \`PenOptions\` shape is:
|
||||
\`\`\`ts
|
||||
interface PenOptions {
|
||||
highlighter: boolean; // if true the pen is drawn at the lowest layer, behind all other elements
|
||||
constantPressure: boolean;
|
||||
hasOutline: boolean;
|
||||
outlineWidth: number;
|
||||
options: {
|
||||
thinning: number;
|
||||
smoothing: number;
|
||||
streamline: number;
|
||||
easing: string; // see supported names below
|
||||
start: { cap: boolean; taper: number | boolean; easing: string; };
|
||||
end: { cap: boolean; taper: number | boolean; easing: string; };
|
||||
};
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
Using custom pens from scripts:
|
||||
- Activate a custom pen for drawing:
|
||||
\`\`\`ts
|
||||
// obtain the Excalidraw API
|
||||
const api = ea.getExcalidrawAPI();
|
||||
|
||||
// define Perfect Freehand options (example similar to "finetip")
|
||||
const penOptions = {
|
||||
highlighter: false,
|
||||
constantPressure: true,
|
||||
hasOutline: false,
|
||||
outlineWidth: 1,
|
||||
options: {
|
||||
thinning: -0.5,
|
||||
smoothing: 0.4,
|
||||
streamline: 0.4,
|
||||
easing: "linear",
|
||||
start: { taper: 5, cap: false, easing: "linear" },
|
||||
end: { taper: 5, cap: false, easing: "linear" },
|
||||
},
|
||||
};
|
||||
|
||||
// apply stroke options + canvas style, then switch to freedraw (strokeWidth, color, background, fillStyle are optional)
|
||||
ea.viewUpdateScene({
|
||||
appState: {
|
||||
currentStrokeOptions: penOptions,
|
||||
currentItemStrokeWidth: 0.5,
|
||||
currentItemStrokeColor: "#3E6F8D",
|
||||
currentItemBackgroundColor: "transparent",
|
||||
currentItemFillStyle: "hachure",
|
||||
},
|
||||
});
|
||||
api.setActiveTool({ type: "freedraw" });
|
||||
\`\`\`
|
||||
|
||||
- Clear custom pen (revert to default freedraw behavior):
|
||||
\`\`\`ts
|
||||
ea.viewUpdateScene({ appState: { currentStrokeOptions: null } });
|
||||
\`\`\`
|
||||
|
||||
- Persist custom strokeOptions onto existing freedraw elements:
|
||||
\`\`\`ts
|
||||
const selected = ea.getViewSelectedElements().filter(el => el.type === "freedraw");
|
||||
ea.copyViewElementsToEAforEditing(selected);
|
||||
for (const el of selected) {
|
||||
ea.addAppendUpdateCustomData(el.id, { strokeOptions: penOptions });
|
||||
}
|
||||
await ea.addElementsToView();
|
||||
\`\`\`
|
||||
|
||||
Notes:
|
||||
- New strokes respect \`appState.currentStrokeOptions\` at draw time. Existing elements only change if you update their \`customData.strokeOptions\`.
|
||||
- For pens that should behave like real markers/highlighters, set \`highlighter: true\` and often \`constantPressure: true\` with an \`outlineWidth\` for the edge.
|
||||
|
||||
Supported easing names (string values for \`options.easing\`, \`options.start.easing\`, \`options.end.easing\`):
|
||||
linear, easeInQuad, easeOutQuad, easeInOutQuad, easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, easeInQuint, easeOutQuint, easeInOutQuint, easeInSine, easeOutSine, easeInOutSine, easeInExpo, easeOutExpo, easeInOutExpo, easeInCirc, easeOutCirc, easeInOutCirc, easeInBack, easeOutBack, easeInOutBack, easeInElastic, easeOutElastic, easeInOutElastic, easeInBounce, easeOutBounce, easeInOutBounce.
|
||||
|
||||
Example freedraw element carrying \`customData.strokeOptions\`:
|
||||
\`\`\`json
|
||||
{"type":"excalidraw/clipboard","elements":[{"id":"...","type":"freedraw","strokeColor":"#3E6F8D","backgroundColor":"transparent","fillStyle":"hachure","strokeWidth":0.5,"roughness":0,"customData":{"strokeOptions":{"highlighter":false,"hasOutline":false,"outlineWidth":0,"constantPressure":true,"options":{"smoothing":0.4,"thinning":-0.5,"streamline":0.4,"easing":"linear","start":{"taper":5,"cap":false,"easing":"linear"},"end":{"taper":5,"cap":false,"easing":"linear"}}}}}],"files":{}}
|
||||
\`\`\`
|
||||
|
||||
#### **9. Text Element**
|
||||
* There are three text properties.
|
||||
* **textElement.text** holds the wrapped, rendered text. This is what is displayed in the view. Excalidraw adds '\\n' linebreaks during dynamic wrapping.
|
||||
* **textElement.originalText** holds the rendered, but unwrapped text. Any '\\n' character in originalText is an intentional linebreak by the user. Rendered means that for example [[wiki links]] are rendered without the square brackets.
|
||||
* **textElement.rawText** holds the original raw text including intentional new line characters and the full markdown markup (thought currently only links are rendered, so markdown support is limited to these)
|
||||
* When modifying element text from script, typically all 3 of these properties must be updated, though in case textElement.autoresize === true, or when a text element is bound in a container, excalidraw will update textElement.text following the size of the text element or the container.
|
||||
|
||||
`;
|
||||
|
||||
const EXCALIDRAW_STARTUP_MESSAGE = `# Excalidraw Startup Script
|
||||
|
||||
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs automatically when the Excalidraw plugin is loaded to Obsidian. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
|
||||
`;
|
||||
const EXCALIDRAW_STARTUP_TEMPLATE = "src/constants/assets/startupScript.md";
|
||||
const EXCALIDRAW_STARTUP_EXAMPLE = "docs/AITrainingData/ExcalidrawStartupExample.md";
|
||||
|
||||
const TYPE_DEF_WHITELIST = [
|
||||
"lib/shared/ExcalidrawAutomate.d.ts",
|
||||
"lib/types/excalidrawAutomateTypes.d.ts",
|
||||
"lib/types/sidepanelTabTypes.d.ts",
|
||||
"lib/types/penTypes.d.ts",
|
||||
"lib/types/utilTypes.d.ts",
|
||||
"lib/types/exportUtilTypes.d.ts",
|
||||
"lib/types/embeddedFileLoaderTypes.d.ts",
|
||||
"lib/types/AIUtilTypes.d.ts",
|
||||
"node_modules/@zsviczian/excalidraw/types/element/src/types.d.ts",
|
||||
"node_modules/@zsviczian/excalidraw/types/excalidraw/types.d.ts",
|
||||
"node_modules/@zsviczian/excalidraw/types/element/src/bounds.d.ts",
|
||||
"node_modules/@zsviczian/excalidraw/types/excalidraw/components/App.d.ts",
|
||||
];
|
||||
|
||||
/**
|
||||
* Returns true if content contains at least one line starting with ```
|
||||
* and has an odd number of fences (unbalanced).
|
||||
*/
|
||||
function needsClosingFence(content) {
|
||||
const fenceCount = (content.match(/^```/gm) || []).length;
|
||||
return fenceCount > 0 && fenceCount % 2 === 1;
|
||||
}
|
||||
|
||||
function normalizeEOL(str) {
|
||||
return str.replace(/\r\n/g, '\n');
|
||||
}
|
||||
|
||||
function stripBOM(str) {
|
||||
return str.replace(/^\uFEFF/, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove top-of-file imports/references while preserving initial comments/blank lines.
|
||||
* Also removes bare "export {}" lines (module markers).
|
||||
*/
|
||||
function stripTopImports(content) {
|
||||
const lines = normalizeEOL(stripBOM(content)).split('\n');
|
||||
const out = [];
|
||||
let inTopRegion = true;
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
|
||||
const isImport =
|
||||
/^\s*import\s+type\s+/.test(line) ||
|
||||
/^\s*import\s+/.test(line) ||
|
||||
/^\s*import\(/.test(line);
|
||||
|
||||
const isTripleRef = /^\s*\/\/\/\s*<reference/.test(line);
|
||||
const isBareExportModule = /^\s*export\s*\{\s*\};?\s*$/.test(line);
|
||||
|
||||
if (inTopRegion) {
|
||||
if (isImport || isTripleRef) {
|
||||
continue;
|
||||
}
|
||||
const isBlank = /^\s*$/.test(line);
|
||||
const isLineComment = /^\s*\/\//.test(line);
|
||||
const isBlockCommentStart = /^\s*\/\*/.test(line);
|
||||
|
||||
if (!isBlank && !isLineComment && !isBlockCommentStart) {
|
||||
inTopRegion = false;
|
||||
}
|
||||
if (!isBareExportModule) out.push(line);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isBareExportModule) out.push(line);
|
||||
}
|
||||
|
||||
return out.join('\n').trim() + '\n';
|
||||
}
|
||||
|
||||
function makeSectionHeader(relPath) {
|
||||
const stars = '*'.repeat(Math.max(6, Math.min(38, relPath.length + 6)));
|
||||
return [
|
||||
`/* ${stars} */`,
|
||||
`/* ${relPath} */`,
|
||||
`/* ${stars} */`,
|
||||
].join('\n') + '\n';
|
||||
}
|
||||
|
||||
function buildTypeDefMarkdown() {
|
||||
const entries = TYPE_DEF_WHITELIST.map((rel) => ({
|
||||
rel,
|
||||
abs: path.join(ROOT, ...rel.split('/')),
|
||||
}));
|
||||
|
||||
let body = '# ExcalidrawAutomate library and related type definitions\n\n```js\n';
|
||||
for (const { rel, abs } of entries) {
|
||||
if (!fs.existsSync(abs)) {
|
||||
console.warn('[skill-builder] Whitelist file missing:', rel);
|
||||
continue;
|
||||
}
|
||||
let content = fs.readFileSync(abs, 'utf8');
|
||||
content = stripTopImports(content);
|
||||
|
||||
body += makeSectionHeader(rel);
|
||||
body += content.trimEnd() + '\n\n';
|
||||
}
|
||||
body += '```\n';
|
||||
return body;
|
||||
}
|
||||
|
||||
function resolveExcalModulePath(spec, excalIndexAbs) {
|
||||
const baseTypesRoot = path.join(ROOT, 'node_modules', '@zsviczian', 'excalidraw', 'types');
|
||||
if (spec.startsWith('@excalidraw/')) {
|
||||
const sub = spec.slice('@excalidraw/'.length);
|
||||
const parts = sub.split('/');
|
||||
const pkg = parts.shift();
|
||||
const rest = parts;
|
||||
if (!pkg) return null;
|
||||
const base = path.join(baseTypesRoot, pkg);
|
||||
if (rest.length === 0) {
|
||||
return path.join(base, 'src', 'index.d.ts');
|
||||
}
|
||||
return path.join(base, 'src', ...rest) + '.d.ts';
|
||||
}
|
||||
if (spec.startsWith('.')) {
|
||||
const dir = path.dirname(excalIndexAbs);
|
||||
return path.resolve(dir, spec) + '.d.ts';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function extractFunctionSignaturesFromModule(absPath, names) {
|
||||
const out = {};
|
||||
if (!absPath || !fs.existsSync(absPath)) {
|
||||
return out;
|
||||
}
|
||||
const content = fs.readFileSync(absPath, 'utf8');
|
||||
|
||||
for (const rawName of names) {
|
||||
const name = rawName.trim();
|
||||
if (!name) continue;
|
||||
|
||||
let m = content.match(new RegExp(`export\\s+declare\\s+function\\s+${name}[\\s\\S]*?;`, 'm'));
|
||||
if (m) {
|
||||
out[name] = m[0].trim();
|
||||
continue;
|
||||
}
|
||||
m = content.match(new RegExp(`(^|\\n)declare\\s+function\\s+${name}[\\s\\S]*?;`, 'm'));
|
||||
if (m) {
|
||||
out[name] = m[0].replace(/^\s*declare\s+/, 'export declare ').trim();
|
||||
continue;
|
||||
}
|
||||
m = content.match(new RegExp(`export\\s+declare\\s+const\\s+${name}\\s*:\\s*[\\s\\S]*?=>[\\s\\S]*?;`, 'm'));
|
||||
if (m) {
|
||||
out[name] = m[0].trim();
|
||||
continue;
|
||||
}
|
||||
m = content.match(new RegExp(`export\\s+declare\\s+(?:var|let|const)\\s+${name}\\s*:\\s*[\\s\\S]*?;`, 'm'));
|
||||
if (m && /=>/.test(m[0])) {
|
||||
out[name] = m[0].trim();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function buildExcalidrawLibFunctionsSection() {
|
||||
const excalIndexRel = 'node_modules/@zsviczian/excalidraw/types/excalidraw/index.d.ts';
|
||||
const excalIndexAbs = path.join(ROOT, ...excalIndexRel.split('/'));
|
||||
if (!fs.existsSync(excalIndexAbs)) {
|
||||
console.warn('[skill-builder] Missing Excalidraw index.d.ts:', excalIndexRel);
|
||||
return '';
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(excalIndexAbs, 'utf8');
|
||||
const reExport = /export\s*\{\s*([\s\S]*?)\s*\}\s*from\s*["']([^"']+)["'];/g;
|
||||
|
||||
const moduleToNames = new Map();
|
||||
for (const match of content.matchAll(reExport)) {
|
||||
const namesChunk = match[1];
|
||||
const spec = match[2];
|
||||
const names = namesChunk
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
if (!names.length) continue;
|
||||
const abs = resolveExcalModulePath(spec, excalIndexAbs);
|
||||
if (!abs) continue;
|
||||
const key = spec;
|
||||
const curr = moduleToNames.get(key) || { abs, names: new Set() };
|
||||
for (const n of names) curr.names.add(n);
|
||||
moduleToNames.set(key, curr);
|
||||
}
|
||||
|
||||
const seen = new Set();
|
||||
const sections = [];
|
||||
|
||||
for (const [spec, { abs, names }] of moduleToNames) {
|
||||
const sigs = extractFunctionSignaturesFromModule(abs, Array.from(names));
|
||||
const sigEntries = Object.entries(sigs)
|
||||
.filter(([name]) => {
|
||||
if (seen.has(name)) return false;
|
||||
seen.add(name);
|
||||
return true;
|
||||
})
|
||||
.sort(([a], [b]) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
|
||||
|
||||
if (!sigEntries.length) continue;
|
||||
|
||||
const rel = path.relative(ROOT, abs).replace(/\\/g, '/');
|
||||
const header = makeSectionHeader(`${spec} -> ${rel}`);
|
||||
sections.push(header + sigEntries.map(([, s]) => s).join('\n') + '\n');
|
||||
}
|
||||
|
||||
return '# ExcalidrawLib module functions\n\n' +
|
||||
'The following functions are exposed via window.ExcalidrawLib. Signatures are extracted from TypeScript declarations.\n\n' +
|
||||
'```ts\n' +
|
||||
sections.join('\n') +
|
||||
'```\n';
|
||||
}
|
||||
import { runUnifiedGeneration } from './excalidraw-docs-generator-core.mjs';
|
||||
|
||||
function main() {
|
||||
console.log('[skill-builder] Generating Excalidraw Agent Skill...');
|
||||
if (!fs.existsSync(EA_SCRIPTS_DIR)) {
|
||||
console.error('ea-scripts directory not found:', EA_SCRIPTS_DIR);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Ensure directories exist
|
||||
fs.mkdirSync(SKILL_DIR, { recursive: true });
|
||||
fs.mkdirSync(SKILL_REFERENCES_DIR, { recursive: true });
|
||||
|
||||
// Create or clean the scripts directory
|
||||
if (fs.existsSync(SKILL_SCRIPTS_DIR)) {
|
||||
fs.rmSync(SKILL_SCRIPTS_DIR, { recursive: true, force: true });
|
||||
}
|
||||
fs.mkdirSync(SKILL_SCRIPTS_DIR, { recursive: true });
|
||||
|
||||
// Read exclusions
|
||||
const args = process.argv.slice(2);
|
||||
const cmdLineExcludes = args.map(arg => arg.toLowerCase());
|
||||
const defaultExcludes = ['index-new.md', 'mindmap builder.md', 'color scheme manager.md', 'comic strip director.md'];
|
||||
const exclusions = new Set([...defaultExcludes, ...cmdLineExcludes]);
|
||||
|
||||
// Collect scripts
|
||||
const files = fs
|
||||
.readdirSync(EA_SCRIPTS_DIR, { withFileTypes: true })
|
||||
.filter(
|
||||
(d) =>
|
||||
d.isFile() &&
|
||||
(d.name.endsWith('.md') || d.name.toLowerCase() === "mindmap builder.js") &&
|
||||
!exclusions.has(d.name.toLowerCase())
|
||||
)
|
||||
.map((d) => d.name)
|
||||
.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
|
||||
|
||||
// Prepare API Index Map
|
||||
const apiIndex = {
|
||||
ExcalidrawAutomate: {},
|
||||
ExcalidrawAPI: {},
|
||||
ExcalidrawLib: {}
|
||||
};
|
||||
|
||||
function addUsage(category, method, scriptName) {
|
||||
// Filter out obvious noise or generic javascript attributes
|
||||
const ignoreList = ['length', 'push', 'map', 'filter', 'forEach', 'includes', 'join', 'toString', 'toLowerCase'];
|
||||
if (ignoreList.includes(method)) return;
|
||||
if (method.length < 2) return;
|
||||
|
||||
if (!apiIndex[category][method]) {
|
||||
apiIndex[category][method] = new Set();
|
||||
}
|
||||
apiIndex[category][method].add(scriptName);
|
||||
}
|
||||
|
||||
console.log('[skill-builder] Processing scripts and building API Index...');
|
||||
for (const file of files) {
|
||||
const full = path.join(EA_SCRIPTS_DIR, file);
|
||||
let content = fs.readFileSync(full, 'utf8').replace(/\r\n/g, '\n');
|
||||
|
||||
// Fix missing fences
|
||||
if (needsClosingFence(content)) {
|
||||
content += '\n```\n';
|
||||
}
|
||||
|
||||
// Write individual script to references/scripts/
|
||||
fs.writeFileSync(path.join(SKILL_SCRIPTS_DIR, file), content, 'utf8');
|
||||
|
||||
// Parse API Usage
|
||||
// 1. ExcalidrawAutomate: ea.functionName
|
||||
const eaMatches = [...content.matchAll(/ea\.([a-zA-Z0-9_]+)/g)];
|
||||
eaMatches.forEach(m => addUsage('ExcalidrawAutomate', m[1], file));
|
||||
|
||||
// 2. ExcalidrawAPI: api.functionName or ea.getExcalidrawAPI().functionName
|
||||
const apiMatches = [...content.matchAll(/(?:getExcalidrawAPI\(\)|api)\.([a-zA-Z0-9_]+)/g)];
|
||||
apiMatches.forEach(m => addUsage('ExcalidrawAPI', m[1], file));
|
||||
|
||||
// 3. ExcalidrawLib: ExcalidrawLib.functionName or window.ExcalidrawLib.functionName
|
||||
const libMatches = [...content.matchAll(/(?:window\.)?ExcalidrawLib\.([a-zA-Z0-9_]+)/g)];
|
||||
libMatches.forEach(m => addUsage('ExcalidrawLib', m[1], file));
|
||||
}
|
||||
|
||||
// Generate API Usage Index Markdown
|
||||
console.log('[skill-builder] Writing api-usage-index.md...');
|
||||
let apiIndexContent = `# Excalidraw API Usage Index\n\n`;
|
||||
apiIndexContent += `This index maps methods and properties from ExcalidrawAutomate (\`ea\`), ExcalidrawAPI, and ExcalidrawLib to the example scripts that use them. Use this to find real-world examples of how to implement specific features.\n\n`;
|
||||
|
||||
for (const [category, methods] of Object.entries(apiIndex)) {
|
||||
apiIndexContent += `## ${category}\n\n`;
|
||||
const sortedMethods = Object.keys(methods).sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
|
||||
|
||||
if (sortedMethods.length === 0) {
|
||||
apiIndexContent += `*No usages found.*\n\n`;
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const method of sortedMethods) {
|
||||
const scriptLinks = Array.from(methods[method])
|
||||
.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }))
|
||||
.map(script => `[${script}](scripts/${script.replace(/ /g, '%20')})`)
|
||||
.join(', ');
|
||||
|
||||
apiIndexContent += `- **${method}**: ${scriptLinks}\n`;
|
||||
}
|
||||
apiIndexContent += `\n`;
|
||||
}
|
||||
|
||||
fs.writeFileSync(path.join(SKILL_REFERENCES_DIR, 'api-usage-index.md'), apiIndexContent, 'utf8');
|
||||
|
||||
// Write Type Definitions
|
||||
console.log('[skill-builder] Writing type-definitions.md...');
|
||||
fs.writeFileSync(path.join(SKILL_REFERENCES_DIR, 'type-definitions.md'), buildTypeDefMarkdown(), 'utf8');
|
||||
|
||||
// Write ExcalidrawLib Functions
|
||||
console.log('[skill-builder] Writing excalidraw-lib-functions.md...');
|
||||
fs.writeFileSync(path.join(SKILL_REFERENCES_DIR, 'excalidraw-lib-functions.md'), buildExcalidrawLibFunctionsSection(), 'utf8');
|
||||
|
||||
// Write Startup Scripts template
|
||||
console.log('[skill-builder] Writing startup-scripts.md...');
|
||||
const startupTemplatePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_TEMPLATE.split('/'));
|
||||
const startupExamplePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_EXAMPLE.split('/'));
|
||||
const startupTemplate = fs.existsSync(startupTemplatePath)
|
||||
? fs.readFileSync(startupTemplatePath, 'utf8').replace(/\r\n/g, '\n').trim()
|
||||
: '';
|
||||
const startupExample = fs.existsSync(startupExamplePath)
|
||||
? fs.readFileSync(startupExamplePath, 'utf8').replace(/\r\n/g, '\n').trim()
|
||||
: '';
|
||||
|
||||
const startupSection = EXCALIDRAW_STARTUP_MESSAGE + '\n\n' +
|
||||
(startupTemplate ? `### Template\n\`\`\`js\n${startupTemplate}\n\`\`\`\n\n` : '') +
|
||||
(startupExample ? `### Example\n\`\`\`js\n${startupExample}\n\`\`\`\n` : '');
|
||||
|
||||
fs.writeFileSync(path.join(SKILL_REFERENCES_DIR, 'startup-scripts.md'), startupSection, 'utf8');
|
||||
|
||||
// Write SKILL.md
|
||||
console.log('[skill-builder] Writing SKILL.md...');
|
||||
const skillMdPath = path.join(SKILL_DIR, 'SKILL.md');
|
||||
const skillFrontmatter = `---
|
||||
name: ${SKILL_NAME}
|
||||
description: Write and manipulate ExcalidrawAutomate scripts for Obsidian.md. Use when the user wants to create, modify, or understand an Excalidraw script.
|
||||
---
|
||||
|
||||
`;
|
||||
|
||||
let skillIntro = AI_TRAINING_INTRO
|
||||
.replaceAll("https://youtu.be/", "YouTube: ")
|
||||
.replaceAll("https://www.youtube.com/watch?v=", "YouTube: ")
|
||||
.replaceAll("https://www.youtube.com/", "YouTube: ");
|
||||
|
||||
skillIntro += `
|
||||
## References
|
||||
The \`references/\` directory contains supporting documentation necessary for writing scripts:
|
||||
- \`references/type-definitions.md\`: Core type definitions for ExcalidrawAutomate.
|
||||
- \`references/excalidraw-lib-functions.md\`: Function signatures for \`window.ExcalidrawLib\`.
|
||||
- \`references/startup-scripts.md\`: ExcalidrawStartup script template and examples.
|
||||
- \`references/api-usage-index.md\`: A highly useful index mapping every API method (ea.*, api.*, ExcalidrawLib.*) to the specific example scripts that utilize them.
|
||||
- \`references/scripts/\`: A folder containing all the raw, real-world example scripts.
|
||||
|
||||
### How to use the Script Examples
|
||||
If you need to implement a specific function (e.g., \`ea.addElementsToView\`), do NOT guess its implementation context. Instead:
|
||||
1. Open \`references/api-usage-index.md\`.
|
||||
2. Find the function name.
|
||||
3. Note the scripts listed next to it.
|
||||
4. Read the corresponding script inside the \`references/scripts/\` directory to see a complete, working example of how the function is used in context.
|
||||
`;
|
||||
|
||||
fs.writeFileSync(skillMdPath, skillFrontmatter + skillIntro, 'utf8');
|
||||
console.log('[skill-builder] Done.');
|
||||
console.log('[skill-builder] Running unified documentation generator (full mode)...');
|
||||
const result = runUnifiedGeneration({
|
||||
mode: 'full',
|
||||
args: process.argv.slice(2),
|
||||
});
|
||||
console.log('[skill-builder] Wrote outputs:', result.generated);
|
||||
console.log('[skill-builder] Processed scripts:', result.scriptsProcessed);
|
||||
}
|
||||
|
||||
// ESM equivalent of `if (require.main === module)`
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
try {
|
||||
main();
|
||||
@@ -643,4 +20,4 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
console.error('[skill-builder] Failed:', e);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,17 @@
|
||||
/*
|
||||
#exclude
|
||||
```js*/
|
||||
/**
|
||||
* Startup scripts receive the plugin-global EA for the plugin lifetime and
|
||||
* utils.executionSource === "plugin-startup". Register cleanup for resources
|
||||
* outside EA so plugin reload/unload cannot accumulate them.
|
||||
*/
|
||||
// const ref = app.workspace.on("file-open", (file) => {});
|
||||
// ea.registerCleanup(() => app.workspace.offref(ref));
|
||||
//
|
||||
// const interval = window.setInterval(() => {}, 1000);
|
||||
// ea.registerCleanup(() => window.clearInterval(interval));
|
||||
|
||||
/**
|
||||
* If set, this callback is triggered when the user closes an Excalidraw view.
|
||||
* onViewUnloadHook: (view: ExcalidrawView) => void = null;
|
||||
@@ -317,4 +328,4 @@
|
||||
// elementCount: elements.length
|
||||
// });
|
||||
// }
|
||||
// };
|
||||
// };
|
||||
@@ -103,7 +103,7 @@ export const URL_REGISTRY = {
|
||||
UrlPurpose.SUPPORT,
|
||||
),
|
||||
COMMUNITY_SKETCH_YOUR_MIND_COM_WIKI: defineUrl(
|
||||
"https://community.sketch-your-mind.com/wiki",
|
||||
"https://community.sketch-your-mind.com/Wiki",
|
||||
UrlPurpose.SUPPORT,
|
||||
),
|
||||
WWW_YOUTUBE_COM_VISUALPKM: defineUrl(
|
||||
|
||||
+116
-42
@@ -34,10 +34,8 @@ import {
|
||||
DEVICE,
|
||||
setRootElementSize,
|
||||
} from "../constants/constants";
|
||||
import {
|
||||
ExcalidrawSettings,
|
||||
ExcalidrawSettingTab,
|
||||
} from "./settings";
|
||||
import { ExcalidrawSettingTab } from "./settings";
|
||||
import type { ExcalidrawSettings } from "./settingsDefaults";
|
||||
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
|
||||
import { initExcalidrawAutomate } from "src/utils/excalidrawAutomateUtils";
|
||||
import { t } from "../lang/helpers";
|
||||
@@ -48,7 +46,6 @@ import {
|
||||
getNewUniqueFilepath,
|
||||
} from "../utils/fileUtils";
|
||||
import {
|
||||
errorlog,
|
||||
isVersionNewerThanOther,
|
||||
versionUpdateCheckTimer,
|
||||
calculateUIModeValue,
|
||||
@@ -68,7 +65,7 @@ import {
|
||||
} from "./managers/MarkdownPostProcessor";
|
||||
import { FieldSuggester } from "../shared/Suggesters/FieldSuggester";
|
||||
import { ReleaseNotes } from "../shared/Dialogs/ReleaseNotes";
|
||||
import { DeviceType, Packages } from "../types/types";
|
||||
import { DeviceType, PackageLease, Packages } from "../types/types";
|
||||
import { PaneTarget } from "../types/utilTypes";
|
||||
import {
|
||||
emulateCTRLClickForLinks,
|
||||
@@ -114,6 +111,16 @@ import { PluginSettingsManager } from "./managers/PluginSettingsManager";
|
||||
import { FooterSafeAreaManager } from "./managers/FooterSafeAreaManager";
|
||||
import { FontManager } from "./managers/FontManager";
|
||||
import { StartupTimer } from "./managers/StartupTimer";
|
||||
import {
|
||||
ViewMigrationPersistenceHandoffManager,
|
||||
type ViewMigrationPersistenceHandoff,
|
||||
} from "./managers/ViewMigrationPersistenceHandoffManager";
|
||||
import {
|
||||
ViewMigrationHandoffManager,
|
||||
type ViewMigrationDrawingState,
|
||||
type ViewMigrationHandoffRegistration,
|
||||
type ViewMigrationHandoffRequest,
|
||||
} from "./managers/ViewMigrationHandoffManager";
|
||||
|
||||
declare const PLUGIN_VERSION: string;
|
||||
declare const INITIAL_TIMESTAMP: number;
|
||||
@@ -156,9 +163,12 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
private commandManager: CommandManager;
|
||||
private eventManager: EventManager;
|
||||
private settingsManager: PluginSettingsManager;
|
||||
private settingsTab: ExcalidrawSettingTab;
|
||||
private footerSafeAreaManager: FooterSafeAreaManager;
|
||||
private fontManager: FontManager;
|
||||
private startupTimer: StartupTimer;
|
||||
private viewMigrationHandoffManager: ViewMigrationHandoffManager;
|
||||
private viewMigrationPersistenceHandoffManager: ViewMigrationPersistenceHandoffManager;
|
||||
public stencilLibraryManager: StencilLibraryManager;
|
||||
public eaInstances = new WeakArray<ExcalidrawAutomate>();
|
||||
public fourthFontLoaded: boolean = false;
|
||||
@@ -202,6 +212,9 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
super(app, manifest);
|
||||
this.loadTimestamp = INITIAL_TIMESTAMP;
|
||||
this.startupTimer = new StartupTimer(this.loadTimestamp, PLUGIN_VERSION);
|
||||
this.viewMigrationHandoffManager = new ViewMigrationHandoffManager();
|
||||
this.viewMigrationPersistenceHandoffManager =
|
||||
new ViewMigrationPersistenceHandoffManager();
|
||||
this.filesMaster = new Map<
|
||||
FileId,
|
||||
{
|
||||
@@ -222,7 +235,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.settingsManager = new PluginSettingsManager(this);
|
||||
this.footerSafeAreaManager = new FooterSafeAreaManager(this);
|
||||
this.fontManager = new FontManager(this, () =>
|
||||
this.packageManager.getPackageMap(),
|
||||
this.packageManager.getRuntimePackage(),
|
||||
);
|
||||
|
||||
setExcalidrawPlugin(this);
|
||||
@@ -395,7 +408,8 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.settings.onceOffCompressFlagReset = true;
|
||||
await this.saveSettings();
|
||||
}
|
||||
this.addSettingTab(new ExcalidrawSettingTab(this.app, this));
|
||||
this.settingsTab = new ExcalidrawSettingTab(this.app, this);
|
||||
this.addSettingTab(this.settingsTab);
|
||||
this.settingsReady = true;
|
||||
}
|
||||
|
||||
@@ -564,7 +578,10 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
|
||||
public async awaitSettings() {
|
||||
let counter = 0;
|
||||
while (!this.settingsReady && counter < 150) {
|
||||
while (
|
||||
!this.settingsReady &&
|
||||
(counter < 150 || this.settingsManager.isAwaitingStartupRecoveryChoice)
|
||||
) {
|
||||
await sleep(20);
|
||||
counter++;
|
||||
}
|
||||
@@ -657,17 +674,16 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
|
||||
private registerInstallCodeblockProcessor() {
|
||||
const codeblockProcessor = async (source: string, el: HTMLElement) => {
|
||||
//Button next to the "List of available scripts" at the top
|
||||
//In try/catch block because this approach is very error prone, depends on
|
||||
//MarkdownRenderer() and index.md structure, in case these are not as
|
||||
//expected this code will break
|
||||
// The mirrored update button is only available in the Script Library
|
||||
// index layout. Other render contexts do not have the adjacent heading.
|
||||
let button2: HTMLButtonElement = null;
|
||||
try {
|
||||
const link: HTMLElement = el.parentElement.querySelector(
|
||||
`a[href="#${el.previousElementSibling.getAttribute(
|
||||
"data-heading",
|
||||
)}"]`,
|
||||
);
|
||||
const heading = el.previousElementSibling?.getAttribute("data-heading");
|
||||
const link = heading
|
||||
? Array.from(el.parentElement?.querySelectorAll("a") ?? []).find(
|
||||
(anchor) => anchor.getAttribute("href") === `#${heading}`,
|
||||
)
|
||||
: null;
|
||||
if (link?.parentElement) {
|
||||
link.addClass("excalidraw-installCodeBlock-link");
|
||||
button2 = link.parentElement.createEl("button", null, (b) => {
|
||||
b.setText(t("UPDATE_SCRIPT"));
|
||||
@@ -675,12 +691,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
setButtonBgColor(b, "success");
|
||||
hideElement(b);
|
||||
});
|
||||
} catch (e: unknown) {
|
||||
errorlog({
|
||||
where: "this.registerInstallCodeblockProcessor",
|
||||
source,
|
||||
error: e,
|
||||
});
|
||||
}
|
||||
|
||||
source = source.trim();
|
||||
@@ -748,6 +758,9 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
keepOriginal: boolean = false,
|
||||
): Promise<TFile> {
|
||||
const data = await this.app.vault.read(file);
|
||||
const hasEmbeddedFiles = Object.keys(
|
||||
(JSON_parse<{ files?: Record<string, unknown> }>(data).files ?? {}),
|
||||
).length > 0;
|
||||
const filename =
|
||||
file.name.substring(0, file.name.lastIndexOf(".excalidraw")) +
|
||||
(replaceExtension ? ".md" : ".excalidraw.md");
|
||||
@@ -757,11 +770,17 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
normalizePath(file.path.substring(0, file.path.lastIndexOf(file.name))),
|
||||
);
|
||||
log(fname);
|
||||
const result = await createOrOverwriteFile(
|
||||
this.app,
|
||||
fname,
|
||||
FRONTMATTER + (await this.fileManager.exportSceneToMD(data, false)),
|
||||
);
|
||||
const initialMarkdown =
|
||||
FRONTMATTER + (await this.fileManager.exportSceneToMD(data, false));
|
||||
const result = await createOrOverwriteFile(this.app, fname, initialMarkdown);
|
||||
if (hasEmbeddedFiles) {
|
||||
const convertedMarkdown =
|
||||
await this.fileManager.persistLegacySceneFilesInMarkdown(
|
||||
initialMarkdown,
|
||||
result,
|
||||
);
|
||||
await this.app.vault.modify(result, convertedMarkdown);
|
||||
}
|
||||
if (this.settings.keepInSync) {
|
||||
EXPORT_TYPES.forEach((ext: string) => {
|
||||
const oldIMGpath =
|
||||
@@ -808,18 +827,20 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const path = this.settings.startupScriptPath.endsWith(".md")
|
||||
? this.settings.startupScriptPath
|
||||
: `${this.settings.startupScriptPath}.md`;
|
||||
const path = this.scriptEngine.resolveStartupScriptPath(
|
||||
this.settings.startupScriptPath,
|
||||
);
|
||||
if (!path) {
|
||||
new Notice(t("STARTUP_SCRIPT_JS_DISABLED"));
|
||||
return;
|
||||
}
|
||||
const f = this.app.vault.getFileByPath(path);
|
||||
if (!f || !(f instanceof TFile)) {
|
||||
new Notice(`Startup script not found: ${path}`);
|
||||
return;
|
||||
}
|
||||
const script = await this.app.vault.read(f);
|
||||
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
|
||||
try {
|
||||
await new AsyncFunction("ea", script)(this.ea);
|
||||
await this.scriptEngine.executeStartupScript(f, this.ea);
|
||||
} catch (e) {
|
||||
new Notice(`Error running startup script: ${e}`);
|
||||
}
|
||||
@@ -967,11 +988,15 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.activeExcalidrawView = null;
|
||||
this.lastActiveExcalidrawFilePath = null;
|
||||
|
||||
this.settingsManager.destroy();
|
||||
this.settingsTab = null;
|
||||
this.settings = null;
|
||||
//pluginPackages = null;
|
||||
//PLUGIN_VERSION = null;
|
||||
delete window.PolyBool;
|
||||
this.packageManager.destroy();
|
||||
this.viewMigrationHandoffManager.destroy();
|
||||
this.viewMigrationPersistenceHandoffManager.destroy();
|
||||
this.commandManager?.destroy();
|
||||
this.eventManager.destroy();
|
||||
terminateCompressionWorker();
|
||||
@@ -989,10 +1014,17 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
await this.settingsManager.saveSettings();
|
||||
}
|
||||
|
||||
/** Refreshes the mounted settings tab after script-defined settings change. */
|
||||
public refreshSettingsTab(): void {
|
||||
this.settingsTab?.refreshAfterExternalSettingsChange();
|
||||
}
|
||||
|
||||
/** Reloads externally changed settings and invalidates cached libraries. */
|
||||
async onExternalSettingsChange() {
|
||||
await this.loadSettings();
|
||||
this.stencilLibraryManager?.invalidate();
|
||||
const didLoadSettings = await this.settingsManager.loadSettings();
|
||||
if (didLoadSettings) {
|
||||
this.stencilLibraryManager?.invalidate();
|
||||
}
|
||||
}
|
||||
|
||||
public async openSidepanel(
|
||||
@@ -1212,8 +1244,8 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.observerManager.removeThemeObserver();
|
||||
}
|
||||
|
||||
public addModalContainerObserver() {
|
||||
this.observerManager.addModalContainerObserver();
|
||||
public addModalContainerObserver(view?: ExcalidrawView) {
|
||||
this.observerManager.addModalContainerObserver(view);
|
||||
}
|
||||
|
||||
public removeModalContainerObserver() {
|
||||
@@ -1228,10 +1260,52 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
return this.packageManager.getPackage(win);
|
||||
}
|
||||
|
||||
/** Acquires explicit ownership of the runtime package for one view window. */
|
||||
public acquirePackage(win: Window): PackageLease {
|
||||
return this.packageManager.acquirePackage(win);
|
||||
}
|
||||
|
||||
public deletePackage(win: Window) {
|
||||
this.packageManager.deletePackage(win);
|
||||
}
|
||||
|
||||
/** Registers drawing-owned runtime state for one recreated view. */
|
||||
public registerViewMigrationHandoff(
|
||||
registration: ViewMigrationHandoffRegistration,
|
||||
): string {
|
||||
return this.viewMigrationHandoffManager.register(registration);
|
||||
}
|
||||
|
||||
/** Consumes validated drawing-owned runtime state for one recreated view. */
|
||||
public consumeViewMigrationHandoff(
|
||||
request: ViewMigrationHandoffRequest,
|
||||
): ViewMigrationDrawingState | null {
|
||||
return this.viewMigrationHandoffManager.consume(request);
|
||||
}
|
||||
|
||||
/** Registers serialized drawing text for a popout-to-main migration. */
|
||||
public registerViewMigrationPersistenceHandoff(
|
||||
handoff: ViewMigrationPersistenceHandoff,
|
||||
): void {
|
||||
this.viewMigrationPersistenceHandoffManager.register(handoff);
|
||||
}
|
||||
|
||||
/** Consumes serialized drawing text for the replacement main-window view. */
|
||||
public consumeViewMigrationPersistenceHandoff(
|
||||
leafId: string,
|
||||
filePath: string,
|
||||
): string | null {
|
||||
return this.viewMigrationPersistenceHandoffManager.consume(
|
||||
leafId,
|
||||
filePath,
|
||||
);
|
||||
}
|
||||
|
||||
/** Discards a handoff when the old view could not be replaced. */
|
||||
public discardViewMigrationPersistenceHandoff(leafId: string): void {
|
||||
this.viewMigrationPersistenceHandoffManager.discard(leafId);
|
||||
}
|
||||
|
||||
get taskbone() {
|
||||
return this.commandManager?.taskbone;
|
||||
}
|
||||
@@ -1314,14 +1388,14 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
|
||||
/**
|
||||
* Attaches an inline link suggester to the specified input element.
|
||||
* @param inputEl The HTML input element to attach the suggester to.
|
||||
* @param inputEl The text input element to attach the suggester to.
|
||||
* @param widthWrapper Optional HTML element to wrap the width of suggester element.
|
||||
* @param containerEl Optional container element used as collision boundary.
|
||||
* @param surpessPlaceholder Whether to suppress the placeholder text. Defaults to true.
|
||||
* @returns A KeyBlocker instance for managing keyboard input.
|
||||
*/
|
||||
public attachInlineLinkSuggester(
|
||||
inputEl: HTMLInputElement,
|
||||
inputEl: HTMLInputElement | HTMLTextAreaElement,
|
||||
widthWrapper?: HTMLElement,
|
||||
containerEl?: HTMLDivElement,
|
||||
surpessPlaceholder: boolean = true,
|
||||
|
||||
@@ -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";
|
||||
@@ -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,
|
||||
@@ -136,6 +136,12 @@ export class EventManager {
|
||||
),
|
||||
);
|
||||
|
||||
//theme/snippet toggles can change header/toolbar heights and shift the canvas
|
||||
//without firing layout-change; refresh cached canvas offsets the same way
|
||||
this.registerEvent(
|
||||
this.app.workspace.on("css-change", () => this.onLayoutChangeHandler()),
|
||||
);
|
||||
|
||||
//File Save Trigger Handlers
|
||||
//Save the drawing if the user clicks outside the Excalidraw Canvas
|
||||
const onClickEventSaveActiveDrawing = (e: PointerEvent) =>
|
||||
@@ -343,7 +349,7 @@ export class EventManager {
|
||||
this.previouslyActiveLeaf = leaf;
|
||||
|
||||
if (newActiveviewEV) {
|
||||
this.plugin.addModalContainerObserver();
|
||||
this.plugin.addModalContainerObserver(newActiveviewEV);
|
||||
this.plugin.lastActiveExcalidrawFilePath = newActiveviewEV.file?.path;
|
||||
} else {
|
||||
this.plugin.removeModalContainerObserver();
|
||||
|
||||
@@ -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,
|
||||
@@ -79,6 +79,16 @@ export class PluginFileManager {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether a vault file is an Excalidraw drawing.
|
||||
*
|
||||
* Parsed frontmatter is authoritative when available. During a vault write,
|
||||
* Obsidian can temporarily remove that frontmatter from the metadata cache;
|
||||
* in that gap, retain the last confirmed classification from
|
||||
* {@link excalidrawFiles}. The metadata `changed` event updates that set, so
|
||||
* deliberately removing the Excalidraw frontmatter still declassifies the
|
||||
* file once the replacement metadata is published.
|
||||
*/
|
||||
public isExcalidrawFile(f: TFile): boolean {
|
||||
if (!f) {
|
||||
return false;
|
||||
@@ -86,11 +96,12 @@ export class PluginFileManager {
|
||||
if (f.extension === "excalidraw") {
|
||||
return true;
|
||||
}
|
||||
const fileCache = f ? this.plugin.app.metadataCache.getFileCache(f) : null;
|
||||
return (
|
||||
!!fileCache?.frontmatter &&
|
||||
!!fileCache.frontmatter[FRONTMATTER_KEYS.plugin.name]
|
||||
);
|
||||
const frontmatter = this.plugin.app.metadataCache.getFileCache(f)?.frontmatter;
|
||||
if (frontmatter) {
|
||||
return !!frontmatter[FRONTMATTER_KEYS.plugin.name];
|
||||
}
|
||||
|
||||
return this.excalidrawFiles.has(f);
|
||||
}
|
||||
|
||||
//managing my own list of Excalidraw files because in the onDelete event handler
|
||||
@@ -537,6 +548,40 @@ export class PluginFileManager {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts binary files embedded in a converted legacy scene and rewrites
|
||||
* the Markdown drawing with durable vault attachment links.
|
||||
*
|
||||
* The target file must already exist because Obsidian determines its
|
||||
* attachment folder relative to that file. This method resolves only after
|
||||
* every embedded file has been persisted.
|
||||
*/
|
||||
public async persistLegacySceneFilesInMarkdown(
|
||||
markdown: string,
|
||||
file: TFile,
|
||||
): Promise<string> {
|
||||
const convertedData = new ExcalidrawData(this.plugin);
|
||||
try {
|
||||
const loaded = await convertedData.loadData(
|
||||
markdown,
|
||||
file,
|
||||
getTextMode(markdown),
|
||||
);
|
||||
if (!loaded) {
|
||||
throw new Error(`Failed to load converted drawing: ${file.path}`);
|
||||
}
|
||||
|
||||
convertedData.disableCompression = true;
|
||||
await convertedData.syncElements(convertedData.scene);
|
||||
return (
|
||||
FRONTMATTER +
|
||||
(await convertedData.generateMDAsync(convertedData.deletedElements))
|
||||
);
|
||||
} finally {
|
||||
convertedData.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------
|
||||
// ------------------ Event Handlers ---------------------
|
||||
// -------------------------------------------------------
|
||||
@@ -622,7 +667,10 @@ export class PluginFileManager {
|
||||
const excalidrawViews = getExcalidrawViews(this.app);
|
||||
excalidrawViews.forEach((excalidrawView) => {
|
||||
void (async () => {
|
||||
if (excalidrawView.semaphores?.viewunload) {
|
||||
if (
|
||||
excalidrawView.semaphores?.viewunload ||
|
||||
excalidrawView.semaphores?.windowMigrating
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
@@ -718,12 +766,13 @@ export class PluginFileManager {
|
||||
return;
|
||||
}
|
||||
//this will not work in the short period when Obsidian is starting up, however
|
||||
//this will only effect a very few files, statistically unlikely to cause
|
||||
//much/any real user impact.
|
||||
//a proper queuing feels overkill for this.
|
||||
//this will only affect very few files, statistically unlikely to cause
|
||||
//much/any real user impact. Flush the shared queue so a recently scheduled
|
||||
//backup is moved with the drawing instead of later recreating the old key.
|
||||
if (!getImageCache().isReady()) {
|
||||
return;
|
||||
}
|
||||
await getImageCache().flushPendingBAK(oldPath);
|
||||
const backup = await getImageCache().getBAKFromCache(oldPath);
|
||||
if (backup) {
|
||||
await getImageCache().addBAKToCache(newPath, `${backup}`);
|
||||
|
||||
@@ -17,7 +17,7 @@ declare const deliberateCreateElement: (
|
||||
tagName: string,
|
||||
) => HTMLStyleElement;
|
||||
|
||||
type PackageMapProvider = () => Map<Window, Packages>;
|
||||
type RuntimePackageProvider = () => Packages;
|
||||
|
||||
/**
|
||||
* Owns CJK and custom-font discovery, registration, document stylesheets, and
|
||||
@@ -30,7 +30,7 @@ export class FontManager {
|
||||
|
||||
public constructor(
|
||||
private readonly plugin: ExcalidrawPlugin,
|
||||
private readonly getPackageMap: PackageMapProvider,
|
||||
private readonly getRuntimePackage: RuntimePackageProvider,
|
||||
) {}
|
||||
|
||||
/** Whether font initialization permits the plugin readiness wait to finish. */
|
||||
@@ -76,7 +76,7 @@ export class FontManager {
|
||||
|
||||
/**
|
||||
* Loads configured CJK and custom fonts into every open Obsidian document
|
||||
* and registers custom font metrics with each window-scoped Excalidraw package.
|
||||
* and registers custom font metrics with the shared Excalidraw runtime.
|
||||
*/
|
||||
public async initializeFonts(): Promise<void> {
|
||||
const cjkFontDataURLs = await getCJKDataURLs(this.plugin);
|
||||
@@ -128,15 +128,13 @@ export class FontManager {
|
||||
lineHeight: 1.2,
|
||||
};
|
||||
}
|
||||
this.getPackageMap().forEach(({ excalidrawLib }) => {
|
||||
if (!fontMetrics) {
|
||||
return;
|
||||
}
|
||||
const { excalidrawLib } = this.getRuntimePackage();
|
||||
if (fontMetrics) {
|
||||
excalidrawLib.registerLocalFont(
|
||||
{ metrics: fontMetrics },
|
||||
fourthFontDataURL,
|
||||
);
|
||||
});
|
||||
}
|
||||
for (const ownerDocument of this.getOpenObsidianDocuments()) {
|
||||
await this.addFonts(
|
||||
[
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { App } from "obsidian";
|
||||
import { DEVICE } from "src/constants/constants";
|
||||
import type { ExcalidrawSettings } from "src/core/settings";
|
||||
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
|
||||
import { isInstanceOfHTMLStyleElement } from "src/utils/typechecks";
|
||||
|
||||
declare const mainDocument: Document;
|
||||
|
||||
@@ -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,
|
||||
@@ -41,6 +41,7 @@ import { linkPrompt } from "../../shared/Dialogs/Prompt";
|
||||
import {
|
||||
isInstanceOfHTMLElement,
|
||||
isInstanceOfHTMLImageElement,
|
||||
isInstanceOfSVGSVGElement,
|
||||
isInstanceOfSVGElement,
|
||||
} from "../../utils/typechecks";
|
||||
import { ExportSettings } from "src/types/exportUtilTypes";
|
||||
@@ -150,7 +151,9 @@ const _getPNG = async ({
|
||||
};
|
||||
|
||||
if (cacheReady) {
|
||||
const src = await getImageCache().getImageFromCache(cacheKey);
|
||||
const src = await getImageCache().getImageFromCache(cacheKey, {
|
||||
expectedPayloadKind: "raster",
|
||||
});
|
||||
if (src && typeof src === "string") {
|
||||
img.src = src;
|
||||
return img;
|
||||
@@ -288,7 +291,10 @@ const _getSVGIMG = async ({
|
||||
};
|
||||
|
||||
if (cacheReady) {
|
||||
const src = await getImageCache().getImageFromCache(cacheKey);
|
||||
const src = await getImageCache().getImageFromCache(cacheKey, {
|
||||
expectedPayloadKind: "svg",
|
||||
svgFormat: "data-url",
|
||||
});
|
||||
if (src && typeof src === "string") {
|
||||
img.setAttribute("src", src);
|
||||
return img;
|
||||
@@ -380,11 +386,13 @@ const _getSVGNative = async ({
|
||||
};
|
||||
let maybeSVG;
|
||||
if (cacheReady) {
|
||||
maybeSVG = await getImageCache().getImageFromCache(cacheKey);
|
||||
maybeSVG = await getImageCache().getImageFromCache(cacheKey, {
|
||||
expectedPayloadKind: "svg",
|
||||
});
|
||||
}
|
||||
|
||||
const svg =
|
||||
maybeSVG && maybeSVG instanceof SVGSVGElement
|
||||
maybeSVG && isInstanceOfSVGSVGElement(maybeSVG)
|
||||
? maybeSVG
|
||||
: convertSVGStringToElement(
|
||||
(
|
||||
|
||||
@@ -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 {
|
||||
@@ -11,14 +12,30 @@ import {
|
||||
isInstanceOfDocumentFragment,
|
||||
isInstanceOfElement,
|
||||
} from "src/utils/typechecks";
|
||||
import type ExcalidrawView from "src/view/ExcalidrawView";
|
||||
|
||||
declare const mainDocument: Document;
|
||||
const MODAL_CONTAINER_SELECTOR = ".modal-container";
|
||||
|
||||
/**
|
||||
* Checks an observed DOM node without relying on cross-window constructors.
|
||||
*
|
||||
* Mutation records can contain nodes from an Obsidian popout realm whose
|
||||
* `instanceof Element` identity is not reliable after window migration.
|
||||
*/
|
||||
const isObservedElement = (node: Node): node is Element =>
|
||||
node.nodeType === 1 && typeof (node as Element).matches === "function";
|
||||
|
||||
export class ObserverManager {
|
||||
private plugin: ExcalidrawPlugin;
|
||||
private app: App;
|
||||
private themeObserver: MutationObserver | CustomMutationObserver;
|
||||
private fileExplorerObserver: MutationObserver | CustomMutationObserver;
|
||||
private modalContainerObserver: MutationObserver | CustomMutationObserver;
|
||||
private modalContainerObserver:
|
||||
| MutationObserver
|
||||
| CustomMutationObserver
|
||||
| null = null;
|
||||
private modalObservedView: ExcalidrawView | null = null;
|
||||
private workspaceDrawerLeftObserver:
|
||||
| MutationObserver
|
||||
| CustomMutationObserver;
|
||||
@@ -49,7 +66,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");
|
||||
@@ -266,51 +283,70 @@ export class ObserverManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Monitors if the user clicks outside the Excalidraw view, and saves the drawing if it's dirty
|
||||
* @returns
|
||||
* Saves a dirty drawing when an Obsidian modal opens in its live document.
|
||||
*
|
||||
* @param view - The active or same-leaf replacement view to observe.
|
||||
*/
|
||||
public addModalContainerObserver() {
|
||||
if (!this.plugin.activeExcalidrawView) {
|
||||
public addModalContainerObserver(view = this.plugin.activeExcalidrawView) {
|
||||
if (!view) {
|
||||
return;
|
||||
}
|
||||
const activeViewDoc = view.containerEl.ownerDocument;
|
||||
if (this.modalContainerObserver) {
|
||||
if (
|
||||
this.activeViewDoc === this.plugin.activeExcalidrawView.ownerDocument
|
||||
this.activeViewDoc === activeViewDoc &&
|
||||
this.modalObservedView === view
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.removeModalContainerObserver();
|
||||
}
|
||||
//The user clicks settings, or "open another vault", or the command palette
|
||||
//The user clicks settings, or "open another vault", or the command palette.
|
||||
//Other body portals, including inline suggestions, must not interrupt editing with a save.
|
||||
const modalContainerObserverFn: MutationCallback = (
|
||||
m: MutationRecord[],
|
||||
mutations: MutationRecord[],
|
||||
) => {
|
||||
const view = this.plugin.activeExcalidrawView;
|
||||
const observedView = this.modalObservedView;
|
||||
const addedNodes = mutations.flatMap((mutation) =>
|
||||
mutation.type === "childList"
|
||||
? Array.from(mutation.addedNodes)
|
||||
: [],
|
||||
);
|
||||
const modalOpened = addedNodes.some(
|
||||
(node) =>
|
||||
isObservedElement(node) &&
|
||||
(node.matches(MODAL_CONTAINER_SELECTOR) ||
|
||||
node.querySelector(MODAL_CONTAINER_SELECTOR) !== null),
|
||||
);
|
||||
if (
|
||||
m.length !== 1 ||
|
||||
m[0].type !== "childList" ||
|
||||
m[0].addedNodes.length !== 1 ||
|
||||
!view ||
|
||||
view.semaphores?.viewunload ||
|
||||
!view.isDirty()
|
||||
!modalOpened ||
|
||||
!observedView ||
|
||||
observedView.semaphores?.viewunload ||
|
||||
!observedView.isDirty() ||
|
||||
!observedView.excalidrawAPI
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { errorMessage } = view.excalidrawAPI.getAppState();
|
||||
const { errorMessage } = observedView.excalidrawAPI.getAppState();
|
||||
if (!errorMessage) {
|
||||
void this.plugin.activeExcalidrawView.save();
|
||||
void observedView.save();
|
||||
}
|
||||
};
|
||||
|
||||
this.activeViewDoc = activeViewDoc;
|
||||
this.modalObservedView = view;
|
||||
// Keep the observer constructor and target in the same window realm so a
|
||||
// migrated view never depends on its destroyed source window.
|
||||
this.modalContainerObserver = DEBUGGING
|
||||
? new CustomMutationObserver(
|
||||
modalContainerObserverFn,
|
||||
"modalContainerObserver",
|
||||
)
|
||||
: new MutationObserver(modalContainerObserverFn);
|
||||
this.activeViewDoc = this.plugin.activeExcalidrawView.ownerDocument;
|
||||
this.modalContainerObserver.observe(this.activeViewDoc.body, {
|
||||
: new (activeViewDoc.defaultView?.MutationObserver ?? MutationObserver)(
|
||||
modalContainerObserverFn,
|
||||
);
|
||||
this.modalContainerObserver.observe(activeViewDoc.body, {
|
||||
childList: true,
|
||||
});
|
||||
}
|
||||
@@ -320,8 +356,9 @@ export class ObserverManager {
|
||||
return;
|
||||
}
|
||||
this.modalContainerObserver.disconnect();
|
||||
this.activeViewDoc = null;
|
||||
this.modalContainerObserver = null;
|
||||
this.modalObservedView = null;
|
||||
this.activeViewDoc = null;
|
||||
}
|
||||
|
||||
private addWorkspaceDrawerObserver() {
|
||||
|
||||
+211
-130
@@ -1,31 +1,52 @@
|
||||
import { updateExcalidrawLib } from "src/constants/constants";
|
||||
import { ExcalidrawLib } from "../../types/excalidrawLib";
|
||||
import { Packages } from "../../types/types";
|
||||
import { PackageLease, Packages } from "../../types/types";
|
||||
import { Notice } from "obsidian";
|
||||
import 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 * as ReactDOMLegacy from "react-dom";
|
||||
import * as ReactDOMClient from "react-dom/client";
|
||||
import * as ReactJSXRuntime from "react/jsx-runtime";
|
||||
import * as ReactJSXDevRuntime from "react/jsx-dev-runtime";
|
||||
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;
|
||||
|
||||
export class PackageManager {
|
||||
private packageMap: Map<Window, Packages> = new Map<Window, Packages>();
|
||||
private EXCALIDRAW_PACKAGE: string;
|
||||
private plugin: ExcalidrawPlugin;
|
||||
private fallbackPackage: Packages | null = null;
|
||||
const reactDOM = Object.assign({}, ReactDOMLegacy, ReactDOMClient);
|
||||
const reactJSXDevRuntime = Object.assign({}, ReactJSXDevRuntime, {
|
||||
// React's production jsx-dev-runtime deliberately leaves jsxDEV undefined,
|
||||
// while the Excalidraw artifact accepts either external runtime entrypoint.
|
||||
jsxDEV: ReactJSXDevRuntime.jsxDEV ?? ReactJSXRuntime.jsx,
|
||||
});
|
||||
|
||||
constructor(plugin: ExcalidrawPlugin) {
|
||||
this.plugin = plugin;
|
||||
const normalizeError = (error: unknown): Error =>
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error(typeof error === "string" ? error : "Unknown error");
|
||||
|
||||
/**
|
||||
* Owns the plugin's single private React/Excalidraw runtime.
|
||||
*
|
||||
* Each view receives the same package but retains an idempotent lease keyed by
|
||||
* its actual window. The window key governs migration persistence and the
|
||||
* temporary `ExcalidrawLib` compatibility alias only; rendering ownership is
|
||||
* supplied independently through each Excalidraw instance's `ownerDocument`.
|
||||
*/
|
||||
export class PackageManager {
|
||||
private runtimePackage: Packages | null = null;
|
||||
private packageLeaseCountMap = new Map<Window, number>();
|
||||
private commonHostDisposer: (() => void) | null = null;
|
||||
private excalidrawHostDisposer: (() => void) | null = null;
|
||||
private runtimeAliasWindows = new Set<Window>();
|
||||
|
||||
constructor(private readonly plugin: ExcalidrawPlugin) {
|
||||
let excalidrawPackage = "";
|
||||
|
||||
try {
|
||||
this.EXCALIDRAW_PACKAGE = unpackExcalidraw();
|
||||
excalidrawPackage = unpackExcalidraw();
|
||||
|
||||
// Evaluate Excalidraw in the main window with the same private React
|
||||
// instance used by the plugin bundle. The runtime is passed explicitly
|
||||
@@ -33,23 +54,23 @@ export class PackageManager {
|
||||
const loadExcalidraw = errorHandler.safeEval<
|
||||
(
|
||||
reactInstance: typeof React,
|
||||
reactDOMInstance: typeof ReactDOM,
|
||||
reactDOMInstance: typeof reactDOM,
|
||||
jsxRuntime: unknown,
|
||||
jsxDevRuntime: unknown,
|
||||
) => typeof ExcalidrawLib
|
||||
>(
|
||||
`(function(React, ReactDOM, ReactJSXRuntime, ReactJSXDevRuntime) {
|
||||
${this.EXCALIDRAW_PACKAGE};
|
||||
${excalidrawPackage};
|
||||
return ExcalidrawLib;
|
||||
})`,
|
||||
"PackageManager constructor - excalidrawLib initialization",
|
||||
window,
|
||||
);
|
||||
excalidrawLib = loadExcalidraw(
|
||||
react,
|
||||
React,
|
||||
reactDOM,
|
||||
ReactJSXRuntime,
|
||||
ReactJSXDevRuntime,
|
||||
reactJSXDevRuntime,
|
||||
);
|
||||
|
||||
if (!excalidrawLib) {
|
||||
@@ -60,22 +81,29 @@ export class PackageManager {
|
||||
updateExcalidrawLib();
|
||||
|
||||
// Create a package with the loaded libraries
|
||||
const initialPackage = { react, reactDOM, excalidrawLib };
|
||||
const initialPackage = { react: React, reactDOM, excalidrawLib };
|
||||
|
||||
// Validate the package before storing
|
||||
if (this.validatePackage(initialPackage)) {
|
||||
this.setPackage(window, initialPackage);
|
||||
this.fallbackPackage = initialPackage; // Store a valid package as fallback
|
||||
this.setRuntimePackage(initialPackage);
|
||||
} else {
|
||||
throw new Error("Invalid initial package");
|
||||
}
|
||||
} 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,
|
||||
);
|
||||
console.error("Error loading the Excalidraw package", e);
|
||||
} finally {
|
||||
// Per-window evaluation has been removed. Release the decompressed
|
||||
// Excalidraw source after the one runtime is initialized instead of
|
||||
// retaining it for hypothetical future popouts.
|
||||
excalidrawPackage = "";
|
||||
}
|
||||
|
||||
plugin.logStartupEvent("Excalidraw package unpacked");
|
||||
@@ -105,141 +133,194 @@ export class PackageManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a package for a specific window
|
||||
* Registers plugin capabilities with one evaluated Excalidraw runtime.
|
||||
*/
|
||||
public setPackage(window: Window, pkg: Packages) {
|
||||
if (this.validatePackage(pkg)) {
|
||||
this.packageMap.set(window, pkg);
|
||||
private configureObsidianCommonHost(pkg: Packages): void {
|
||||
this.commonHostDisposer?.();
|
||||
this.commonHostDisposer = null;
|
||||
|
||||
// Update fallback if we don't have one
|
||||
if (!this.fallbackPackage) {
|
||||
this.fallbackPackage = pkg;
|
||||
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.commonHostDisposer = lib.configureObsidianCommonHost(adapter);
|
||||
}
|
||||
|
||||
/** Registers plugin-wide settings with one evaluated Excalidraw runtime. */
|
||||
private configureObsidianExcalidrawHost(pkg: Packages): void {
|
||||
this.excalidrawHostDisposer?.();
|
||||
this.excalidrawHostDisposer = null;
|
||||
|
||||
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.excalidrawHostDisposer =
|
||||
lib.configureObsidianExcalidrawHost(adapter);
|
||||
}
|
||||
|
||||
/** Disposes the plugin capabilities registered with the shared runtime. */
|
||||
private disposeObsidianHosts(): void {
|
||||
this.commonHostDisposer?.();
|
||||
this.commonHostDisposer = null;
|
||||
this.excalidrawHostDisposer?.();
|
||||
this.excalidrawHostDisposer = null;
|
||||
}
|
||||
|
||||
/** Stores and configures the plugin's single evaluated runtime package. */
|
||||
private setRuntimePackage(pkg: Packages): void {
|
||||
if (this.validatePackage(pkg)) {
|
||||
try {
|
||||
this.configureObsidianCommonHost(pkg);
|
||||
this.configureObsidianExcalidrawHost(pkg);
|
||||
} catch (error: unknown) {
|
||||
this.disposeObsidianHosts();
|
||||
throw normalizeError(error);
|
||||
}
|
||||
this.runtimePackage = pkg;
|
||||
} else {
|
||||
errorHandler.handleError(
|
||||
"Attempted to set invalid package",
|
||||
"PackageManager.setPackage",
|
||||
"PackageManager.setRuntimePackage",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public getPackageMap() {
|
||||
return this.packageMap;
|
||||
/** Returns the one runtime used by every main-window and popout view. */
|
||||
public getRuntimePackage(): Packages {
|
||||
if (!this.runtimePackage || !this.validatePackage(this.runtimePackage)) {
|
||||
throw new Error("Excalidraw runtime package is unavailable");
|
||||
}
|
||||
return this.runtimePackage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a package for a window, creating it if necessary
|
||||
* with robust error handling
|
||||
* Acquires the shared runtime while retaining the view's actual window.
|
||||
*
|
||||
* @remarks
|
||||
* Window identity remains view-owned migration/persistence state. Popout
|
||||
* leases additionally own the temporary `window.ExcalidrawLib` compatibility
|
||||
* alias and remove it when the final view in that window releases its lease.
|
||||
*/
|
||||
public acquirePackage(win: Window): PackageLease {
|
||||
const packages = this.getPackage(win);
|
||||
const leaseCount = (this.packageLeaseCountMap.get(win) ?? 0) + 1;
|
||||
this.packageLeaseCountMap.set(win, leaseCount);
|
||||
|
||||
let released = false;
|
||||
return {
|
||||
window: win,
|
||||
packages,
|
||||
release: () => {
|
||||
if (released) {
|
||||
return;
|
||||
}
|
||||
released = true;
|
||||
this.releasePackageLease(win);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Releases one view-owned package lease without consulting mutable DOM. */
|
||||
private releasePackageLease(win: Window): void {
|
||||
const leaseCount = this.packageLeaseCountMap.get(win);
|
||||
if (leaseCount === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const remainingLeases = Math.max(0, leaseCount - 1);
|
||||
if (remainingLeases === 0) {
|
||||
this.packageLeaseCountMap.delete(win);
|
||||
if (win !== window) {
|
||||
this.removeRuntimeAlias(win);
|
||||
}
|
||||
} else {
|
||||
this.packageLeaseCountMap.set(win, remainingLeases);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the shared runtime and exposes its compatibility API in `win`.
|
||||
*
|
||||
* @remarks
|
||||
* The runtime is never evaluated in the supplied window. Rendering ownership
|
||||
* is provided separately through Excalidraw's stable `ownerDocument` prop.
|
||||
*/
|
||||
public getPackage(win: Window): Packages {
|
||||
try {
|
||||
// Return existing package if available
|
||||
if (this.packageMap.has(win)) {
|
||||
const pkg = this.packageMap.get(win);
|
||||
if (this.validatePackage(pkg)) {
|
||||
return pkg;
|
||||
}
|
||||
// If package exists but is invalid, delete it so we can recreate it
|
||||
this.packageMap.delete(win);
|
||||
}
|
||||
|
||||
// Create new package
|
||||
return errorHandler.wrapWithTryCatch(
|
||||
() => {
|
||||
// Use safe evaluation to load packages in the window context
|
||||
const evalResult = errorHandler.safeEval<{
|
||||
react: typeof React;
|
||||
reactDOM: typeof ReactDOM;
|
||||
excalidrawLib: typeof ExcalidrawLib;
|
||||
}>(
|
||||
`(function() {
|
||||
${REACT_PACKAGES + this.EXCALIDRAW_PACKAGE};
|
||||
return {
|
||||
react: React,
|
||||
reactDOM: ReactDOM,
|
||||
excalidrawLib: ExcalidrawLib,
|
||||
};
|
||||
})()`,
|
||||
"PackageManager.getPackage - package evaluation",
|
||||
win,
|
||||
);
|
||||
|
||||
if (!evalResult || !this.validatePackage(evalResult)) {
|
||||
throw new Error("Failed to create valid package");
|
||||
}
|
||||
|
||||
const newPackage = {
|
||||
react: evalResult.react,
|
||||
reactDOM: evalResult.reactDOM,
|
||||
excalidrawLib: evalResult.excalidrawLib,
|
||||
};
|
||||
|
||||
this.packageMap.set(win, newPackage);
|
||||
return newPackage;
|
||||
},
|
||||
"PackageManager.getPackage",
|
||||
this.fallbackPackage,
|
||||
);
|
||||
} catch (error) {
|
||||
errorHandler.handleError(error, "PackageManager.getPackage");
|
||||
|
||||
// Return fallback package if available to prevent data loss
|
||||
if (this.fallbackPackage) {
|
||||
return this.fallbackPackage;
|
||||
}
|
||||
|
||||
// If no fallback, throw error to prevent undefined behavior
|
||||
throw new Error("Failed to get package and no fallback available");
|
||||
const pkg = this.getRuntimePackage();
|
||||
if (win !== window) {
|
||||
win.ExcalidrawLib = pkg.excalidrawLib;
|
||||
this.runtimeAliasWindows.add(win);
|
||||
}
|
||||
return pkg;
|
||||
}
|
||||
|
||||
/** Removes only the window-local alias; the shared runtime remains alive. */
|
||||
private removeRuntimeAlias(win: Window): void {
|
||||
const packageLib = this.runtimePackage?.excalidrawLib;
|
||||
errorHandler.wrapWithTryCatch(() => {
|
||||
if (packageLib && win.ExcalidrawLib === packageLib) {
|
||||
delete win.ExcalidrawLib;
|
||||
}
|
||||
}, "PackageManager.removeRuntimeAlias");
|
||||
this.runtimeAliasWindows.delete(win);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compatibility facade retained for callers that explicitly clean a window.
|
||||
* The plugin-wide runtime and host registrations live until `destroy()`.
|
||||
*/
|
||||
public deletePackage(win: Window) {
|
||||
try {
|
||||
const pkg = this.packageMap.get(win);
|
||||
if (!pkg) {
|
||||
return;
|
||||
if (win !== window) {
|
||||
this.removeRuntimeAlias(win);
|
||||
}
|
||||
|
||||
const { excalidrawLib } = pkg;
|
||||
if (win.ExcalidrawLib === excalidrawLib) {
|
||||
errorHandler.wrapWithTryCatch(() => {
|
||||
if (
|
||||
excalidrawLib &&
|
||||
typeof excalidrawLib.destroyObsidianUtils === "function"
|
||||
) {
|
||||
excalidrawLib.destroyObsidianUtils();
|
||||
}
|
||||
delete win.ExcalidrawLib;
|
||||
}, "PackageManager.deletePackage - cleanup ExcalidrawLib");
|
||||
}
|
||||
|
||||
this.packageMap.delete(win);
|
||||
} catch (error) {
|
||||
errorHandler.handleError(error, "PackageManager.deletePackage");
|
||||
} catch (error: unknown) {
|
||||
errorHandler.handleError(
|
||||
normalizeError(error),
|
||||
"PackageManager.deletePackage",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public setExcalidrawPackage(pkg: string) {
|
||||
this.EXCALIDRAW_PACKAGE = pkg;
|
||||
}
|
||||
|
||||
public destroy() {
|
||||
try {
|
||||
REACT_PACKAGES = "";
|
||||
|
||||
Array.from(this.packageMap.entries()).forEach(([win, _]) => {
|
||||
this.deletePackage(win);
|
||||
Array.from(this.runtimeAliasWindows).forEach((win) => {
|
||||
this.removeRuntimeAlias(win);
|
||||
});
|
||||
this.removeRuntimeAlias(window);
|
||||
|
||||
this.packageMap.clear();
|
||||
this.EXCALIDRAW_PACKAGE = "";
|
||||
this.fallbackPackage = null;
|
||||
this.packageLeaseCountMap.clear();
|
||||
this.runtimeAliasWindows.clear();
|
||||
this.disposeObsidianHosts();
|
||||
this.runtimePackage = null;
|
||||
|
||||
react = null;
|
||||
reactDOM = null;
|
||||
excalidrawLib = null;
|
||||
} catch (error) {
|
||||
errorHandler.handleError(error, "PackageManager.destroy");
|
||||
} catch (error: unknown) {
|
||||
errorHandler.handleError(
|
||||
normalizeError(error),
|
||||
"PackageManager.destroy",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,40 +1,173 @@
|
||||
import { Notice, type App, type PluginManifest } from "obsidian";
|
||||
import { JSON_parse } from "src/constants/constants";
|
||||
import {
|
||||
DEFAULT_SETTINGS,
|
||||
type ExcalidrawSettings,
|
||||
} from "src/core/settings";
|
||||
} from "src/core/settingsDefaults";
|
||||
import { PreviewImageType } from "src/types/utilTypes";
|
||||
import {
|
||||
decryptPersistedAPIKeys,
|
||||
encryptPersistedAPIKeys,
|
||||
} from "src/utils/settingsKeyObfuscation";
|
||||
import { SerializedSettingsWriter } from "src/core/settings/SerializedSettingsWriter";
|
||||
import { SettingsRecoveryStore } from "src/core/settings/SettingsRecoveryStore";
|
||||
import {
|
||||
SettingsRecoveryPrompt,
|
||||
type SettingsRecoveryChoice,
|
||||
type SettingsRecoveryPromptMode,
|
||||
} from "src/shared/Dialogs/SettingsRecoveryPrompt";
|
||||
import {
|
||||
classifySettingsDataLoad,
|
||||
isSettingsDataRecord,
|
||||
type SettingsDataFileState,
|
||||
} from "src/core/settings/settingsDataValidation";
|
||||
import { t } from "src/lang/helpers";
|
||||
|
||||
type PersistedExcalidrawSettings = Partial<ExcalidrawSettings> &
|
||||
Record<string, unknown>;
|
||||
|
||||
interface PluginSettingsHost {
|
||||
app: App;
|
||||
manifest: PluginManifest;
|
||||
settings: ExcalidrawSettings;
|
||||
loadData(): Promise<unknown>;
|
||||
saveData(data: unknown): Promise<void>;
|
||||
}
|
||||
|
||||
interface SettingsRecoveryStoreLike {
|
||||
load(): Promise<PersistedExcalidrawSettings | null>;
|
||||
save(settings: PersistedExcalidrawSettings): Promise<void>;
|
||||
destroy(): void;
|
||||
}
|
||||
|
||||
type SettingsRecoveryPromptHandler = (
|
||||
mode: SettingsRecoveryPromptMode,
|
||||
) => Promise<SettingsRecoveryChoice>;
|
||||
|
||||
/**
|
||||
* 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) {}
|
||||
private readonly writer: SerializedSettingsWriter<PersistedExcalidrawSettings>;
|
||||
private readonly recoveryStore: SettingsRecoveryStoreLike;
|
||||
private hasCompletedInitialLoad = false;
|
||||
private persistenceBlockedByInvalidData = false;
|
||||
private missingRecoveryNoticeShown = false;
|
||||
private awaitingStartupRecoveryChoice = false;
|
||||
private readonly promptForRecoveryChoice: SettingsRecoveryPromptHandler;
|
||||
|
||||
public constructor(
|
||||
private readonly host: PluginSettingsHost,
|
||||
recoveryStore?: SettingsRecoveryStoreLike,
|
||||
promptForRecoveryChoice?: SettingsRecoveryPromptHandler,
|
||||
) {
|
||||
this.recoveryStore =
|
||||
recoveryStore ??
|
||||
new SettingsRecoveryStore({
|
||||
databaseName: `Excalidraw Settings Recovery ${host.app.appId}`,
|
||||
});
|
||||
this.promptForRecoveryChoice =
|
||||
promptForRecoveryChoice ??
|
||||
((mode) => new SettingsRecoveryPrompt(host.app, mode).start());
|
||||
this.writer = new SerializedSettingsWriter({
|
||||
saveData: async (data) => {
|
||||
await this.saveRecoverySnapshot(data);
|
||||
await this.host.saveData(data);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads persisted settings, applies defaults and migrations, and decrypts
|
||||
* protected API-key fields.
|
||||
*
|
||||
* @remarks Unknown persisted properties are intentionally retained.
|
||||
* @returns `false` when the disk payload was invalid. Runtime callers use
|
||||
* this to suppress cache invalidation for a rejected synchronized payload.
|
||||
*/
|
||||
public async loadSettings(): Promise<void> {
|
||||
const persistedSettings = ((await this.host.loadData()) ??
|
||||
{}) as PersistedExcalidrawSettings;
|
||||
public async loadSettings(): Promise<boolean> {
|
||||
const dataFileState = await this.getSettingsDataFileState();
|
||||
let loadedSettings: unknown = null;
|
||||
let loadFailed = false;
|
||||
try {
|
||||
loadedSettings = await this.host.loadData();
|
||||
} catch {
|
||||
loadFailed = true;
|
||||
}
|
||||
|
||||
const classification = classifySettingsDataLoad({
|
||||
value: loadedSettings,
|
||||
fileState: dataFileState,
|
||||
loadFailed,
|
||||
isInitialLoad: !this.hasCompletedInitialLoad,
|
||||
});
|
||||
const hasInvalidSettings = classification === "invalid";
|
||||
const isFirstInstallation = classification === "first-installation";
|
||||
let persistedSettings: PersistedExcalidrawSettings;
|
||||
let recoveredInvalidStartup = false;
|
||||
let shouldPersistStartupChoice = false;
|
||||
|
||||
if (hasInvalidSettings) {
|
||||
if (this.hasCompletedInitialLoad) {
|
||||
this.persistenceBlockedByInvalidData = false;
|
||||
this.missingRecoveryNoticeShown = false;
|
||||
new Notice(t("SETTINGS_DATA_REPAIRED_FROM_MEMORY"), 12000);
|
||||
console.error(
|
||||
"Excalidraw rejected invalid synchronized settings data and restored the active settings",
|
||||
);
|
||||
await this.persistSnapshot(
|
||||
encryptPersistedAPIKeys(
|
||||
this.host.settings as PersistedExcalidrawSettings,
|
||||
),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const recoveredSettings = await this.loadRecoverySnapshot();
|
||||
if (recoveredSettings) {
|
||||
persistedSettings = recoveredSettings;
|
||||
recoveredInvalidStartup = true;
|
||||
shouldPersistStartupChoice = true;
|
||||
this.persistenceBlockedByInvalidData = false;
|
||||
this.missingRecoveryNoticeShown = false;
|
||||
} else {
|
||||
this.host.settings = Object.assign({}, DEFAULT_SETTINGS);
|
||||
const choice = await this.requestStartupRecoveryChoice(
|
||||
"invalid-without-recovery",
|
||||
);
|
||||
persistedSettings = {};
|
||||
if (choice === "reset-defaults") {
|
||||
this.persistenceBlockedByInvalidData = false;
|
||||
this.missingRecoveryNoticeShown = false;
|
||||
shouldPersistStartupChoice = true;
|
||||
} else {
|
||||
this.blockPersistenceWhileWaitingForFile();
|
||||
}
|
||||
}
|
||||
} else if (isFirstInstallation) {
|
||||
const recoveredSettings = await this.loadRecoverySnapshot();
|
||||
if (recoveredSettings) {
|
||||
this.host.settings = Object.assign({}, DEFAULT_SETTINGS);
|
||||
const choice = await this.requestStartupRecoveryChoice(
|
||||
"missing-with-recovery",
|
||||
);
|
||||
persistedSettings =
|
||||
choice === "reset-defaults" ? {} : recoveredSettings;
|
||||
} else {
|
||||
persistedSettings = {};
|
||||
}
|
||||
this.persistenceBlockedByInvalidData = false;
|
||||
this.missingRecoveryNoticeShown = false;
|
||||
shouldPersistStartupChoice = true;
|
||||
} else {
|
||||
this.persistenceBlockedByInvalidData = false;
|
||||
this.missingRecoveryNoticeShown = false;
|
||||
persistedSettings = isSettingsDataRecord(loadedSettings)
|
||||
? loadedSettings
|
||||
: {};
|
||||
}
|
||||
|
||||
const decryptedSettings = decryptPersistedAPIKeys(persistedSettings);
|
||||
let didSettingsMigration = false;
|
||||
this.host.settings = Object.assign(
|
||||
@@ -149,17 +282,114 @@ export class PluginSettingsManager {
|
||||
const shouldPersistEncryptedSettings =
|
||||
JSON.stringify(encryptedPersistedSettings) !==
|
||||
JSON.stringify(persistedSettings);
|
||||
if (didSettingsMigration || shouldPersistEncryptedSettings) {
|
||||
await this.host.saveData(encryptedPersistedSettings);
|
||||
if (shouldPersistStartupChoice) {
|
||||
await this.persistSnapshot(encryptedPersistedSettings);
|
||||
if (recoveredInvalidStartup) {
|
||||
new Notice(t("SETTINGS_DATA_RECOVERED"), 12000);
|
||||
}
|
||||
} else if (
|
||||
!this.persistenceBlockedByInvalidData &&
|
||||
(didSettingsMigration || shouldPersistEncryptedSettings)
|
||||
) {
|
||||
await this.persistSnapshot(encryptedPersistedSettings);
|
||||
} else if (!this.persistenceBlockedByInvalidData) {
|
||||
await this.saveRecoverySnapshot(encryptedPersistedSettings);
|
||||
}
|
||||
this.hasCompletedInitialLoad = true;
|
||||
return !hasInvalidSettings;
|
||||
}
|
||||
|
||||
/** Encrypts protected fields and persists the current settings object. */
|
||||
public async saveSettings(): Promise<void> {
|
||||
await this.host.saveData(
|
||||
public saveSettings(): Promise<void> {
|
||||
if (this.persistenceBlockedByInvalidData) {
|
||||
this.showMissingRecoveryNotice();
|
||||
return Promise.resolve();
|
||||
}
|
||||
return this.persistSnapshot(
|
||||
encryptPersistedAPIKeys(
|
||||
this.host.settings as PersistedExcalidrawSettings,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether plugin startup is intentionally waiting for a recovery choice. */
|
||||
public get isAwaitingStartupRecoveryChoice(): boolean {
|
||||
return this.awaitingStartupRecoveryChoice;
|
||||
}
|
||||
|
||||
private persistSnapshot(
|
||||
settings: PersistedExcalidrawSettings,
|
||||
): Promise<void> {
|
||||
return this.writer.persist(settings);
|
||||
}
|
||||
|
||||
/** Closes the device-local recovery database connection. */
|
||||
public destroy(): void {
|
||||
this.recoveryStore.destroy();
|
||||
}
|
||||
|
||||
private async getSettingsDataFileState(): Promise<SettingsDataFileState> {
|
||||
const pluginDirectory = this.host.manifest.dir;
|
||||
if (!pluginDirectory) {
|
||||
return "unknown";
|
||||
}
|
||||
try {
|
||||
const stat = await this.host.app.vault.adapter.stat(
|
||||
`${pluginDirectory}/data.json`,
|
||||
);
|
||||
if (!stat) {
|
||||
return "missing";
|
||||
}
|
||||
return stat.size === 0 ? "empty" : "present";
|
||||
} catch {
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
private blockPersistenceWhileWaitingForFile(): void {
|
||||
this.persistenceBlockedByInvalidData = true;
|
||||
this.missingRecoveryNoticeShown = false;
|
||||
}
|
||||
|
||||
private showMissingRecoveryNotice(): void {
|
||||
if (this.missingRecoveryNoticeShown) {
|
||||
return;
|
||||
}
|
||||
this.missingRecoveryNoticeShown = true;
|
||||
console.error(
|
||||
"Excalidraw settings data is empty or unreadable; waiting for a valid replacement file",
|
||||
);
|
||||
new Notice(t("SETTINGS_DATA_INVALID"), 12000);
|
||||
}
|
||||
|
||||
private async requestStartupRecoveryChoice(
|
||||
mode: SettingsRecoveryPromptMode,
|
||||
): Promise<SettingsRecoveryChoice> {
|
||||
this.awaitingStartupRecoveryChoice = true;
|
||||
try {
|
||||
return await this.promptForRecoveryChoice(mode);
|
||||
} finally {
|
||||
this.awaitingStartupRecoveryChoice = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async loadRecoverySnapshot(): Promise<PersistedExcalidrawSettings | null> {
|
||||
try {
|
||||
const recoveredSettings = await this.recoveryStore.load();
|
||||
return isSettingsDataRecord(recoveredSettings) ? recoveredSettings : null;
|
||||
} catch (error) {
|
||||
console.error("Could not load Excalidraw settings recovery", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async saveRecoverySnapshot(
|
||||
settings: PersistedExcalidrawSettings,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this.recoveryStore.save(settings);
|
||||
} catch (error) {
|
||||
console.error("Could not update Excalidraw settings recovery", error);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,8 @@ export class StencilLibraryManager {
|
||||
private itemSource = new Map<LibraryItem["id"], string>();
|
||||
private currentItems: LibraryItems = [];
|
||||
private loaded = false;
|
||||
private loadRevision = 0;
|
||||
private loadPromise: Promise<void> | null = null;
|
||||
private migrationPrompt: Promise<void> | null = null;
|
||||
private saveQueue: Promise<void> = Promise.resolve();
|
||||
private reloadTimer: number | null = null;
|
||||
@@ -86,6 +88,7 @@ export class StencilLibraryManager {
|
||||
}
|
||||
|
||||
public invalidate(): void {
|
||||
this.loadRevision++;
|
||||
this.loaded = false;
|
||||
this.itemSource.clear();
|
||||
this.currentItems = [];
|
||||
@@ -109,7 +112,7 @@ export class StencilLibraryManager {
|
||||
await this.migrateLegacyLibrary();
|
||||
}
|
||||
if (!this.loaded) {
|
||||
await this.loadFromVault();
|
||||
await this.ensureLoaded();
|
||||
}
|
||||
return this.currentItems;
|
||||
}
|
||||
@@ -156,7 +159,7 @@ export class StencilLibraryManager {
|
||||
}
|
||||
await this.saveQueue;
|
||||
this.invalidate();
|
||||
await this.loadFromVault();
|
||||
await this.ensureLoaded();
|
||||
this.isUpdatingOpenViews = true;
|
||||
try {
|
||||
for (const view of getExcalidrawViews(this.plugin.app, true)) {
|
||||
@@ -286,8 +289,39 @@ export class StencilLibraryManager {
|
||||
}
|
||||
}
|
||||
|
||||
private async loadFromVault(): Promise<void> {
|
||||
this.itemSource.clear();
|
||||
/** Coalesces concurrent view initialization into one vault-library load. */
|
||||
private async ensureLoaded(): Promise<void> {
|
||||
while (!this.loaded) {
|
||||
if (this.loadPromise === null) {
|
||||
const revision = this.loadRevision;
|
||||
this.loadPromise = this.loadFromVault().then(
|
||||
({ itemSource, items }) => {
|
||||
if (revision !== this.loadRevision) {
|
||||
return;
|
||||
}
|
||||
this.itemSource = itemSource;
|
||||
this.currentItems = items;
|
||||
this.loaded = true;
|
||||
},
|
||||
);
|
||||
}
|
||||
const activeLoad: Promise<void> = this.loadPromise;
|
||||
try {
|
||||
await activeLoad;
|
||||
} finally {
|
||||
if (this.loadPromise === activeLoad) {
|
||||
this.loadPromise = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads a coherent library snapshot without mutating the active cache. */
|
||||
private async loadFromVault(): Promise<{
|
||||
itemSource: Map<LibraryItem["id"], string>;
|
||||
items: LibraryItems;
|
||||
}> {
|
||||
const itemSource = new Map<LibraryItem["id"], string>();
|
||||
const folderPath = this.getFolderPath();
|
||||
const localPath = this.getLocalLibraryPath();
|
||||
const files = this.plugin.app.vault
|
||||
@@ -315,25 +349,24 @@ export class StencilLibraryManager {
|
||||
isLocalFile ? "unpublished" : "published",
|
||||
);
|
||||
for (const item of items) {
|
||||
if (this.itemSource.has(item.id)) {
|
||||
if (itemSource.has(item.id)) {
|
||||
console.warn(
|
||||
`Duplicate stencil library item id '${item.id}' in ${file.path}; keeping the first occurrence.`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
this.itemSource.set(item.id, file.path);
|
||||
itemSource.set(item.id, file.path);
|
||||
combined.push(
|
||||
isLocalFile ? item : { ...item, status: "published" as const },
|
||||
);
|
||||
}
|
||||
}
|
||||
this.currentItems = combined;
|
||||
this.loaded = true;
|
||||
return { itemSource, items: combined };
|
||||
}
|
||||
|
||||
private async persistChanges(nextItems: LibraryItems): Promise<void> {
|
||||
if (!this.loaded) {
|
||||
await this.loadFromVault();
|
||||
await this.ensureLoaded();
|
||||
}
|
||||
const previousById = new Map(
|
||||
this.currentItems.map((item) => [item.id, item]),
|
||||
@@ -344,7 +377,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 +422,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 +520,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,186 @@
|
||||
import type {
|
||||
AppState,
|
||||
BinaryFiles,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
|
||||
import type { ExcalidrawDataMigrationState } from "../../shared/ExcalidrawData";
|
||||
import type { TextMode } from "../../shared/TextMode";
|
||||
import type { ViewSaveMigrationState } from "../../view/managers/ViewSaveCoordinator";
|
||||
|
||||
const DEFAULT_HANDOFF_TTL_MS = 15_000;
|
||||
|
||||
/** Drawing-owned runtime state that may cross an Obsidian window migration. */
|
||||
export interface ViewMigrationDrawingState {
|
||||
elements: readonly ExcalidrawElement[];
|
||||
appState: AppState;
|
||||
files: BinaryFiles;
|
||||
textMode: TextMode;
|
||||
compatibilityMode: boolean;
|
||||
excalidrawData: ExcalidrawDataMigrationState;
|
||||
save: ViewSaveMigrationState;
|
||||
}
|
||||
|
||||
/** Metadata used to register one transient migration handoff. */
|
||||
export interface ViewMigrationHandoffRegistration {
|
||||
leafId: string;
|
||||
filePath: string;
|
||||
fileMtime: number;
|
||||
drawing: ViewMigrationDrawingState;
|
||||
}
|
||||
|
||||
/** Identity and freshness checks required to consume a migration handoff. */
|
||||
export interface ViewMigrationHandoffRequest {
|
||||
token: string;
|
||||
leafId: string;
|
||||
filePath: string;
|
||||
fileMtime: number;
|
||||
}
|
||||
|
||||
interface ViewMigrationHandoffEntry extends ViewMigrationHandoffRegistration {
|
||||
token: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
interface ViewMigrationHandoffScheduler {
|
||||
now: () => number;
|
||||
setTimeout: (callback: () => void, delay: number) => number;
|
||||
clearTimeout: (timer: number) => void;
|
||||
}
|
||||
|
||||
interface ViewMigrationHandoffManagerOptions {
|
||||
ttlMs?: number;
|
||||
scheduler?: ViewMigrationHandoffScheduler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns bounded, one-shot drawing handoffs between recreated views.
|
||||
*
|
||||
* Entries contain drawing state only. They never retain an `ExcalidrawView`,
|
||||
* React root, DOM node, `Window`, listener, or package lease. Consumption
|
||||
* removes the entry before validation so stale or mismatched state cannot be
|
||||
* retried, and a single expiry timer bounds abandoned payload lifetime.
|
||||
*/
|
||||
export class ViewMigrationHandoffManager {
|
||||
private readonly ttlMs: number;
|
||||
private readonly scheduler: ViewMigrationHandoffScheduler;
|
||||
private readonly entries = new Map<string, ViewMigrationHandoffEntry>();
|
||||
private readonly tokensByLeaf = new Map<string, string>();
|
||||
private cleanupTimer: number | null = null;
|
||||
private tokenSequence = 0;
|
||||
|
||||
public constructor(options: ViewMigrationHandoffManagerOptions = {}) {
|
||||
this.ttlMs = options.ttlMs ?? DEFAULT_HANDOFF_TTL_MS;
|
||||
if (!Number.isFinite(this.ttlMs) || this.ttlMs <= 0) {
|
||||
throw new Error("View migration handoff TTL must be positive");
|
||||
}
|
||||
this.scheduler =
|
||||
options.scheduler ??
|
||||
{
|
||||
now: () => Date.now(),
|
||||
setTimeout: (callback, delay) => window.setTimeout(callback, delay),
|
||||
clearTimeout: (timer) => window.clearTimeout(timer),
|
||||
};
|
||||
}
|
||||
|
||||
/** Registers a handoff, replacing any older payload for the same leaf. */
|
||||
public register(registration: ViewMigrationHandoffRegistration): string {
|
||||
this.pruneExpired();
|
||||
const previousToken = this.tokensByLeaf.get(registration.leafId);
|
||||
if (previousToken) {
|
||||
this.deleteEntry(previousToken);
|
||||
}
|
||||
|
||||
const now = this.scheduler.now();
|
||||
const token = `view-migration-${now.toString(36)}-${(++this.tokenSequence).toString(36)}`;
|
||||
this.entries.set(token, {
|
||||
...registration,
|
||||
token,
|
||||
expiresAt: now + this.ttlMs,
|
||||
});
|
||||
this.tokensByLeaf.set(registration.leafId, token);
|
||||
this.scheduleCleanup();
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Consumes a matching handoff exactly once.
|
||||
*
|
||||
* A token mismatch, leaf/path mismatch, file modification, or TTL expiry
|
||||
* returns `null` and discards the candidate so the caller must use its
|
||||
* ordinary disk-backed load path.
|
||||
*/
|
||||
public consume(
|
||||
request: ViewMigrationHandoffRequest,
|
||||
): ViewMigrationDrawingState | null {
|
||||
this.pruneExpired();
|
||||
const entry = this.entries.get(request.token);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
this.deleteEntry(request.token);
|
||||
this.scheduleCleanup();
|
||||
|
||||
if (
|
||||
entry.leafId !== request.leafId ||
|
||||
entry.filePath !== request.filePath ||
|
||||
entry.fileMtime !== request.fileMtime
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return entry.drawing;
|
||||
}
|
||||
|
||||
/** Drops all retained drawing state and cancels expiry work. */
|
||||
public destroy(): void {
|
||||
if (this.cleanupTimer !== null) {
|
||||
this.scheduler.clearTimeout(this.cleanupTimer);
|
||||
this.cleanupTimer = null;
|
||||
}
|
||||
this.entries.clear();
|
||||
this.tokensByLeaf.clear();
|
||||
}
|
||||
|
||||
private deleteEntry(token: string): void {
|
||||
const entry = this.entries.get(token);
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
this.entries.delete(token);
|
||||
if (this.tokensByLeaf.get(entry.leafId) === token) {
|
||||
this.tokensByLeaf.delete(entry.leafId);
|
||||
}
|
||||
}
|
||||
|
||||
private pruneExpired(): void {
|
||||
const now = this.scheduler.now();
|
||||
for (const [token, entry] of this.entries) {
|
||||
if (entry.expiresAt <= now) {
|
||||
this.deleteEntry(token);
|
||||
}
|
||||
}
|
||||
if (this.entries.size === 0 && this.cleanupTimer !== null) {
|
||||
this.scheduler.clearTimeout(this.cleanupTimer);
|
||||
this.cleanupTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleCleanup(): void {
|
||||
if (this.cleanupTimer !== null) {
|
||||
this.scheduler.clearTimeout(this.cleanupTimer);
|
||||
this.cleanupTimer = null;
|
||||
}
|
||||
if (this.entries.size === 0) {
|
||||
return;
|
||||
}
|
||||
let nextExpiry = Number.POSITIVE_INFINITY;
|
||||
for (const entry of this.entries.values()) {
|
||||
nextExpiry = Math.min(nextExpiry, entry.expiresAt);
|
||||
}
|
||||
this.cleanupTimer = this.scheduler.setTimeout(() => {
|
||||
this.cleanupTimer = null;
|
||||
this.pruneExpired();
|
||||
this.scheduleCleanup();
|
||||
}, Math.max(0, nextExpiry - this.scheduler.now()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
const DEFAULT_HANDOFF_TTL_MS = 15_000;
|
||||
|
||||
export interface ViewMigrationPersistenceHandoff {
|
||||
leafId: string;
|
||||
filePath: string;
|
||||
data: string;
|
||||
}
|
||||
|
||||
interface ViewMigrationPersistenceHandoffEntry extends ViewMigrationPersistenceHandoff {
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns bounded serialized drawing handoffs from a destroyed popout view to
|
||||
* the replacement view in Obsidian's main window.
|
||||
*
|
||||
* Entries contain drawing text and stable identifiers only. They never retain
|
||||
* a view, DOM node, React runtime, package lease, or Window. Consumption is
|
||||
* one-shot, and abandoned entries expire promptly.
|
||||
*/
|
||||
export class ViewMigrationPersistenceHandoffManager {
|
||||
private readonly entries = new Map<
|
||||
string,
|
||||
ViewMigrationPersistenceHandoffEntry
|
||||
>();
|
||||
private cleanupTimer: number | null = null;
|
||||
|
||||
/** Registers or replaces the pending drawing text for one workspace leaf. */
|
||||
public register(handoff: ViewMigrationPersistenceHandoff): void {
|
||||
this.pruneExpired();
|
||||
this.entries.set(handoff.leafId, {
|
||||
...handoff,
|
||||
expiresAt: Date.now() + DEFAULT_HANDOFF_TTL_MS,
|
||||
});
|
||||
this.scheduleCleanup();
|
||||
}
|
||||
|
||||
/** Consumes matching drawing text exactly once. */
|
||||
public consume(leafId: string, filePath: string): string | null {
|
||||
this.pruneExpired();
|
||||
const entry = this.entries.get(leafId);
|
||||
if (!entry) {
|
||||
return null;
|
||||
}
|
||||
this.entries.delete(leafId);
|
||||
this.scheduleCleanup();
|
||||
return entry.filePath === filePath ? entry.data : null;
|
||||
}
|
||||
|
||||
/** Discards an abandoned handoff after a failed view replacement. */
|
||||
public discard(leafId: string): void {
|
||||
this.entries.delete(leafId);
|
||||
this.scheduleCleanup();
|
||||
}
|
||||
|
||||
/** Clears retained text and its main-window cleanup timer. */
|
||||
public destroy(): void {
|
||||
if (this.cleanupTimer !== null) {
|
||||
window.clearTimeout(this.cleanupTimer);
|
||||
this.cleanupTimer = null;
|
||||
}
|
||||
this.entries.clear();
|
||||
}
|
||||
|
||||
private pruneExpired(): void {
|
||||
const now = Date.now();
|
||||
for (const [leafId, entry] of this.entries) {
|
||||
if (entry.expiresAt <= now) {
|
||||
this.entries.delete(leafId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleCleanup(): void {
|
||||
if (this.cleanupTimer !== null) {
|
||||
window.clearTimeout(this.cleanupTimer);
|
||||
this.cleanupTimer = null;
|
||||
}
|
||||
if (this.entries.size === 0) {
|
||||
return;
|
||||
}
|
||||
let nextExpiry = Number.POSITIVE_INFINITY;
|
||||
for (const entry of this.entries.values()) {
|
||||
nextExpiry = Math.min(nextExpiry, entry.expiresAt);
|
||||
}
|
||||
this.cleanupTimer = window.setTimeout(
|
||||
() => {
|
||||
this.cleanupTimer = null;
|
||||
this.pruneExpired();
|
||||
this.scheduleCleanup();
|
||||
},
|
||||
Math.max(0, nextExpiry - Date.now()),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
),
|
||||
});
|
||||
+4380
-3784
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* Obsidian 1.13 declarative adapter for canonical setting specifications.
|
||||
*/
|
||||
|
||||
import type { SettingBindingRegistry } from "src/core/settings/SettingBindingRegistry";
|
||||
import type { LegacySettingsAdapter } from "src/core/settings/LegacySettingsAdapter";
|
||||
import type {
|
||||
SettingBindingKey,
|
||||
SettingSpec,
|
||||
} from "src/core/settings/settingSpecs";
|
||||
import type {
|
||||
SettingDefinition,
|
||||
} from "src/types/obsidianDeclarativeSettings";
|
||||
import { annotateMarkdownDefinition } from "src/core/settings/declarativeSettingsMarkdown";
|
||||
|
||||
/** Converts canonical setting rows into Obsidian 1.13 definitions. */
|
||||
export class DeclarativeSettingsAdapter {
|
||||
private readonly bindings: SettingBindingRegistry;
|
||||
private readonly legacyAdapter: LegacySettingsAdapter;
|
||||
private registerBindings = true;
|
||||
|
||||
constructor(
|
||||
bindings: SettingBindingRegistry,
|
||||
legacyAdapter: LegacySettingsAdapter,
|
||||
) {
|
||||
this.bindings = bindings;
|
||||
this.legacyAdapter = legacyAdapter;
|
||||
}
|
||||
|
||||
/** Starts a definition build, optionally replacing the live control bindings. */
|
||||
beginBuild(registerBindings: boolean = true): void {
|
||||
this.registerBindings = registerBindings;
|
||||
if (registerBindings) {
|
||||
this.bindings.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/** Converts one canonical row during the current definition build. */
|
||||
toDefinition(spec: SettingSpec): SettingDefinition<SettingBindingKey> {
|
||||
if (this.requiresCustomRender(spec)) {
|
||||
return this.toRenderedDefinition(spec);
|
||||
}
|
||||
|
||||
if (this.registerBindings) {
|
||||
this.bindings.register(spec);
|
||||
}
|
||||
const base = {
|
||||
name: this.toSearchText(spec.name),
|
||||
desc: spec.desc,
|
||||
aliases: spec.aliases,
|
||||
searchable: spec.searchable,
|
||||
visible: spec.visible,
|
||||
};
|
||||
const control = spec.control;
|
||||
switch (control.type) {
|
||||
case "toggle":
|
||||
return {
|
||||
...base,
|
||||
control: {
|
||||
type: "toggle",
|
||||
key: control.key,
|
||||
disabled: control.disabled,
|
||||
},
|
||||
};
|
||||
case "text":
|
||||
return {
|
||||
...base,
|
||||
control: {
|
||||
type: "text",
|
||||
key: control.key,
|
||||
placeholder: control.placeholder,
|
||||
disabled: control.disabled,
|
||||
},
|
||||
};
|
||||
case "dropdown":
|
||||
return {
|
||||
...base,
|
||||
control: {
|
||||
type: "dropdown",
|
||||
key: control.key,
|
||||
options: Object.fromEntries(
|
||||
control.options.map(({ value, label }) => [value, label]),
|
||||
),
|
||||
disabled: control.disabled,
|
||||
},
|
||||
};
|
||||
case "number-dropdown":
|
||||
return {
|
||||
...base,
|
||||
control: {
|
||||
type: "dropdown",
|
||||
key: control.key,
|
||||
options: Object.fromEntries(
|
||||
control.options.map(({ value, label }) => [
|
||||
value.toString(),
|
||||
label,
|
||||
]),
|
||||
),
|
||||
disabled: control.disabled,
|
||||
},
|
||||
};
|
||||
case "slider":
|
||||
return {
|
||||
...base,
|
||||
control: {
|
||||
type: "slider",
|
||||
key: control.key,
|
||||
min: control.min,
|
||||
max: control.max,
|
||||
step: control.step,
|
||||
disabled: control.disabled,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private requiresCustomRender(spec: SettingSpec): boolean {
|
||||
if (typeof spec.name !== "string") {
|
||||
return true;
|
||||
}
|
||||
const control = spec.control;
|
||||
return (
|
||||
(control.type === "text" &&
|
||||
Boolean(control.capture || control.sanitize || control.vaultPath)) ||
|
||||
(control.type === "slider" && control.minWidth !== undefined)
|
||||
);
|
||||
}
|
||||
|
||||
private toRenderedDefinition(
|
||||
spec: SettingSpec,
|
||||
): SettingDefinition<SettingBindingKey> {
|
||||
return annotateMarkdownDefinition(
|
||||
{
|
||||
name: this.toSearchText(spec.name),
|
||||
desc:
|
||||
spec.desc === undefined ? undefined : this.toSearchText(spec.desc),
|
||||
aliases: spec.aliases,
|
||||
searchable: spec.searchable,
|
||||
visible: spec.visible,
|
||||
render: (setting) => this.legacyAdapter.configure(setting, spec),
|
||||
},
|
||||
{ controlType: spec.control.type },
|
||||
);
|
||||
}
|
||||
|
||||
private toSearchText(value: string | DocumentFragment): string {
|
||||
return typeof value === "string" ? value : (value.textContent ?? "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* Imperative renderer for canonical setting-row specifications.
|
||||
*/
|
||||
|
||||
import { Setting, type TextComponent } from "obsidian";
|
||||
import type { SettingBindingRegistry } from "src/core/settings/SettingBindingRegistry";
|
||||
import type {
|
||||
SettingSpec,
|
||||
TextControl,
|
||||
} from "src/core/settings/settingSpecs";
|
||||
import { configureSliderWithText } from "src/utils/sliderUtils";
|
||||
|
||||
/** Legacy-only services used by custom text controls. */
|
||||
export interface LegacySettingsAdapterHost {
|
||||
addVaultPathSupport(
|
||||
setting: Setting,
|
||||
text: TextComponent,
|
||||
kind: "file" | "folder",
|
||||
options: NonNullable<TextControl["vaultPath"]>["options"],
|
||||
): void;
|
||||
}
|
||||
|
||||
/** Builds or configures imperative Obsidian setting rows from canonical specs. */
|
||||
export class LegacySettingsAdapter {
|
||||
constructor(
|
||||
private readonly bindings: SettingBindingRegistry,
|
||||
private readonly host: LegacySettingsAdapterHost,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Creates one legacy row. Slider return behavior remains `undefined` for
|
||||
* compatibility with the former in-class interpreter.
|
||||
*/
|
||||
render(container: HTMLElement, spec: SettingSpec): Setting | undefined {
|
||||
const visible =
|
||||
typeof spec.visible === "function"
|
||||
? spec.visible()
|
||||
: (spec.visible ?? true);
|
||||
if (!visible) {
|
||||
return undefined;
|
||||
}
|
||||
const setting = new Setting(container);
|
||||
this.configure(setting, spec);
|
||||
return spec.control.type === "slider" ? undefined : setting;
|
||||
}
|
||||
|
||||
/** Configures a row supplied by either the legacy or declarative host. */
|
||||
configure(setting: Setting, spec: SettingSpec): void {
|
||||
const control = spec.control;
|
||||
const disabled =
|
||||
typeof control.disabled === "function"
|
||||
? control.disabled()
|
||||
: (control.disabled ?? false);
|
||||
if (control.type === "slider") {
|
||||
configureSliderWithText(setting, {
|
||||
name: spec.name,
|
||||
desc: spec.desc,
|
||||
value: this.bindings.getSpecValue(spec) as number,
|
||||
min: control.min,
|
||||
max: control.max,
|
||||
step: control.step,
|
||||
minWidth: control.minWidth,
|
||||
onChange: (value) => this.bindings.setLegacySpecValue(spec, value),
|
||||
});
|
||||
setting.setDisabled(disabled);
|
||||
return;
|
||||
}
|
||||
|
||||
setting.setName(spec.name);
|
||||
if (spec.desc) {
|
||||
setting.setDesc(spec.desc);
|
||||
}
|
||||
|
||||
switch (control.type) {
|
||||
case "toggle":
|
||||
setting.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(this.bindings.getSpecValue(spec) as boolean)
|
||||
.onChange((value) =>
|
||||
this.bindings.setLegacySpecValue(spec, value),
|
||||
),
|
||||
);
|
||||
break;
|
||||
case "text":
|
||||
setting.addText((text) => {
|
||||
control.capture?.(text);
|
||||
if (control.placeholder !== undefined) {
|
||||
text.setPlaceholder(control.placeholder);
|
||||
}
|
||||
text
|
||||
.setValue(this.bindings.getSpecValue(spec) as string)
|
||||
.onChange((value) =>
|
||||
this.bindings.setLegacySpecValue(spec, value, () => {
|
||||
if (control.sanitize) {
|
||||
text.setValue(this.bindings.getSpecValue(spec) as string);
|
||||
}
|
||||
}),
|
||||
);
|
||||
if (control.vaultPath) {
|
||||
this.host.addVaultPathSupport(
|
||||
setting,
|
||||
text,
|
||||
control.vaultPath.kind,
|
||||
control.vaultPath.options,
|
||||
);
|
||||
}
|
||||
});
|
||||
break;
|
||||
case "dropdown":
|
||||
setting.addDropdown((dropdown) => {
|
||||
for (const option of control.options) {
|
||||
dropdown.addOption(option.value, option.label);
|
||||
}
|
||||
dropdown
|
||||
.setValue(this.bindings.getSpecValue(spec) as string)
|
||||
.onChange((value) =>
|
||||
this.bindings.setLegacySpecValue(spec, value),
|
||||
);
|
||||
});
|
||||
break;
|
||||
case "number-dropdown":
|
||||
setting.addDropdown((dropdown) => {
|
||||
for (const option of control.options) {
|
||||
dropdown.addOption(option.value.toString(), option.label);
|
||||
}
|
||||
dropdown
|
||||
.setValue(this.bindings.getSpecValue(spec) as string)
|
||||
.onChange((value) =>
|
||||
this.bindings.setLegacySpecValue(spec, value),
|
||||
);
|
||||
});
|
||||
}
|
||||
// Setting#setDisabled only affects controls that already exist. Apply the
|
||||
// initial predicate after configuring the row so dependent controls start
|
||||
// in the same state in both legacy and declarative render paths.
|
||||
setting.setDisabled(disabled);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Serialized stable-snapshot writer for plugin settings.
|
||||
*/
|
||||
|
||||
/** Persistence operation required by the serialized settings writer. */
|
||||
export interface SerializedSettingsWriterHost<Snapshot> {
|
||||
saveData(data: Snapshot): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializes complete settings writes so an older save cannot finish after a
|
||||
* newer one. Each request captures an immutable JSON snapshot before waiting
|
||||
* for an earlier write.
|
||||
*/
|
||||
export class SerializedSettingsWriter<
|
||||
Snapshot extends Record<string, unknown>,
|
||||
> {
|
||||
private persistenceChain: Promise<void> = Promise.resolve();
|
||||
|
||||
public constructor(
|
||||
private readonly host: SerializedSettingsWriterHost<Snapshot>,
|
||||
) {}
|
||||
|
||||
/** Queues one stable snapshot and resolves when that snapshot is saved. */
|
||||
public persist(settings: Snapshot): Promise<void> {
|
||||
let snapshot: Snapshot;
|
||||
try {
|
||||
snapshot = JSON.parse(JSON.stringify(settings)) as Snapshot;
|
||||
} catch (error) {
|
||||
return Promise.reject(
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error("Could not serialize settings snapshot"),
|
||||
);
|
||||
}
|
||||
const persistence = this.persistenceChain
|
||||
.catch((): void => undefined)
|
||||
.then(() => this.host.saveData(snapshot));
|
||||
this.persistenceChain = persistence;
|
||||
return persistence;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
/**
|
||||
* Typed value and persistence bridge for canonical setting specifications.
|
||||
*/
|
||||
|
||||
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
|
||||
import type {
|
||||
SettingBindingKey,
|
||||
SettingControlSpec,
|
||||
SettingSpec,
|
||||
} from "src/core/settings/settingSpecs";
|
||||
|
||||
/** Services required to persist a canonical setting mutation. */
|
||||
export interface SettingBindingHost {
|
||||
getSettings(): ExcalidrawSettings;
|
||||
queueSettingsUpdate(requestReloadDrawings: boolean): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves declarative control keys and applies the same transformations,
|
||||
* hooks, save queue, and pending actions as the legacy controls.
|
||||
*/
|
||||
export class SettingBindingRegistry {
|
||||
private readonly bindings = new Map<SettingBindingKey, SettingSpec>();
|
||||
private readonly host: SettingBindingHost;
|
||||
|
||||
constructor(host: SettingBindingHost) {
|
||||
this.host = host;
|
||||
}
|
||||
|
||||
/** Clears bindings before a fresh declarative definition build. */
|
||||
clear(): void {
|
||||
this.bindings.clear();
|
||||
}
|
||||
|
||||
/** Registers one native declarative control binding for the current build. */
|
||||
register(spec: SettingSpec): void {
|
||||
const { key } = spec.control;
|
||||
if (this.bindings.has(key)) {
|
||||
throw new Error(`Duplicate declarative setting binding: ${key}`);
|
||||
}
|
||||
this.bindings.set(key, spec);
|
||||
}
|
||||
|
||||
/** Reads a registered declarative control value. */
|
||||
getControlValue(key: string): unknown {
|
||||
return this.getSpecValue(this.getBinding(key));
|
||||
}
|
||||
|
||||
/** Writes a registered declarative control value and awaits persistence. */
|
||||
setControlValue(key: string, value: unknown): Promise<void> {
|
||||
return this.setSpecValue(this.getBinding(key), value);
|
||||
}
|
||||
|
||||
/** Reads the UI-facing value for either adapter. */
|
||||
getSpecValue(spec: SettingSpec): boolean | string | number {
|
||||
const settings = this.host.getSettings();
|
||||
const control = spec.control;
|
||||
switch (control.type) {
|
||||
case "toggle": {
|
||||
const storedValue = settings[control.key];
|
||||
return control.negate ? !storedValue : storedValue;
|
||||
}
|
||||
case "number-dropdown":
|
||||
return settings[control.key].toString();
|
||||
case "slider":
|
||||
return settings[control.key] * (control.scale ?? 1);
|
||||
default:
|
||||
return settings[control.key];
|
||||
}
|
||||
}
|
||||
|
||||
/** Applies a UI-facing value from either adapter. */
|
||||
setSpecValue(
|
||||
spec: SettingSpec,
|
||||
value: unknown,
|
||||
afterWrite?: () => void,
|
||||
): Promise<void> {
|
||||
return this.setSpecValueInternal(spec, value, afterWrite, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a legacy UI value without extending the component callback until
|
||||
* queued disk persistence completes.
|
||||
*/
|
||||
setLegacySpecValue(
|
||||
spec: SettingSpec,
|
||||
value: unknown,
|
||||
afterWrite?: () => void,
|
||||
): Promise<void> {
|
||||
return this.setSpecValueInternal(spec, value, afterWrite, false);
|
||||
}
|
||||
|
||||
private async setSpecValueInternal(
|
||||
spec: SettingSpec,
|
||||
value: unknown,
|
||||
afterWrite: (() => void) | undefined,
|
||||
awaitPersistence: boolean,
|
||||
): Promise<void> {
|
||||
const control = spec.control;
|
||||
switch (control.type) {
|
||||
case "toggle": {
|
||||
const nextValue = this.requireBoolean(control, value);
|
||||
await control.before?.(nextValue);
|
||||
this.setSettingValue(control.key, control.negate ? !nextValue : nextValue);
|
||||
afterWrite?.();
|
||||
await control.after?.(nextValue);
|
||||
await this.persistAndRunAfterUpdate(
|
||||
control,
|
||||
nextValue,
|
||||
awaitPersistence,
|
||||
);
|
||||
return;
|
||||
}
|
||||
case "text": {
|
||||
const nextValue = this.requireString(control, value);
|
||||
await control.before?.(nextValue);
|
||||
this.setSettingValue(
|
||||
control.key,
|
||||
control.sanitize?.(nextValue) ?? nextValue,
|
||||
);
|
||||
afterWrite?.();
|
||||
await control.after?.(nextValue);
|
||||
await this.persistAndRunAfterUpdate(
|
||||
control,
|
||||
nextValue,
|
||||
awaitPersistence,
|
||||
);
|
||||
return;
|
||||
}
|
||||
case "dropdown": {
|
||||
const nextValue = this.requireString(control, value);
|
||||
await control.before?.(nextValue);
|
||||
this.setSettingValue(control.key, nextValue);
|
||||
afterWrite?.();
|
||||
await control.after?.(nextValue);
|
||||
await this.persistAndRunAfterUpdate(
|
||||
control,
|
||||
nextValue,
|
||||
awaitPersistence,
|
||||
);
|
||||
return;
|
||||
}
|
||||
case "number-dropdown": {
|
||||
const rawValue = this.requireString(control, value);
|
||||
const nextValue =
|
||||
control.parse === "int" ? parseInt(rawValue) : parseFloat(rawValue);
|
||||
await control.before?.(nextValue);
|
||||
this.setSettingValue(control.key, nextValue);
|
||||
afterWrite?.();
|
||||
await control.after?.(nextValue);
|
||||
await this.persistAndRunAfterUpdate(
|
||||
control,
|
||||
nextValue,
|
||||
awaitPersistence,
|
||||
);
|
||||
return;
|
||||
}
|
||||
case "slider": {
|
||||
const displayValue = this.requireNumber(control, value);
|
||||
await control.before?.(displayValue);
|
||||
this.setSettingValue(
|
||||
control.key,
|
||||
displayValue / (control.scale ?? 1),
|
||||
);
|
||||
afterWrite?.();
|
||||
await control.after?.(displayValue);
|
||||
await this.persistAndRunAfterUpdate(
|
||||
control,
|
||||
displayValue,
|
||||
awaitPersistence,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private getBinding(key: string): SettingSpec {
|
||||
const binding = this.bindings.get(key as SettingBindingKey);
|
||||
if (!binding) {
|
||||
throw new Error(`Unknown declarative setting binding: ${key}`);
|
||||
}
|
||||
return binding;
|
||||
}
|
||||
|
||||
private setSettingValue<K extends keyof ExcalidrawSettings>(
|
||||
key: K,
|
||||
value: ExcalidrawSettings[K],
|
||||
): void {
|
||||
this.host.getSettings()[key] = value;
|
||||
}
|
||||
|
||||
private async persistAndRunAfterUpdate<Value>(
|
||||
control: SettingControlSpec & {
|
||||
afterUpdate?: (value: Value) => void | Promise<void>;
|
||||
},
|
||||
value: Value,
|
||||
awaitPersistence: boolean,
|
||||
): Promise<void> {
|
||||
const persistence = this.host.queueSettingsUpdate(control.reload ?? false);
|
||||
if (awaitPersistence) {
|
||||
try {
|
||||
await control.afterUpdate?.(value);
|
||||
} finally {
|
||||
await persistence;
|
||||
}
|
||||
return;
|
||||
}
|
||||
await control.afterUpdate?.(value);
|
||||
void persistence.catch((): void => undefined);
|
||||
}
|
||||
|
||||
private requireBoolean(control: SettingControlSpec, value: unknown): boolean {
|
||||
if (typeof value !== "boolean") {
|
||||
throw this.invalidValueError(control, "boolean");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private requireString(control: SettingControlSpec, value: unknown): string {
|
||||
if (typeof value !== "string") {
|
||||
throw this.invalidValueError(control, "string");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private requireNumber(control: SettingControlSpec, value: unknown): number {
|
||||
if (typeof value !== "number") {
|
||||
throw this.invalidValueError(control, "number");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private invalidValueError(
|
||||
control: SettingControlSpec,
|
||||
expectedType: string,
|
||||
): TypeError {
|
||||
return new TypeError(
|
||||
`Invalid value for setting '${control.key}': expected ${expectedType}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* Coalesces settings mutations so rapid controls do not enqueue one complete
|
||||
* `data.json` write per input event.
|
||||
*/
|
||||
|
||||
/** Persistence operations owned by the settings tab. */
|
||||
export interface SettingsPersistenceQueueHost {
|
||||
/** Persists the latest in-memory settings snapshot. */
|
||||
persistSettings(): Promise<void>;
|
||||
/** Applies side effects that must observe a successfully persisted snapshot. */
|
||||
applyPendingActions(): Promise<void>;
|
||||
/** Returns true while persistence would replace a control being edited. */
|
||||
shouldDeferPersistence?(): boolean;
|
||||
}
|
||||
|
||||
interface PersistenceWaiter {
|
||||
revision: number;
|
||||
resolve: () => void;
|
||||
reject: (reason: unknown) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trailing-edge persistence queue for settings mutations.
|
||||
*
|
||||
* Rapid mutations are collapsed into one write. If another mutation arrives
|
||||
* while that write is in flight, one follow-up write persists the newest
|
||||
* snapshot before pending actions and callers are released.
|
||||
*/
|
||||
export class SettingsPersistenceQueue {
|
||||
private requestedRevision = 0;
|
||||
private completedRevision = 0;
|
||||
private debounceTimer: number | null = null;
|
||||
private activeRun: Promise<void> | null = null;
|
||||
private waiters: PersistenceWaiter[] = [];
|
||||
|
||||
constructor(
|
||||
private readonly host: SettingsPersistenceQueueHost,
|
||||
private readonly debounceMilliseconds: number = 250,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Records a mutation and resolves after a persisted snapshot containing it
|
||||
* has had its pending actions applied.
|
||||
*/
|
||||
enqueue(): Promise<void> {
|
||||
const revision = ++this.requestedRevision;
|
||||
const persistence = new Promise<void>((resolve, reject) => {
|
||||
this.waiters.push({ revision, resolve, reject });
|
||||
});
|
||||
this.schedule();
|
||||
return persistence;
|
||||
}
|
||||
|
||||
/** Immediately starts any scheduled persistence and awaits completion. */
|
||||
flush(): Promise<void> {
|
||||
this.cancelTimer();
|
||||
if (this.activeRun !== null) {
|
||||
return this.activeRun;
|
||||
}
|
||||
if (this.completedRevision >= this.requestedRevision) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
return this.startRun();
|
||||
}
|
||||
|
||||
private schedule(): void {
|
||||
if (this.activeRun !== null) {
|
||||
return;
|
||||
}
|
||||
this.cancelTimer();
|
||||
this.debounceTimer = window.setTimeout(() => {
|
||||
this.debounceTimer = null;
|
||||
if (this.host.shouldDeferPersistence?.()) {
|
||||
this.schedule();
|
||||
return;
|
||||
}
|
||||
void this.startRun().catch((): void => undefined);
|
||||
}, this.debounceMilliseconds);
|
||||
}
|
||||
|
||||
private cancelTimer(): void {
|
||||
if (this.debounceTimer === null) {
|
||||
return;
|
||||
}
|
||||
window.clearTimeout(this.debounceTimer);
|
||||
this.debounceTimer = null;
|
||||
}
|
||||
|
||||
private startRun(): Promise<void> {
|
||||
if (this.activeRun !== null) {
|
||||
return this.activeRun;
|
||||
}
|
||||
const run = this.persistLatestRevision();
|
||||
this.activeRun = run;
|
||||
void run
|
||||
.finally(() => {
|
||||
if (this.activeRun === run) {
|
||||
this.activeRun = null;
|
||||
}
|
||||
})
|
||||
.catch((): void => undefined);
|
||||
return run;
|
||||
}
|
||||
|
||||
private async persistLatestRevision(): Promise<void> {
|
||||
try {
|
||||
while (this.completedRevision < this.requestedRevision) {
|
||||
const revisionToPersist = this.requestedRevision;
|
||||
await this.host.persistSettings();
|
||||
if (revisionToPersist !== this.requestedRevision) {
|
||||
continue;
|
||||
}
|
||||
await this.host.applyPendingActions();
|
||||
if (revisionToPersist !== this.requestedRevision) {
|
||||
continue;
|
||||
}
|
||||
this.completedRevision = revisionToPersist;
|
||||
this.resolveWaitersThrough(revisionToPersist);
|
||||
}
|
||||
} catch (error) {
|
||||
this.rejectWaiters(error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private resolveWaitersThrough(revision: number): void {
|
||||
const remaining: PersistenceWaiter[] = [];
|
||||
for (const waiter of this.waiters) {
|
||||
if (waiter.revision <= revision) {
|
||||
waiter.resolve();
|
||||
} else {
|
||||
remaining.push(waiter);
|
||||
}
|
||||
}
|
||||
this.waiters = remaining;
|
||||
}
|
||||
|
||||
private rejectWaiters(reason: unknown): void {
|
||||
const waiters = this.waiters;
|
||||
this.waiters = [];
|
||||
for (const waiter of waiters) {
|
||||
waiter.reject(reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* Device-local, transactional storage for the last known good settings.
|
||||
*
|
||||
* The recovery copy deliberately lives outside the vault and Obsidian's
|
||||
* localStorage. IndexedDB can hold large legacy settings records and replaces
|
||||
* the single recovery record atomically if a write completes.
|
||||
*/
|
||||
|
||||
const DATABASE_VERSION = 1;
|
||||
const STORE_NAME = "settingsRecovery";
|
||||
const RECORD_KEY = "lastKnownGood";
|
||||
const RECORD_VERSION = 1;
|
||||
|
||||
interface SettingsRecoveryRecord<Snapshot> {
|
||||
version: typeof RECORD_VERSION;
|
||||
settings: Snapshot;
|
||||
}
|
||||
|
||||
interface SettingsRecoveryStoreOptions {
|
||||
databaseName: string;
|
||||
indexedDBFactory?: IDBFactory | null;
|
||||
}
|
||||
|
||||
const normalizeError = (error: unknown, message: string): Error =>
|
||||
error instanceof Error ? error : new Error(message);
|
||||
|
||||
/**
|
||||
* Stores one durable last-known-good settings snapshot for the current vault.
|
||||
*/
|
||||
export class SettingsRecoveryStore<Snapshot extends Record<string, unknown>> {
|
||||
private database: IDBDatabase | null = null;
|
||||
private databasePromise: Promise<IDBDatabase> | null = null;
|
||||
private readonly indexedDBFactory: IDBFactory | null;
|
||||
private destroyed = false;
|
||||
|
||||
public constructor(private readonly options: SettingsRecoveryStoreOptions) {
|
||||
this.indexedDBFactory =
|
||||
"indexedDBFactory" in options
|
||||
? (options.indexedDBFactory ?? null)
|
||||
: typeof indexedDB === "undefined"
|
||||
? null
|
||||
: indexedDB;
|
||||
}
|
||||
|
||||
/** Returns the last complete settings snapshot, if one is available. */
|
||||
public async load(): Promise<Snapshot | null> {
|
||||
const database = await this.getDatabase();
|
||||
return new Promise<Snapshot | null>((resolve, reject) => {
|
||||
let request: IDBRequest<SettingsRecoveryRecord<Snapshot> | undefined>;
|
||||
try {
|
||||
const transaction = database.transaction(STORE_NAME, "readonly");
|
||||
request = transaction
|
||||
.objectStore(STORE_NAME)
|
||||
.get(RECORD_KEY) as IDBRequest<
|
||||
SettingsRecoveryRecord<Snapshot> | undefined
|
||||
>;
|
||||
request.onsuccess = () => {
|
||||
const record = request.result;
|
||||
resolve(
|
||||
record?.version === RECORD_VERSION &&
|
||||
typeof record.settings === "object" &&
|
||||
record.settings !== null &&
|
||||
!Array.isArray(record.settings)
|
||||
? record.settings
|
||||
: null,
|
||||
);
|
||||
};
|
||||
request.onerror = () => {
|
||||
reject(
|
||||
request.error ?? new Error("Could not read settings recovery"),
|
||||
);
|
||||
};
|
||||
} catch (error) {
|
||||
reject(normalizeError(error, "Could not read settings recovery"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Atomically replaces the last-known-good settings snapshot. */
|
||||
public async save(settings: Snapshot): Promise<void> {
|
||||
const database = await this.getDatabase();
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
try {
|
||||
const transaction = database.transaction(STORE_NAME, "readwrite");
|
||||
transaction.objectStore(STORE_NAME).put(
|
||||
{
|
||||
version: RECORD_VERSION,
|
||||
settings,
|
||||
} satisfies SettingsRecoveryRecord<Snapshot>,
|
||||
RECORD_KEY,
|
||||
);
|
||||
transaction.oncomplete = () => resolve();
|
||||
transaction.onerror = () => {
|
||||
reject(
|
||||
transaction.error ?? new Error("Could not save settings recovery"),
|
||||
);
|
||||
};
|
||||
transaction.onabort = () => {
|
||||
reject(
|
||||
transaction.error ?? new Error("Settings recovery write aborted"),
|
||||
);
|
||||
};
|
||||
} catch (error) {
|
||||
reject(normalizeError(error, "Could not save settings recovery"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Closes the database connection owned by this plugin instance. */
|
||||
public destroy(): void {
|
||||
this.destroyed = true;
|
||||
this.database?.close();
|
||||
this.database = null;
|
||||
this.databasePromise = null;
|
||||
}
|
||||
|
||||
private async getDatabase(): Promise<IDBDatabase> {
|
||||
if (this.destroyed) {
|
||||
throw new Error("Settings recovery store has been destroyed");
|
||||
}
|
||||
if (this.database) {
|
||||
return this.database;
|
||||
}
|
||||
const indexedDBFactory = this.indexedDBFactory;
|
||||
if (!indexedDBFactory) {
|
||||
throw new Error("IndexedDB is unavailable for settings recovery");
|
||||
}
|
||||
if (this.databasePromise === null) {
|
||||
this.databasePromise = this.openDatabase(indexedDBFactory);
|
||||
}
|
||||
try {
|
||||
return await this.databasePromise;
|
||||
} catch (error) {
|
||||
this.database?.close();
|
||||
this.database = null;
|
||||
this.databasePromise = null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private openDatabase(indexedDBFactory: IDBFactory): Promise<IDBDatabase> {
|
||||
return new Promise<IDBDatabase>((resolve, reject) => {
|
||||
let requestCompleted = false;
|
||||
const request = indexedDBFactory.open(
|
||||
this.options.databaseName,
|
||||
DATABASE_VERSION,
|
||||
);
|
||||
request.onupgradeneeded = () => {
|
||||
const database = request.result;
|
||||
if (!database.objectStoreNames.contains(STORE_NAME)) {
|
||||
database.createObjectStore(STORE_NAME);
|
||||
}
|
||||
};
|
||||
request.onsuccess = () => {
|
||||
const database = request.result;
|
||||
if (requestCompleted || this.destroyed) {
|
||||
database.close();
|
||||
if (!requestCompleted) {
|
||||
requestCompleted = true;
|
||||
reject(new Error("Settings recovery store has been destroyed"));
|
||||
}
|
||||
return;
|
||||
}
|
||||
requestCompleted = true;
|
||||
database.onversionchange = () => {
|
||||
database.close();
|
||||
if (this.database === database) {
|
||||
this.database = null;
|
||||
this.databasePromise = null;
|
||||
}
|
||||
};
|
||||
this.database = database;
|
||||
resolve(database);
|
||||
};
|
||||
request.onerror = () => {
|
||||
requestCompleted = true;
|
||||
reject(request.error ?? new Error("Could not open settings recovery"));
|
||||
};
|
||||
request.onblocked = () => {
|
||||
requestCompleted = true;
|
||||
reject(new Error("Settings recovery database upgrade was blocked"));
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* Markdown export for Obsidian's declarative settings tree.
|
||||
*
|
||||
* The exporter reads the declarations rather than the currently mounted page,
|
||||
* so nested and conditionally rendered settings remain discoverable in one
|
||||
* document.
|
||||
*/
|
||||
|
||||
import { htmlToMarkdown } from "obsidian";
|
||||
import type {
|
||||
SettingDefinition,
|
||||
SettingDefinitionItem,
|
||||
} from "src/types/obsidianDeclarativeSettings";
|
||||
|
||||
declare const mainDocument: Document;
|
||||
declare const deliberateCreateElement: (
|
||||
document: Document,
|
||||
tagName: string,
|
||||
) => HTMLElement;
|
||||
|
||||
interface MarkdownDefinitionMetadata {
|
||||
controlType?: string;
|
||||
omit?: boolean;
|
||||
}
|
||||
|
||||
const definitionMetadata = new WeakMap<object, MarkdownDefinitionMetadata>();
|
||||
|
||||
/** Adds export-only metadata without exposing custom fields to Obsidian. */
|
||||
export function annotateMarkdownDefinition<T extends object>(
|
||||
definition: T,
|
||||
metadata: MarkdownDefinitionMetadata,
|
||||
): T {
|
||||
definitionMetadata.set(definition, metadata);
|
||||
return definition;
|
||||
}
|
||||
|
||||
function toMarkdown(value: string | DocumentFragment | undefined): string {
|
||||
if (value === undefined) {
|
||||
return "";
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
return htmlToMarkdown(value).trim();
|
||||
}
|
||||
|
||||
const container = deliberateCreateElement(mainDocument, "div");
|
||||
container.appendChild(value.cloneNode(true));
|
||||
return htmlToMarkdown(container.innerHTML).trim();
|
||||
}
|
||||
|
||||
function normalizeControlType(controlType: string): string {
|
||||
switch (controlType) {
|
||||
case "text":
|
||||
return "text input";
|
||||
case "number-dropdown":
|
||||
return "dropdown";
|
||||
case "textarea":
|
||||
return "text area";
|
||||
default:
|
||||
return controlType;
|
||||
}
|
||||
}
|
||||
|
||||
function getControlType(definition: SettingDefinition): string | undefined {
|
||||
const metadata = definitionMetadata.get(definition);
|
||||
if (metadata?.controlType) {
|
||||
return normalizeControlType(metadata.controlType);
|
||||
}
|
||||
if ("control" in definition && definition.control) {
|
||||
return normalizeControlType(definition.control.type);
|
||||
}
|
||||
if ("render" in definition && definition.render) {
|
||||
return "custom control";
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function renderSetting(definition: SettingDefinition): string | null {
|
||||
const metadata = definitionMetadata.get(definition);
|
||||
if (metadata?.omit) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const description = toMarkdown(definition.desc);
|
||||
const controlType = getControlType(definition);
|
||||
const typePrefix = controlType ? ` (${controlType})` : "";
|
||||
return `- **${definition.name}:**${typePrefix}${description ? ` ${description}` : ""}`;
|
||||
}
|
||||
|
||||
function renderItems(
|
||||
items: readonly SettingDefinitionItem[],
|
||||
headingLevel: number,
|
||||
): string[] {
|
||||
const output: string[] = [];
|
||||
|
||||
for (const item of items) {
|
||||
if ("type" in item) {
|
||||
output.push(`${"#".repeat(headingLevel)} ${item.name}`);
|
||||
const description = toMarkdown(item.desc);
|
||||
if (description) {
|
||||
output.push(description);
|
||||
}
|
||||
if (item.items?.length) {
|
||||
output.push(...renderItems(item.items, headingLevel + 1));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const setting = renderSetting(item);
|
||||
if (setting) {
|
||||
output.push(setting);
|
||||
}
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/** Converts a complete declarative settings tree into one Markdown document. */
|
||||
export function declarativeSettingsToMarkdown(
|
||||
definitions: readonly SettingDefinitionItem[],
|
||||
): string {
|
||||
const blocks = renderItems(definitions, 1);
|
||||
if (blocks.length === 0) {
|
||||
return "";
|
||||
}
|
||||
let markdown = "";
|
||||
let previousBlock = "";
|
||||
for (const block of blocks) {
|
||||
const separator =
|
||||
markdown.length === 0
|
||||
? ""
|
||||
: previousBlock.startsWith("- **") && block.startsWith("- **")
|
||||
? "\n"
|
||||
: "\n\n";
|
||||
markdown += `${separator}${block}`;
|
||||
previousBlock = block;
|
||||
}
|
||||
return `${markdown}\n`;
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* Canonical setting-row specifications shared by the legacy and declarative
|
||||
* settings adapters.
|
||||
*/
|
||||
|
||||
import type { TextComponent } from "obsidian";
|
||||
import type { ExcalidrawSettings } from "src/core/settingsDefaults";
|
||||
|
||||
/** Keys of {@link ExcalidrawSettings} whose value type is boolean. */
|
||||
export type BooleanSettingKey = {
|
||||
[K in keyof ExcalidrawSettings]: ExcalidrawSettings[K] extends boolean
|
||||
? K
|
||||
: never;
|
||||
}[keyof ExcalidrawSettings];
|
||||
|
||||
/** Keys whose value type is exactly `string`, excluding literal unions. */
|
||||
export type StringSettingKey = {
|
||||
[K in keyof ExcalidrawSettings]: string extends ExcalidrawSettings[K]
|
||||
? ExcalidrawSettings[K] extends string
|
||||
? K
|
||||
: never
|
||||
: never;
|
||||
}[keyof ExcalidrawSettings];
|
||||
|
||||
/** Keys whose value is a string or a narrower string-literal union. */
|
||||
export type StringLikeSettingKey = {
|
||||
[K in keyof ExcalidrawSettings]: ExcalidrawSettings[K] extends string
|
||||
? K
|
||||
: never;
|
||||
}[keyof ExcalidrawSettings];
|
||||
|
||||
/** Keys of {@link ExcalidrawSettings} whose value type is number. */
|
||||
export type NumberSettingKey = {
|
||||
[K in keyof ExcalidrawSettings]: ExcalidrawSettings[K] extends number
|
||||
? K
|
||||
: never;
|
||||
}[keyof ExcalidrawSettings];
|
||||
|
||||
/** Every persisted key currently supported by a canonical row binding. */
|
||||
export type SettingBindingKey =
|
||||
| BooleanSettingKey
|
||||
| StringLikeSettingKey
|
||||
| NumberSettingKey;
|
||||
|
||||
type SettingControlBase<Value, Key extends SettingBindingKey> = {
|
||||
key: Key;
|
||||
before?: (value: Value) => void | Promise<void>;
|
||||
after?: (value: Value) => void | Promise<void>;
|
||||
afterUpdate?: (value: Value) => void | Promise<void>;
|
||||
reload?: boolean;
|
||||
disabled?: boolean | (() => boolean);
|
||||
};
|
||||
|
||||
/** Canonical toggle control, including support for an inverted stored value. */
|
||||
export type ToggleControl = SettingControlBase<boolean, BooleanSettingKey> & {
|
||||
type: "toggle";
|
||||
negate?: boolean;
|
||||
};
|
||||
|
||||
/** Canonical text control and its legacy-only component integrations. */
|
||||
export type TextControl = SettingControlBase<string, StringSettingKey> & {
|
||||
type: "text";
|
||||
placeholder?: string;
|
||||
sanitize?: (value: string) => string;
|
||||
vaultPath?: {
|
||||
kind: "file" | "folder";
|
||||
options?: {
|
||||
optional?: boolean;
|
||||
extensions?: readonly string[];
|
||||
resolvePath?: (value: string) => string;
|
||||
createFolder?: boolean;
|
||||
validate?: boolean;
|
||||
};
|
||||
};
|
||||
capture?: (text: TextComponent) => void;
|
||||
};
|
||||
|
||||
/** Canonical string-valued dropdown control. */
|
||||
export type DropdownControl = SettingControlBase<
|
||||
string,
|
||||
StringLikeSettingKey
|
||||
> & {
|
||||
type: "dropdown";
|
||||
options: readonly { value: string; label: string }[];
|
||||
};
|
||||
|
||||
/** Canonical numeric value represented by string-valued dropdown options. */
|
||||
export type NumberDropdownControl = SettingControlBase<
|
||||
number,
|
||||
NumberSettingKey
|
||||
> & {
|
||||
type: "number-dropdown";
|
||||
options: readonly { value: number; label: string }[];
|
||||
parse?: "int" | "float";
|
||||
};
|
||||
|
||||
/** Canonical numeric slider control. */
|
||||
export type SliderControl = SettingControlBase<number, NumberSettingKey> & {
|
||||
type: "slider";
|
||||
min: number;
|
||||
max: number;
|
||||
step: number;
|
||||
minWidth?: string;
|
||||
scale?: number;
|
||||
};
|
||||
|
||||
/** Controls currently understood by both settings adapters. */
|
||||
export type SettingControlSpec =
|
||||
| ToggleControl
|
||||
| TextControl
|
||||
| DropdownControl
|
||||
| NumberDropdownControl
|
||||
| SliderControl;
|
||||
|
||||
/**
|
||||
* One canonical setting row. Search metadata is declarative-only; visibility
|
||||
* and disabled predicates are interpreted by both adapters.
|
||||
*/
|
||||
export interface SettingSpec {
|
||||
name: string | DocumentFragment;
|
||||
desc?: string | DocumentFragment;
|
||||
aliases?: string[];
|
||||
searchable?: boolean | (() => boolean);
|
||||
visible?: boolean | (() => boolean);
|
||||
control: SettingControlSpec;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/** Classification helpers for safely loading plugin settings data. */
|
||||
|
||||
/** Observable state of the plugin's `data.json` file before loading it. */
|
||||
export type SettingsDataFileState =
|
||||
| "missing"
|
||||
| "empty"
|
||||
| "present"
|
||||
| "unknown";
|
||||
|
||||
/** Result of validating one settings load attempt. */
|
||||
export type SettingsDataLoadClassification =
|
||||
| "valid"
|
||||
| "first-installation"
|
||||
| "invalid";
|
||||
|
||||
/** Returns true for the object shape accepted as persisted settings data. */
|
||||
export const isSettingsDataRecord = (
|
||||
value: unknown,
|
||||
): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
/**
|
||||
* Distinguishes a genuine first installation from an empty, malformed, or
|
||||
* failed settings load that must not replace already loaded settings.
|
||||
*/
|
||||
export function classifySettingsDataLoad(options: {
|
||||
value: unknown;
|
||||
fileState: SettingsDataFileState;
|
||||
loadFailed: boolean;
|
||||
isInitialLoad: boolean;
|
||||
}): SettingsDataLoadClassification {
|
||||
if (isSettingsDataRecord(options.value)) {
|
||||
return "valid";
|
||||
}
|
||||
if (
|
||||
options.isInitialLoad &&
|
||||
!options.loadFailed &&
|
||||
(options.value === null || typeof options.value === "undefined") &&
|
||||
options.fileState === "missing"
|
||||
) {
|
||||
return "first-installation";
|
||||
}
|
||||
return "invalid";
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { App } from "obsidian";
|
||||
|
||||
/** Returns whether the current Obsidian runtime exposes page navigation. */
|
||||
export function canNavigateSettingsPages(app: App): boolean {
|
||||
return (
|
||||
typeof app.setting.openPagePath === "function" ||
|
||||
(typeof app.setting.findTabById === "function" &&
|
||||
typeof app.setting.navigateToPage === "function")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigates to a declarative settings page through Obsidian's unpublished
|
||||
* settings API.
|
||||
*
|
||||
* The method is deliberately isolated behind structural and exception guards
|
||||
* because it is not part of Obsidian's public compatibility contract.
|
||||
*
|
||||
* @returns `true` when Obsidian accepted the navigation request, otherwise
|
||||
* `false` so callers can leave the current page intact.
|
||||
*/
|
||||
export function navigateToSettingsPage(
|
||||
app: App,
|
||||
tabId: string,
|
||||
pagePath: readonly string[],
|
||||
): boolean {
|
||||
try {
|
||||
if (typeof app.setting.openPagePath === "function") {
|
||||
return app.setting.openPagePath(tabId, [...pagePath]) !== null;
|
||||
}
|
||||
|
||||
if (
|
||||
typeof app.setting.findTabById !== "function" ||
|
||||
typeof app.setting.navigateToPage !== "function"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const tab = app.setting.findTabById(tabId);
|
||||
if (!tab) {
|
||||
return false;
|
||||
}
|
||||
app.setting.navigateToPage(tab, [...pagePath]);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
"Excalidraw: Obsidian settings page navigation is unavailable.",
|
||||
error,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+190
-5
@@ -22,6 +22,21 @@ export default {
|
||||
SELECT_FILE_TO_INSERT: "Select a file to insert",
|
||||
// main.ts
|
||||
ERROR_INITIALIZING_EA: "Error initializing Excalidraw Automate",
|
||||
SETTINGS_DATA_INVALID:
|
||||
"Excalidraw is waiting for a valid replacement data.json. Setting changes will not be saved until that file is restored, or you restart Obsidian and choose Reset to defaults.",
|
||||
SETTINGS_DATA_REPAIRED_FROM_MEMORY:
|
||||
"An empty or unreadable Excalidraw settings file was received and rejected. The active settings were written back to repair data.json.",
|
||||
SETTINGS_DATA_RECOVERED:
|
||||
"Excalidraw data.json was empty or unreadable. The last known good settings were restored automatically.",
|
||||
SETTINGS_RECOVERY_MISSING_TITLE: "Excalidraw settings file is missing",
|
||||
SETTINGS_RECOVERY_MISSING_DESC:
|
||||
"A last known good settings backup exists on this device. Restore that backup, or reset Excalidraw to factory defaults. Closing this message restores the backup.",
|
||||
SETTINGS_RECOVERY_CORRUPT_TITLE: "Excalidraw settings file is corrupted",
|
||||
SETTINGS_RECOVERY_CORRUPT_DESC:
|
||||
"The settings file is empty or unreadable, and no recovery backup is available on this device. Reset Excalidraw to factory defaults, or leave the file unchanged while you restore a valid data.json from another source. Closing this message waits for a replacement file.",
|
||||
SETTINGS_RECOVERY_RESTORE_BACKUP: "Restore backup",
|
||||
SETTINGS_RECOVERY_RESET_DEFAULTS: "Reset to defaults",
|
||||
SETTINGS_RECOVERY_WAIT_FOR_FILE: "Wait for restored file",
|
||||
CONVERT_URL_TO_FILE: "Save image from URL to local file",
|
||||
UNZIP_CURRENT_FILE: "Decompress current Excalidraw file",
|
||||
PUBLISH_SVG_CHECK:
|
||||
@@ -246,6 +261,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:
|
||||
@@ -380,6 +399,18 @@ export default {
|
||||
SEARCH_SHOWHIDE_ARIA: "Show/Hide search bar",
|
||||
SEARCH_NEXT: "Next",
|
||||
SEARCH_PREVIOUS: "Previous",
|
||||
SETTINGS_TOOLBAR_COPY: "Copy settings",
|
||||
SETTINGS_TOOLBAR_NOTEBOOKLM: "NotebookLM",
|
||||
SETTINGS_TOOLBAR_BUGS: "Bugs",
|
||||
SETTINGS_TOOLBAR_WIKI: "Wiki",
|
||||
SETTINGS_TOOLBAR_YOUTUBE: "YouTube",
|
||||
SETTINGS_TOOLBAR_LEARN: "Learn",
|
||||
SETTINGS_TOOLBAR_FOLLOW: "Twitter",
|
||||
SETTINGS_TOOLBAR_READ: "Read Book",
|
||||
SETTINGS_TOOLBAR_KOFI: "Ko-fi",
|
||||
USE_DECLARATIVE_SETTINGS_NAME: "Use searchable settings",
|
||||
USE_DECLARATIVE_SETTINGS_DESC:
|
||||
"Use Obsidian's searchable, multi-page settings interface. Turn this off to use Excalidraw's legacy single-page settings. Requires restarting Obsidian.",
|
||||
|
||||
//settings.ts
|
||||
FOLDER_PLACEHOLDER: "e.g.: Excalidraw",
|
||||
@@ -414,8 +445,6 @@ export default {
|
||||
"Disables the Excalidraw context menu. This can be useful on Mobile devices where the context menu pops up in unwanted moments.",
|
||||
NOTEBOOKLM_LINK_ARIA:
|
||||
"Ask NotebookLM for help about the plugin. This model is pre-loaded with all my video transcripts, release notes and other helpful content. Chat with NotebookLM to explore my 250+ videos and the Excalidraw documentation.",
|
||||
NOTEBOOKLM_LINK_TEXT:
|
||||
"Learn the Plugin. Access the NotebookLM knowledgebase.",
|
||||
EXCALIDRAW_MASTERY: "Excalidraw Mastery",
|
||||
EXCALIDRAW_MASTERY_PROMO_ARIA: "Open Excalidraw Mastery",
|
||||
EXCALIDRAW_MASTERY_PROMO_HTML: `<p><b>Feeling lost in the toggles and menus?</b></p><p>Excalidraw is a Visual PKM powerhouse built for heavy-duty workflows like <b>Visual-First Daily Notes</b>, deep <b>PDF research</b>, <b>automation</b>, <b>AI integration</b>, and <b>Visual Zettelkasten</b>. But all this power comes with complexity.</p><p>Skip the trial and error. <a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}" target="_blank">👉 Join Excalidraw Mastery</a> to learn these exact setups step-by-step. Overcome tool friction and master your knowledge alongside a supportive community of visual thinkers!</p>`,
|
||||
@@ -449,6 +478,15 @@ export default {
|
||||
"<b><u>Toggle OFF:</u></b> Silent mode. You need to check for plugin updates in Community Plugins.",
|
||||
|
||||
BASIC_HEAD: "Basic",
|
||||
BASIC_UPDATES_STARTUP_HEAD: "Updates and startup",
|
||||
BASIC_UPDATES_STARTUP_DESC:
|
||||
"Release notes, update checks and notifications, and the startup splash screen.",
|
||||
BASIC_FILES_FOLDERS_HEAD: "Files and folders",
|
||||
BASIC_FILES_FOLDERS_DESC:
|
||||
"Default folders and paths for drawings, crops, annotations, templates, and Excalidraw Automate scripts.",
|
||||
BASIC_STENCIL_LIBRARY_HEAD: "Stencil Library",
|
||||
BASIC_STENCIL_LIBRARY_DESC:
|
||||
"Choose where stencil library data is stored and configure its vault folder and local library file.",
|
||||
BASIC_DESC: `In the "Basic" settings, you can configure options such as displaying release notes after updates, receiving plugin update notifications, setting the default location for new drawings, specifying the Excalidraw folder for embedding drawings into active documents, defining an Excalidraw template file, and designating an Excalidraw Automate script folder for managing automation scripts.`,
|
||||
FOLDER_NAME: "Excalidraw folder (CAsE sEnsITive!)",
|
||||
FOLDER_DESC:
|
||||
@@ -648,6 +686,9 @@ export default {
|
||||
AI_USAGE_SETTINGS_BUTTON_DESC:
|
||||
"View AI token consumption for the current Obsidian session broken down by model. Usage resets on restart.",
|
||||
SAVING_HEAD: "Saving",
|
||||
SAVING_STORAGE_AUTOSAVE_HEAD: "Storage and autosave",
|
||||
SAVING_STORAGE_AUTOSAVE_DESC:
|
||||
"Control drawing JSON compression and choose desktop and mobile autosave intervals.",
|
||||
SAVING_DESC:
|
||||
"In the 'Saving' section of Excalidraw Settings, you can configure how your drawings are saved. This includes options for compressing Excalidraw JSON in Markdown, setting autosave intervals for both desktop and mobile, defining filename formats, and choosing whether to use the .excalidraw.md or .md file extension. ",
|
||||
COMPRESS_NAME: "Compress Excalidraw JSON in Markdown",
|
||||
@@ -681,6 +722,8 @@ export default {
|
||||
"Excalidraw will not be able to save your work when terminating Obsidian directly (i.e. swiping it away). Also note, that when you switch apps on a Mobile device, sometimes Android and iOS closes " +
|
||||
"Obsidian in the background to save system resources. In such a case Excalidraw will not be able to save the latest changes.",
|
||||
FILENAME_HEAD: "Filename",
|
||||
FILENAME_GROUP_DESC:
|
||||
"Configure how new, embedded, cropped, and annotated drawing filenames are generated.",
|
||||
FILENAME_DESC:
|
||||
`<p>Click this link for the <a href="${URLs.MOMENTJS_COM_DOCS}">` +
|
||||
"date and time format reference</a>.</p>",
|
||||
@@ -708,6 +751,9 @@ export default {
|
||||
DISPLAY_HEAD: "Excalidraw appearance and behavior",
|
||||
DISPLAY_DESC:
|
||||
"In the 'appearance and behavior' section of Excalidraw Settings, you can fine-tune how Excalidraw appears and behaves. This includes options for dynamic styling, left-handed mode, matching Excalidraw and Obsidian themes, default modes, and more.",
|
||||
DISPLAY_EDITOR_PREVIEWS_HEAD: "Editing and previews",
|
||||
DISPLAY_EDITOR_PREVIEWS_DESC:
|
||||
"Configure canvas editing gestures and how Excalidraw files appear in reading mode and hover previews.",
|
||||
OVERRIDE_OBSIDIAN_FONT_SIZE_NAME: "Limit Obsidian Font Size to Editor Text",
|
||||
OVERRIDE_OBSIDIAN_FONT_SIZE_DESC:
|
||||
"Obsidian's custom font size setting affects the entire interface, including Excalidraw and themes that depend on the default font size. " +
|
||||
@@ -788,6 +834,8 @@ export default {
|
||||
}'>Markdown Reading Mode</a> under 'Appearance and Behavior' further above.<br>` +
|
||||
`⚠️ You must close and reopen the Excalidraw/markdown file for changes to take effect. ⚠️`,
|
||||
MODES_HEAD: "UI Modes",
|
||||
MODES_DESC:
|
||||
"Choose device-specific Excalidraw interface layouts, title-bar controls, and left- or right-handed tray placement.",
|
||||
DESKTOP_UI_MODE_NAME: "Preferred Desktop Mode",
|
||||
DESKTOP_UI_MODE_DESC: "Select the default UI mode for desktop devices.",
|
||||
TABLET_UI_MODE_NAME: "Preferred Tablet Mode",
|
||||
@@ -800,12 +848,19 @@ export default {
|
||||
MODE_PHONE: "Phone-mode",
|
||||
REAPPLY_UI_MODE_BUTTON: "Reapply UI mode now",
|
||||
HOTKEY_OVERRIDE_HEAD: "Hotkey overrides",
|
||||
HOTKEY_OVERRIDE_GROUP_DESC:
|
||||
"Manage Excalidraw key combinations that should take priority over conflicting Obsidian hotkeys.",
|
||||
HOTKEY_OVERRIDE_CONTROL_NAME: "Manage hotkey overrides",
|
||||
HOTKEY_OVERRIDE_DESC:
|
||||
`Some of the Excalidraw hotkeys such as <code>${labelCTRL()}+Enter</code> to edit text or <code>${labelCTRL()}+K</code> to create an element link ` +
|
||||
"conflict with Obsidian hotkey settings. The hotkey combinations you add below will override Obsidian's hotkey settings while using Excalidraw, thus " +
|
||||
`you can add <code>${labelCTRL()}+G</code> if you want to default to Group Object in Excalidraw instead of opening Graph View.`,
|
||||
THEME_HEAD: "Theme and styling",
|
||||
THEME_DESC:
|
||||
"Control interface styling, drawing and embed themes, opening mode, and mobile safe-area spacing.",
|
||||
ZOOM_AND_PAN_HEAD: "Zoom and Pan",
|
||||
ZOOM_AND_PAN_DESC:
|
||||
"Configure mouse, touch, opening, resizing, and zoom-range behavior.",
|
||||
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "Right-click drag to pan",
|
||||
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
|
||||
"Right-click and drag to pan the canvas (Miro-style). Press 'm' to open the context menu.",
|
||||
@@ -838,7 +893,11 @@ export default {
|
||||
ZOOM_MAX_DESC:
|
||||
"Upper zoom limit. Default: 3000%. Usually no need to change; included for completeness.",
|
||||
PEN_HEAD: "Pen",
|
||||
PEN_DESC:
|
||||
"Configure automatic pen mode, touch gestures, the eraser, and the freedraw crosshair.",
|
||||
GRID_HEAD: "Grid",
|
||||
GRID_DESC:
|
||||
"Configure grid direction, automatic or custom color, and opacity.",
|
||||
GRID_DYNAMIC_COLOR_NAME: "Dynamic grid color",
|
||||
GRID_DYNAMIC_COLOR_DESC:
|
||||
"<b><u>Toggle ON:</u></b>Change grid color to match the canvas color<br><b><u>Toggle OFF:</u></b>Use the color below as the grid color",
|
||||
@@ -852,6 +911,8 @@ export default {
|
||||
GRID_HORIZONTAL: "Render horizontal grid",
|
||||
GRID_VERTICAL: "Render vertical grid",
|
||||
LASER_HEAD: "Laser pointer",
|
||||
LASER_DESC:
|
||||
"Configure the laser pointer color and how quickly and how far its trail fades.",
|
||||
LASER_COLOR: "Laser pointer color",
|
||||
LASER_DECAY_TIME_NAME: "Laser pointer decay time",
|
||||
LASER_DECAY_TIME_DESC:
|
||||
@@ -871,6 +932,21 @@ export default {
|
||||
"When Obsidian files change, the matching <code>[[link]]</code> in your drawings will also change. " +
|
||||
"If you don't want text accidentally changing in your drawings use <code>[[links|with aliases]]</code>.",
|
||||
DRAG_MODIFIER_NAME: "Link Click and Drag&Drop Modifier Keys",
|
||||
DRAG_MODIFIER_GROUP_DESC:
|
||||
"Configure link-opening gestures and platform-specific modifier combinations for clicks and drag-and-drop actions.",
|
||||
LINK_OPENING_GESTURES_HEAD: "Link-opening gestures",
|
||||
LINK_OPENING_GESTURES_DESC:
|
||||
"Configure long-press delays and double-click link opening for embedded drawings and view mode.",
|
||||
WEB_BROWSER_DRAG_ACTION_DESC:
|
||||
"Choose modifier combinations for links, images, imports, and embeddables dragged from a web browser.",
|
||||
LOCAL_FILE_DRAG_ACTION_DESC:
|
||||
"Choose modifier combinations for links, images, imports, and embeddables dragged from the operating system.",
|
||||
INTERNAL_DRAG_ACTION_DESC:
|
||||
"Choose modifier combinations for links, images, full-size images, and embeddables dragged inside Obsidian.",
|
||||
PANE_TARGET_DESC:
|
||||
"Choose modifier combinations that determine where clicked links open.",
|
||||
MODIFIER_KEY_USAGE_NAME: "Configuring modifier keys",
|
||||
MODIFIER_KEY_COMBINATIONS: "Modifier combinations",
|
||||
DRAG_MODIFIER_DESC:
|
||||
`Modifier key behavior when clicking links and dragging and dropping elements. ` +
|
||||
`Excalidraw will not validate your configuration... pay attention to avoid conflicting settings. ` +
|
||||
@@ -968,6 +1044,22 @@ export default {
|
||||
"Use the <code>http" +
|
||||
"s://noembed" +
|
||||
".com/embed?url=</code> to get title of page when dropping an HTTPS link into Excalidraw",
|
||||
LINK_BEHAVIOR_HEAD: "Link behavior",
|
||||
LINK_BEHAVIOR_DESC:
|
||||
"Configure link synchronization, related links, hover previews, click handling, and web-page title lookup.",
|
||||
LINK_USAGE_NAME: "Using links in Excalidraw",
|
||||
LINK_OPENING_HEAD: "Pane and tab behavior",
|
||||
LINK_OPENING_DESC:
|
||||
"Choose whether opened links reuse, focus, or move between panes, tabs, and the main workspace.",
|
||||
LINK_APPEARANCE_HEAD: "Link appearance",
|
||||
LINK_APPEARANCE_DESC:
|
||||
"Configure brackets, prefixes, icons, and opacity used when links are displayed.",
|
||||
TODO_HEAD: "TODOs",
|
||||
TODO_GROUP_DESC:
|
||||
"Configure TODO parsing and the icons used for open and completed tasks.",
|
||||
TRANSCLUSION_HEAD: "Text transclusions",
|
||||
TRANSCLUSION_DESC:
|
||||
"Configure character limits, wrapping, and quote cleanup for transcluded Markdown text.",
|
||||
PDF_TO_IMAGE: "PDF to Image",
|
||||
PDF_TO_IMAGE_SCALE_NAME: "PDF to Image conversion scale",
|
||||
PDF_TO_IMAGE_SCALE_DESC:
|
||||
@@ -977,7 +1069,12 @@ export default {
|
||||
EMBED_TOEXCALIDRAW_DESC:
|
||||
"In the Embed Files section of Excalidraw Settings, you can configure how various files are embedded into Excalidraw. This includes options for embedding interactive markdown files, PDFs, and markdown files as images.",
|
||||
MD_HEAD: "Embed markdown into Excalidraw as image",
|
||||
MD_GROUP_DESC:
|
||||
"Set dimensions, font, colors, borders, and CSS for Markdown files rendered as images.",
|
||||
MD_EMBED_CUSTOMDATA_HEAD_NAME: "Interactive Markdown Files",
|
||||
MD_EMBED_CUSTOMDATA_GROUP_DESC:
|
||||
"Configure editing and default appearance for future interactive Markdown embeds.",
|
||||
MD_EMBED_DEFAULTS_CONTROL_NAME: "Interactive Markdown appearance defaults",
|
||||
MD_EMBED_CUSTOMDATA_HEAD_DESC: `The below settings will only effect future embeds. Current embeds remain unchanged. The theme setting of embedded frames is under the "Excalidraw appearance and behavior" section.`,
|
||||
MD_EMBED_SINGLECLICK_EDIT_NAME: "Single click to edit embedded markdown",
|
||||
MD_EMBED_SINGLECLICK_EDIT_DESC:
|
||||
@@ -1021,12 +1118,17 @@ export default {
|
||||
EMBED_HEAD: "Embedding Excalidraw into your Notes and Exporting",
|
||||
EMBED_DESC: `In the "Embed & Export" settings, you can configure how images and Excalidraw drawings are embedded and exported within your documents. Key settings include choosing the image type for markdown preview (such as Native SVG or PNG), specifying the type of file to insert into the document (original Excalidraw, PNG, or SVG), and managing image caching for embedding in markdown. You can also control image sizing, whether to embed drawings using wiki links or markdown links, and adjust settings related to image themes, background colors, and Obsidian integration.
|
||||
Additionally, there are settings for auto-export, which automatically generates SVG and/or PNG files to match the title of your Excalidraw drawings, keeping them in sync with file renames and deletions.`,
|
||||
EMBED_PREVIEW_LINKS_HEAD: "Previews, links, and Canvas",
|
||||
EMBED_PREVIEW_LINKS_DESC:
|
||||
"Choose preview and inserted-file formats, source-link behavior, placeholders, and immersive Canvas embeds.",
|
||||
EMBED_CANVAS: "Obsidian Canvas support",
|
||||
EMBED_CANVAS_NAME: "Immersive embedding",
|
||||
EMBED_CANVAS_DESC:
|
||||
"Hide canvas node border and background when embedding an Excalidraw drawing to Canvas. " +
|
||||
"Note that for a full transparent background for your image, you will still need to configure Excalidraw to export images with transparent background.",
|
||||
EMBED_CACHING: "Image caching and rendering optimization",
|
||||
EMBED_CACHING_DESC:
|
||||
"Tune rendering concurrency and local image caches, purge cached images or backups, and optionally reuse exported previews.",
|
||||
RENDERING_CONCURRENCY_NAME: "Image rendering concurrency",
|
||||
RENDERING_CONCURRENCY_DESC:
|
||||
"Number of parallel workers to use for image rendering. Increasing this number will speed up the rendering process, but may slow down the rest of the system. " +
|
||||
@@ -1039,8 +1141,14 @@ export default {
|
||||
"The practical impact is local disk or browser-storage usage inside Obsidian. This can matter on phones and on desktops with tighter browser storage quotas or limited free disk space.<br><br>" +
|
||||
"Lower values reclaim local cache space sooner but may force more rerendering of PDFs and embedded drawings. Higher values keep repeat loads faster at the cost of more local cache storage.",
|
||||
EXPORT_SUBHEAD: "Export Settings",
|
||||
EXPORT_SUBHEAD_DESC:
|
||||
"Configure PDF rendering and exported scene data, image dimensions, theme and background, PDF defaults, and automatic PNG/SVG copies.",
|
||||
EMBED_SIZING: "Image sizing",
|
||||
EMBED_SIZING_DESC:
|
||||
"Set default embedded-image dimensions, PNG scale, and export padding.",
|
||||
EMBED_THEME_BACKGROUND: "Image theme and background color",
|
||||
EMBED_THEME_BACKGROUND_DESC:
|
||||
"Choose exported-image background and theme behavior and whether previews follow Obsidian's theme.",
|
||||
EMBED_IMAGE_CACHE_NAME: "Cache images for embedding in markdown",
|
||||
EMBED_IMAGE_CACHE_DESC:
|
||||
"Cache images for embedding in markdown. This will speed up the embedding process, but in case you compose images of several sub-component drawings, " +
|
||||
@@ -1121,7 +1229,18 @@ export default {
|
||||
"Embed Excalidraw scene in exported image. Can be overridden at a file level by adding the <code>excalidraw-export-embed-scene: true/false</code> frontmatter key. " +
|
||||
"The setting only takes effect the next time you (re)open drawings.",
|
||||
PDF_EXPORT_SETTINGS: "PDF Export Settings",
|
||||
PDF_EXPORT_SETTINGS_DESC:
|
||||
"Choose default PDF page size, orientation, tiling, margins, paper color, and alignment.",
|
||||
PDF_EXPORT_DEFAULTS_CONTROL_NAME: "Default PDF export layout",
|
||||
EXPORT_HEAD: "Auto-export Settings",
|
||||
EXPORT_AUTOEXPORT_DESC:
|
||||
"Keep exported files synchronized and automatically create SVG, PNG, light, and dark variants.",
|
||||
SETTINGS_NAVIGATION_OPEN: "Open",
|
||||
SETTINGS_BREADCRUMB_ARIA: "Settings path",
|
||||
SETTINGS_RELATED_AUTOEXPORT_DESC:
|
||||
"Enable automatic PNG or SVG copies to make those formats available in the inserted-file dropdown.",
|
||||
SETTINGS_RELATED_EMBED_TYPE_DESC:
|
||||
"Choose whether Excalidraw, PNG, or SVG is inserted when you embed a drawing in a document.",
|
||||
EXPORT_SYNC_NAME:
|
||||
"Keep the .SVG and/or .PNG filenames in sync with the drawing file",
|
||||
EXPORT_SYNC_DESC:
|
||||
@@ -1195,8 +1314,11 @@ export default {
|
||||
CUSTOM_PEN_DESC:
|
||||
"You will see these pens next to the Obsidian Menu on the canvas. You can customize the pens on the canvas by long-pressing the pen button.",
|
||||
EXPERIMENTAL_HEAD: "Miscellaneous features",
|
||||
EXPERIMENTAL_DESC: `These miscellaneous features in Excalidraw include options for setting default LaTeX formulas for new equations, enabling a Field Suggester for autocompletion, displaying type indicators for Excalidraw files, enabling immersive image embedding in live preview editing mode, and experimenting with Taskbone Optical Character Recognition for text extraction from images and drawings. Users can also enter a Taskbone API key for extended usage of the OCR service.`,
|
||||
EXPERIMENTAL_DESC:
|
||||
"Configure LaTeX defaults, file type indicators, live preview behavior, property suggestions, and the experimental Taskbone OCR integration.",
|
||||
EA_HEAD: "Excalidraw Automate",
|
||||
EA_GROUP_DESC:
|
||||
"Configure Excalidraw Automate scripting, startup and autostart behavior, command links, and settings exposed by installed scripts.",
|
||||
EA_DESC:
|
||||
"ExcalidrawAutomate is a scripting and automation API for Excalidraw. Unfortunately, the documentation of the API is sparse. " +
|
||||
`I recommend reading the <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_API_EXCALIDRAWAUTOMATE_D_TS}">ExcalidrawAutomate.d.ts</a> file, ` +
|
||||
@@ -1207,6 +1329,33 @@ export default {
|
||||
FIELD_SUGGESTER_DESC:
|
||||
"Field Suggester borrowed from Breadcrumbs and Templater plugins. The Field Suggester will show an autocomplete menu " +
|
||||
"when you type <code>excalidraw-</code> or <code>ea.</code> with function description as hints on the individual items in the list.",
|
||||
ALLOW_JS_FILES_NAME: "Load JavaScript files from the Scripts folder",
|
||||
ALLOW_JS_FILES_DESC:
|
||||
"When enabled, Excalidraw Automate monitors and runs <code>.js</code> files in the Scripts folder and accepts a <code>.js</code> startup script. " +
|
||||
"By default, Obsidian Sync does not sync non-Markdown files, Obsidian does not open <code>.js</code> files for editing, and File Explorer hides them. Enable <b>Sync all other types</b> and <b>Show all file types</b> in Obsidian when needed. If matching <code>.md</code> and <code>.js</code> scripts exist, the Markdown file is used.",
|
||||
STORE_SCRIPTS_AS_JS_NAME: "Store downloaded scripts as",
|
||||
STORE_SCRIPTS_AS_JS_DESC:
|
||||
"Choose the local file type used for new Script Library downloads and updates. This is independent of whether the remote source is <code>.md</code> or <code>.js</code>.",
|
||||
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
|
||||
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
|
||||
MIGRATE_SCRIPT_FILES_NAME: "Move existing script files",
|
||||
MIGRATE_SCRIPTS_TO_JS_BUTTON: "Move existing scripts to .js",
|
||||
MIGRATE_SCRIPTS_TO_MD_BUTTON: "Move existing scripts to .md",
|
||||
MIGRATE_SCRIPT_FILES_STATUS:
|
||||
"{eligible} script file(s) can be moved to {extension}. {skipped}",
|
||||
MIGRATE_SCRIPT_FILES_CONFIRM:
|
||||
"Back up your vault before continuing.<br><br><b>{count}</b> script file(s) will be renamed to <code>{extension}</code>. Pinned script paths will be updated. {startup} {skipped}",
|
||||
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
|
||||
"The configured startup script and its setting will also be updated.",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED:
|
||||
"{count} same-named .md/.js pair(s) will not be moved.",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
|
||||
"Skipped {count} script file(s) because the destination already exists:\n{files}",
|
||||
MIGRATE_SCRIPT_FILES_NONE: "No eligible script files were found to move.",
|
||||
MIGRATE_SCRIPT_FILES_COMPLETE:
|
||||
"Moved {count} script file(s) to {extension}.",
|
||||
MIGRATE_SCRIPT_FILES_FAILED:
|
||||
"Could not move the script files. Completed renames were rolled back where possible.",
|
||||
ENABLE_ONLOAD_SCRIPTS_NAME: "Enable onload scripts",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
|
||||
"This file includes an <code>excalidraw-onload-script</code>. Do you want to enable onload scripts?",
|
||||
@@ -1216,6 +1365,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 → Excalidraw Automate → 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?",
|
||||
@@ -1226,9 +1388,10 @@ export default {
|
||||
"This creates a risk if you open drawings from unknown sources: a malicious drawing can make a normal click trigger privileged commands. " +
|
||||
"Only enable this if you trust the file and its source.",
|
||||
STARTUP_SCRIPT_NAME: "Startup script",
|
||||
STARTUP_SCRIPT_JS_DISABLED:
|
||||
"JavaScript startup scripts are disabled. Enable JavaScript files in Excalidraw Automate settings first.",
|
||||
STARTUP_SCRIPT_DESC:
|
||||
"If set, excalidraw will execute the script at plugin startup. This is useful if you want to set any of the Excalidraw Automate hooks. The startup script is a markdown file " +
|
||||
"that should contain the javascript code you want to execute when Excalidraw starts.",
|
||||
"If set, Excalidraw will execute the script at plugin startup. This is useful for configuring Excalidraw Automate hooks. Extensionless paths use a Markdown file; <code>.js</code> files are accepted when JavaScript-file loading is enabled.",
|
||||
STARTUP_SCRIPT_BUTTON_CREATE: "Create startup script",
|
||||
STARTUP_SCRIPT_BUTTON_OPEN: "Open startup script",
|
||||
FILETYPE_NAME: "Display type (✏️) for excalidraw.md files in File Explorer",
|
||||
@@ -1272,6 +1435,8 @@ export default {
|
||||
"For optimal performance, it is recommended to use a .woff2 file, as Excalidraw will encode only the necessary glyphs when exporting images to SVG. " +
|
||||
"Other font formats will embed the entire font in the exported file, potentially resulting in significantly larger file sizes.",
|
||||
OFFLINE_CJK_NAME: "Offline CJK font support",
|
||||
OFFLINE_CJK_GROUP_DESC:
|
||||
"Download and selectively preload Chinese, Japanese, and Korean fonts so Excalidraw can render them without an internet connection.",
|
||||
OFFLINE_CJK_DESC: `<strong>Changes you make here will only take effect after restarting Obsidian.</strong><br>
|
||||
Excalidraw.com offers handwritten CJK fonts. By default these fonts are not included in the plugin locally, but are served from the Internet.
|
||||
If you prefer to keep Excalidraw fully local, allowing it to work without Internet access you can download the necessary <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RAW_REFS_HEADS_MASTER_ASSETS_EXCALIDRAW_FONTS_ZIP}" target="_blank">font files from GitHub</a>.
|
||||
@@ -1288,6 +1453,8 @@ export default {
|
||||
SCRIPT_SETTINGS_DESC:
|
||||
"Some of the Excalidraw Automate Scripts include settings. Settings are organized by script. Settings will only become visible in this list after you have executed the newly downloaded script once.",
|
||||
TASKBONE_HEAD: "Taskbone Optical Character Recognition",
|
||||
TASKBONE_GROUP_DESC:
|
||||
"Configure the optional Taskbone online OCR service for extracting searchable text from drawings and images.",
|
||||
TASKBONE_DESC:
|
||||
"This is an experimental integration of optical character recognition into Excalidraw. Please note, that taskbone is an independent external service not provided by Excalidraw, nor the Excalidraw-Obsidian plugin project. " +
|
||||
"The OCR service will grab legible text from freedraw lines and embedded pictures on your canvas and place the recognized text in the frontmatter of your drawing as well as onto clipboard. " +
|
||||
@@ -1467,6 +1634,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 +1661,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 +1998,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.",
|
||||
};
|
||||
+198
-5
@@ -19,6 +19,23 @@ export default {
|
||||
// Sugester
|
||||
SELECT_FILE_TO_INSERT: "Selecciona un archivo para insertar",
|
||||
// main.ts
|
||||
SETTINGS_DATA_INVALID:
|
||||
"Excalidraw está esperando un archivo data.json válido. Los cambios no se guardarán hasta que se restaure el archivo o reinicies Obsidian y elijas Restablecer valores predeterminados.",
|
||||
SETTINGS_DATA_REPAIRED_FROM_MEMORY:
|
||||
"Se recibió y rechazó un archivo de configuración de Excalidraw vacío o ilegible. La configuración activa se volvió a guardar para reparar data.json.",
|
||||
SETTINGS_DATA_RECOVERED:
|
||||
"El archivo data.json de Excalidraw estaba vacío o no se podía leer. La última configuración válida se restauró automáticamente.",
|
||||
SETTINGS_RECOVERY_MISSING_TITLE:
|
||||
"Falta el archivo de configuración de Excalidraw",
|
||||
SETTINGS_RECOVERY_MISSING_DESC:
|
||||
"Existe una copia válida de la configuración en este dispositivo. Restaura la copia o restablece Excalidraw a los valores de fábrica. Al cerrar este mensaje se restaurará la copia.",
|
||||
SETTINGS_RECOVERY_CORRUPT_TITLE:
|
||||
"El archivo de configuración de Excalidraw está dañado",
|
||||
SETTINGS_RECOVERY_CORRUPT_DESC:
|
||||
"El archivo está vacío o no se puede leer y no hay una copia de recuperación en este dispositivo. Restablece Excalidraw a los valores de fábrica o deja el archivo sin cambios mientras restauras un data.json válido desde otra fuente. Al cerrar este mensaje se esperará un archivo de reemplazo.",
|
||||
SETTINGS_RECOVERY_RESTORE_BACKUP: "Restaurar copia",
|
||||
SETTINGS_RECOVERY_RESET_DEFAULTS: "Restablecer valores predeterminados",
|
||||
SETTINGS_RECOVERY_WAIT_FOR_FILE: "Esperar archivo restaurado",
|
||||
CONVERT_URL_TO_FILE: "Guardar imagen desde el URL en un archivo local",
|
||||
UNZIP_CURRENT_FILE: "Descomprimir el archivo Excalidraw actual",
|
||||
PUBLISH_SVG_CHECK:
|
||||
@@ -373,12 +390,22 @@ export default {
|
||||
SEARCH_SHOWHIDE_ARIA: "Mostrar/Ocultar barra de búsqueda",
|
||||
SEARCH_NEXT: "Siguiente",
|
||||
SEARCH_PREVIOUS: "Anterior",
|
||||
SETTINGS_TOOLBAR_COPY: "Copiar ajustes",
|
||||
SETTINGS_TOOLBAR_NOTEBOOKLM: "NotebookLM",
|
||||
SETTINGS_TOOLBAR_BUGS: "Errores",
|
||||
SETTINGS_TOOLBAR_WIKI: "Wiki",
|
||||
SETTINGS_TOOLBAR_YOUTUBE: "YouTube",
|
||||
SETTINGS_TOOLBAR_LEARN: "Aprender",
|
||||
SETTINGS_TOOLBAR_FOLLOW: "Twitter",
|
||||
SETTINGS_TOOLBAR_READ: "Leer libro",
|
||||
SETTINGS_TOOLBAR_KOFI: "Ko-fi",
|
||||
USE_DECLARATIVE_SETTINGS_NAME: "Usar ajustes con búsqueda",
|
||||
USE_DECLARATIVE_SETTINGS_DESC:
|
||||
"Usa la interfaz de ajustes de Obsidian con búsqueda y varias páginas. Desactívala para usar los ajustes heredados de Excalidraw en una sola página. Requiere reiniciar Obsidian.",
|
||||
|
||||
//settings.ts
|
||||
NOTEBOOKLM_LINK_ARIA:
|
||||
"Pídele ayuda a NotebookLM sobre el complemento. Este modelo viene precargado con todas mis transcripciones de videos, notas de lanzamiento y otro contenido útil. Chatea con NotebookLM para explorar mis más de 250 videos y la documentación de Excalidraw.",
|
||||
NOTEBOOKLM_LINK_TEXT:
|
||||
"Aprende sobre el complemento. Accede a la base de conocimientos de NotebookLM.",
|
||||
LINKS_BUGS_ARIA:
|
||||
"Reporta errores y solicita nuevas funciones en la página de GitHub del complemento",
|
||||
LINKS_BUGS: "Reportar Errores",
|
||||
@@ -408,6 +435,15 @@ export default {
|
||||
"<b><u>Desactivado:</u></b> Modo silencioso. Necesitarás verificar las actualizaciones del complemento en Complementos Comunitarios.",
|
||||
|
||||
BASIC_HEAD: "Básico",
|
||||
BASIC_UPDATES_STARTUP_HEAD: "Actualizaciones e inicio",
|
||||
BASIC_UPDATES_STARTUP_DESC:
|
||||
"Notas de la versión, comprobaciones y avisos de actualizaciones, y la pantalla de inicio.",
|
||||
BASIC_FILES_FOLDERS_HEAD: "Archivos y carpetas",
|
||||
BASIC_FILES_FOLDERS_DESC:
|
||||
"Carpetas y rutas predeterminadas para dibujos, recortes, anotaciones, plantillas y scripts de Excalidraw Automate.",
|
||||
BASIC_STENCIL_LIBRARY_HEAD: "Biblioteca de elementos",
|
||||
BASIC_STENCIL_LIBRARY_DESC:
|
||||
"Elige dónde se guardan los datos de la biblioteca de elementos y configura su carpeta y archivo local.",
|
||||
BASIC_DESC: `En la configuración "Básico", puedes configurar opciones como mostrar las notas de la versión después de las actualizaciones, recibir notificaciones de actualización del complemento, establecer la ubicación predeterminada para nuevos bosquejos, especificar la carpeta de Excalidraw para incrustar bosquejos en documentos activos, definir un archivo de plantilla de Excalidraw, y designar una carpeta de scripts de Excalidraw Automate para gestionar scripts de automatización.`,
|
||||
FOLDER_NAME: "Carpeta de Excalidraw (¡Sensible a MAYÚSCULAS/minúsculas!)",
|
||||
FOLDER_DESC:
|
||||
@@ -621,6 +657,9 @@ export default {
|
||||
AI_USAGE_SETTINGS_BUTTON_DESC:
|
||||
"Ver el consumo de tokens de IA en la sesión actual de Obsidian desglosado por modelo. El uso se reinicia al reiniciar.",
|
||||
SAVING_HEAD: "Guardar",
|
||||
SAVING_STORAGE_AUTOSAVE_HEAD: "Almacenamiento y guardado automático",
|
||||
SAVING_STORAGE_AUTOSAVE_DESC:
|
||||
"Controla la compresión del JSON de los dibujos y los intervalos de guardado automático en escritorio y móvil.",
|
||||
SAVING_DESC:
|
||||
"En la sección 'Guardar' de la Configuración de Excalidraw, puedes configurar cómo se guardan tus bosquejos. Esto incluye opciones para comprimir el JSON de Excalidraw en Markdown, establecer intervalos de autoguardado para escritorio y móvil, definir formatos de nombre de archivo y elegir si usar la extensión de archivo .excalidraw.md o .md. ",
|
||||
COMPRESS_NAME: "Comprimir JSON de Excalidraw en Markdown",
|
||||
@@ -655,6 +694,8 @@ export default {
|
||||
"Excalidraw no podrá guardar tu trabajo al cerrar Obsidian directamente (es decir, al deslizar la aplicación para cerrarla). También ten en cuenta que cuando cambias de aplicación en un dispositivo móvil, a veces Android e iOS cierran " +
|
||||
"Obsidian en segundo plano para ahorrar recursos del sistema. En tal caso, Excalidraw no podrá guardar los últimos cambios.",
|
||||
FILENAME_HEAD: "Nombre de archivo",
|
||||
FILENAME_GROUP_DESC:
|
||||
"Configura cómo se generan los nombres de dibujos nuevos, incrustados, recortados y anotados.",
|
||||
FILENAME_DESC:
|
||||
`<p>Haz click en este enlace para la <a href="${URLs.MOMENTJS_COM_DOCS}">` +
|
||||
`referencia de formato de fecha y hora</a>.</p>`,
|
||||
@@ -683,6 +724,9 @@ export default {
|
||||
DISPLAY_HEAD: "Apariencia y Comportamiento de Excalidraw",
|
||||
DISPLAY_DESC:
|
||||
"En la sección 'Apariencia y Comportamiento' de la Configuración de Excalidraw, puedes ajustar cómo se ve y se comporta Excalidraw. Esto incluye opciones para estilos dinámicos, modo para zurdos, coincidencia de temas de Excalidraw y Obsidian, modos predeterminados y más.",
|
||||
DISPLAY_EDITOR_PREVIEWS_HEAD: "Edición y vistas previas",
|
||||
DISPLAY_EDITOR_PREVIEWS_DESC:
|
||||
"Configura los gestos de edición del lienzo y cómo aparecen los archivos de Excalidraw en el modo de lectura y las vistas previas al pasar el cursor.",
|
||||
OVERRIDE_OBSIDIAN_FONT_SIZE_NAME:
|
||||
"Limitar tamaño de fuente de Obsidian al texto del editor",
|
||||
OVERRIDE_OBSIDIAN_FONT_SIZE_DESC:
|
||||
@@ -762,13 +806,22 @@ export default {
|
||||
}'>Modo de Lectura de Markdown</a> en 'Apariencia y Comportamiento' más arriba.<br>` +
|
||||
`⚠️ Debes cerrar y volver a abrir el archivo de Excalidraw/Markdown para que los cambios surtan efecto. ⚠️`,
|
||||
MODES_HEAD: "Modos",
|
||||
MODES_DESC:
|
||||
"Elige diseños de interfaz específicos para cada dispositivo, controles de la barra de título y la posición de la bandeja para diestros o zurdos.",
|
||||
HOTKEY_OVERRIDE_HEAD: "Anulaciones de atajos de teclado",
|
||||
HOTKEY_OVERRIDE_GROUP_DESC:
|
||||
"Administra las combinaciones de Excalidraw que deben tener prioridad sobre los atajos de Obsidian en conflicto.",
|
||||
HOTKEY_OVERRIDE_CONTROL_NAME: "Administrar anulaciones de atajos",
|
||||
HOTKEY_OVERRIDE_DESC:
|
||||
`Algunos de los atajos de teclado de Excalidraw, como <code>${labelCTRL()}+Enter</code> para editar texto o <code>${labelCTRL()}+K</code> para crear un enlace de elemento ` +
|
||||
"entran en conflicto con la configuración de atajos de teclado de Obsidian. Las combinaciones de atajos de teclado que agregues a continuación anularán la configuración de atajos de teclado de Obsidian mientras usas Excalidraw. Por lo tanto, " +
|
||||
`puedes agregar <code>${labelCTRL()}+G</code> si quieres que el comportamiento predeterminado sea Agrupar Objeto en Excalidraw en lugar de abrir la Vista de Gráfico.`,
|
||||
THEME_HEAD: "Tema y estilo",
|
||||
THEME_DESC:
|
||||
"Controla el estilo de la interfaz, los temas de dibujos e incrustaciones, el modo de apertura y el espacio seguro en móviles.",
|
||||
ZOOM_AND_PAN_HEAD: "Zoom y panorámica",
|
||||
ZOOM_AND_PAN_DESC:
|
||||
"Configura el comportamiento del ratón, el tacto, la apertura, el cambio de tamaño y el intervalo de zoom.",
|
||||
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME:
|
||||
"Desplazar el lienzo con el botón derecho del mouse (abrir menú con 'm')",
|
||||
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
|
||||
@@ -802,7 +855,11 @@ export default {
|
||||
ZOOM_MAX_DESC:
|
||||
"Límite superior del zoom. Predeterminado: 3000%. Por lo general, no es necesario cambiarlo; se incluye para ser exhaustivos.",
|
||||
PEN_HEAD: "Lápiz",
|
||||
PEN_DESC:
|
||||
"Configura el modo lápiz automático, los gestos táctiles, el borrador y la cruz de dibujo libre.",
|
||||
GRID_HEAD: "Cuadrícula",
|
||||
GRID_DESC:
|
||||
"Configura la dirección de la cuadrícula, el color automático o personalizado y la opacidad.",
|
||||
GRID_DYNAMIC_COLOR_NAME: "Color de cuadrícula dinámica",
|
||||
GRID_DYNAMIC_COLOR_DESC:
|
||||
"<b><u>Activado:</u></b> Cambia el color de la cuadrícula para que coincida con el color del lienzo<br><b><u>Desactivado:</u></bUsar el color de abajo como color de la cuadrícula",
|
||||
@@ -817,6 +874,8 @@ export default {
|
||||
GRID_HORIZONTAL: "Renderizar cuadrícula horizontal",
|
||||
GRID_VERTICAL: "Renderizar cuadrícula vertical",
|
||||
LASER_HEAD: "Puntero láser",
|
||||
LASER_DESC:
|
||||
"Configura el color del puntero láser y la rapidez y distancia con que se desvanece su rastro.",
|
||||
LASER_COLOR: "Color del puntero láser",
|
||||
LASER_DECAY_TIME_NAME: "Tiempo de desvanecimiento del puntero láser",
|
||||
LASER_DECAY_TIME_DESC:
|
||||
@@ -837,6 +896,21 @@ export default {
|
||||
"Si no quieres que el texto cambie accidentalmente en tus bosquejos, usa <code>[[enlaces|con alias]]</code>.",
|
||||
DRAG_MODIFIER_NAME:
|
||||
"Teclas modificadoras para click de enlace y Arrastrar y Soltar(Drag&Drop)",
|
||||
DRAG_MODIFIER_GROUP_DESC:
|
||||
"Configura gestos para abrir enlaces y combinaciones de modificadores para clics y acciones de arrastrar y soltar.",
|
||||
LINK_OPENING_GESTURES_HEAD: "Gestos para abrir enlaces",
|
||||
LINK_OPENING_GESTURES_DESC:
|
||||
"Configura retrasos de pulsación prolongada y la apertura con doble clic en dibujos incrustados y el modo de vista.",
|
||||
WEB_BROWSER_DRAG_ACTION_DESC:
|
||||
"Elige modificadores para enlaces, imágenes, importaciones e incrustaciones arrastradas desde un navegador web.",
|
||||
LOCAL_FILE_DRAG_ACTION_DESC:
|
||||
"Elige modificadores para enlaces, imágenes, importaciones e incrustaciones arrastradas desde el sistema operativo.",
|
||||
INTERNAL_DRAG_ACTION_DESC:
|
||||
"Elige modificadores para enlaces, imágenes, imágenes a tamaño completo e incrustaciones arrastradas dentro de Obsidian.",
|
||||
PANE_TARGET_DESC:
|
||||
"Elige combinaciones de modificadores que determinan dónde se abren los enlaces.",
|
||||
MODIFIER_KEY_USAGE_NAME: "Configurar teclas modificadoras",
|
||||
MODIFIER_KEY_COMBINATIONS: "Combinaciones de modificadores",
|
||||
DRAG_MODIFIER_DESC:
|
||||
`Comportamiento de la tecla modificadora al hacer click en enlaces y arrastrar y soltar elementos. ` +
|
||||
`Excalidraw no validará tu configuración... presta atención para evitar configuraciones conflictivas. ` +
|
||||
@@ -935,6 +1009,22 @@ export default {
|
||||
"Usa <code>http" +
|
||||
"s://noembed" +
|
||||
".com/embed?url=</code> para obtener el título de la página al soltar un enlace HTTPS en Excalidraw.",
|
||||
LINK_BEHAVIOR_HEAD: "Comportamiento de enlaces",
|
||||
LINK_BEHAVIOR_DESC:
|
||||
"Configura la sincronización, enlaces relacionados, vistas previas, clics y la búsqueda de títulos web.",
|
||||
LINK_USAGE_NAME: "Usar enlaces en Excalidraw",
|
||||
LINK_OPENING_HEAD: "Comportamiento de paneles y pestañas",
|
||||
LINK_OPENING_DESC:
|
||||
"Elige si los enlaces reutilizan, enfocan o cambian entre paneles, pestañas y el espacio de trabajo principal.",
|
||||
LINK_APPEARANCE_HEAD: "Apariencia de enlaces",
|
||||
LINK_APPEARANCE_DESC:
|
||||
"Configura corchetes, prefijos, iconos y opacidad al mostrar enlaces.",
|
||||
TODO_HEAD: "Tareas pendientes",
|
||||
TODO_GROUP_DESC:
|
||||
"Configura el análisis de tareas y los iconos para tareas abiertas y completadas.",
|
||||
TRANSCLUSION_HEAD: "Transclusiones de texto",
|
||||
TRANSCLUSION_DESC:
|
||||
"Configura límites de caracteres, ajuste de línea y limpieza de citas para texto Markdown transcluido.",
|
||||
PDF_TO_IMAGE: "PDF a Image",
|
||||
PDF_TO_IMAGE_SCALE_NAME: "Escala de conversión de PDF a imagen",
|
||||
PDF_TO_IMAGE_SCALE_DESC:
|
||||
@@ -944,7 +1034,13 @@ export default {
|
||||
EMBED_TOEXCALIDRAW_DESC:
|
||||
"En la sección 'Incrustar archivos' de la Configuración de Excalidraw, puedes configurar cómo se incrustan varios tipos de archivos en Excalidraw. Esto incluye opciones para incrustar archivos Markdown interactivos, PDFs y archivos Markdown como imágenes.",
|
||||
MD_HEAD: "Incrustar Markdown en Excalidraw como imagen",
|
||||
MD_GROUP_DESC:
|
||||
"Configura las dimensiones, la fuente, los colores, los bordes y el CSS de los archivos Markdown renderizados como imágenes.",
|
||||
MD_EMBED_CUSTOMDATA_HEAD_NAME: "Archivos Markdown interactivos",
|
||||
MD_EMBED_CUSTOMDATA_GROUP_DESC:
|
||||
"Configura la edición y la apariencia predeterminada de futuras incrustaciones interactivas de Markdown.",
|
||||
MD_EMBED_DEFAULTS_CONTROL_NAME:
|
||||
"Valores predeterminados de apariencia de Markdown interactivo",
|
||||
MD_EMBED_CUSTOMDATA_HEAD_DESC: `Las siguientes configuraciones solo afectarán a futuras incrustaciones. Las incrustaciones actuales no se modificarán. La configuración del tema de los marcos incrustados se encuentra en la sección "Apariencia y comportamiento de Excalidraw`,
|
||||
MD_EMBED_SINGLECLICK_EDIT_NAME:
|
||||
"Un solo click para editar Markdown incrustado",
|
||||
@@ -990,19 +1086,30 @@ export default {
|
||||
EMBED_HEAD: "Incrustar Excalidraw en tus notas y exportar",
|
||||
EMBED_DESC: `En la configuración de "Incrustar y exportar", puedes configurar cómo se incrustan y exportan las imágenes y los bosquejos de Excalidraw en tus documentos. Las configuraciones clave incluyen elegir el tipo de imagen para la vista previa de Markdown (como SVG nativo o PNG), especificar el tipo de archivo a insertar en el documento (Excalidraw original, PNG o SVG) y gestionar el almacenamiento en caché de imágenes para incrustarlas en Markdown. También puedes controlar el tamaño de la imagen, si incrustar los bosquejos usando wikienlaces o enlaces Markdown y ajustar la configuración relacionada con los temas de imagen, colores de fondo y la integración de Obsidian.
|
||||
Además, hay configuraciones para la autoexportación, que genera automáticamente archivos SVG y/o PNG que coinciden con el título de tus bosquejos de Excalidraw, manteniéndolos sincronizados con los cambios de nombre y eliminaciones de archivos.`,
|
||||
EMBED_PREVIEW_LINKS_HEAD: "Vistas previas, enlaces y Canvas",
|
||||
EMBED_PREVIEW_LINKS_DESC:
|
||||
"Elige los formatos de vista previa y de archivo insertado, los enlaces de origen, los marcadores de posición y las incrustaciones inmersivas en Canvas.",
|
||||
EMBED_CANVAS: "Soporte para Obsidian Canvas",
|
||||
EMBED_CANVAS_NAME: "Incrustación inmersiva",
|
||||
EMBED_CANVAS_DESC:
|
||||
"Oculta el borde y el fondo del nodo del Canvas al incrustar un bosquejo de Excalidraw en un Canvas. " +
|
||||
"Ten en cuenta que para un fondo completamente transparente en tu imagen, aún necesitarás configurar Excalidraw para que exporte las imágenes con fondo transparente.",
|
||||
EMBED_CACHING: "Caché de imágenes y optimización de renderizado",
|
||||
EMBED_CACHING_DESC:
|
||||
"Ajusta la concurrencia de renderizado y las cachés locales, elimina imágenes o copias de seguridad almacenadas y reutiliza vistas previas exportadas.",
|
||||
RENDERING_CONCURRENCY_NAME: "Concurrencia de renderizado de imágenes",
|
||||
RENDERING_CONCURRENCY_DESC:
|
||||
"Número de parallel workers(trabajadores paralelos) a usar para el renderizado de imágenes. Aumentar este número acelerará el proceso de renderizado, pero puede ralentizar el resto del sistema. " +
|
||||
"El valor predeterminado es 3. Puedes aumentar este número si tienes un sistema potente.",
|
||||
EXPORT_SUBHEAD: "Configuraciones de Exportación",
|
||||
EXPORT_SUBHEAD_DESC:
|
||||
"Configura el renderizado de PDF, los datos de escena exportados, las dimensiones, el tema y fondo, los valores predeterminados de PDF y las copias PNG/SVG automáticas.",
|
||||
EMBED_SIZING: "Tamaño de imagen",
|
||||
EMBED_SIZING_DESC:
|
||||
"Define las dimensiones predeterminadas de las imágenes incrustadas, la escala PNG y el margen de exportación.",
|
||||
EMBED_THEME_BACKGROUND: "Tema de la imagen y color de fondo",
|
||||
EMBED_THEME_BACKGROUND_DESC:
|
||||
"Elige el fondo y el tema de las imágenes exportadas y si las vistas previas siguen el tema de Obsidian.",
|
||||
EMBED_IMAGE_CACHE_NAME:
|
||||
"Guardar imágenes en caché para incrustar en Markdown",
|
||||
EMBED_IMAGE_CACHE_DESC:
|
||||
@@ -1088,7 +1195,19 @@ export default {
|
||||
"Incrusta la escena de Excalidraw en la imagen exportada. Se puede anular a nivel de archivo añadiendo la clave frontmatter <code>excalidraw-export-embed-scene: true/false</code> . " +
|
||||
"La configuración solo surtirá efecto la próxima vez que (re)abras los bosquejos.",
|
||||
PDF_EXPORT_SETTINGS: "Configuración de exportación a PDF",
|
||||
PDF_EXPORT_SETTINGS_DESC:
|
||||
"Elige el tamaño de página, la orientación, la distribución, los márgenes, el color del papel y la alineación predeterminados del PDF.",
|
||||
PDF_EXPORT_DEFAULTS_CONTROL_NAME:
|
||||
"Diseño predeterminado de exportación a PDF",
|
||||
EXPORT_HEAD: "Configuración de auto-exportación",
|
||||
EXPORT_AUTOEXPORT_DESC:
|
||||
"Mantén sincronizados los archivos exportados y crea automáticamente variantes SVG, PNG, claras y oscuras.",
|
||||
SETTINGS_NAVIGATION_OPEN: "Abrir",
|
||||
SETTINGS_BREADCRUMB_ARIA: "Ruta de configuración",
|
||||
SETTINGS_RELATED_AUTOEXPORT_DESC:
|
||||
"Activa las copias automáticas PNG o SVG para que esos formatos estén disponibles en el menú del tipo de archivo insertado.",
|
||||
SETTINGS_RELATED_EMBED_TYPE_DESC:
|
||||
"Elige si se inserta Excalidraw, PNG o SVG al incrustar un bosquejo en un documento.",
|
||||
EXPORT_SYNC_NAME:
|
||||
"Mantiene los nombres de archivo .SVG y/o .PNG sincronizados con el archivo del bosquejo",
|
||||
EXPORT_SYNC_DESC:
|
||||
@@ -1164,8 +1283,11 @@ export default {
|
||||
CUSTOM_PEN_DESC:
|
||||
"Verás estos lápices junto al Menú de Obsidian en el lienzo. Puedes personalizarlos manteniendo presionado el botón del lápiz en el lienzo.",
|
||||
EXPERIMENTAL_HEAD: "Funcionalidades misceláneas",
|
||||
EXPERIMENTAL_DESC: `Estas funcionalidades misceláneas en Excalidraw incluyen opciones para establecer fórmulas LaTeX predeterminadas para nuevas ecuaciones, habilitar un sugeridor de campos para autocompletar, mostrar indicadores de tipo para archivos de Excalidraw, habilitar la incrustación de imágenes inmersivas en el modo de edición de vista en vivo y experimentar con el Reconocimiento Óptico de Caracteres (OCR) de Taskbone para la extracción de texto de imágenes y bosquejos. Los usuarios también pueden ingresar una clave de API de Taskbone para un uso extendido del servicio de OCR.`,
|
||||
EXPERIMENTAL_DESC:
|
||||
"Configura los valores predeterminados de LaTeX, los indicadores de tipo de archivo, el comportamiento de la vista previa en vivo, las sugerencias de propiedades y la integración experimental de OCR con Taskbone.",
|
||||
EA_HEAD: "Excalidraw Automate",
|
||||
EA_GROUP_DESC:
|
||||
"Configura los scripts de Excalidraw Automate, el comportamiento de inicio y autoarranque, los enlaces de comandos y los ajustes expuestos por los scripts instalados.",
|
||||
EA_DESC:
|
||||
"ExcalidrawAutomate es una API de scripting y automatización para Excalidraw. Desafortunadamente, la documentación de la API es escasa. " +
|
||||
`Te recomiendo leer el archivo <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_API_EXCALIDRAWAUTOMATE_D_TS}">ExcalidrawAutomate.d.ts</a>, ` +
|
||||
@@ -1176,6 +1298,34 @@ export default {
|
||||
FIELD_SUGGESTER_DESC:
|
||||
"El sugeridor de campos, tomado de los complementos Breadcrumbs y Templater, mostrará un menú de autocompletar " +
|
||||
"cuando escribas <code>excalidraw-</code> o <code>ea.</code> , con descripciones de las funciones como pistas para cada elemento en la lista.",
|
||||
ALLOW_JS_FILES_NAME: "Cargar archivos JavaScript desde la carpeta Scripts",
|
||||
ALLOW_JS_FILES_DESC:
|
||||
"Cuando está activado, Excalidraw Automate supervisa y ejecuta archivos <code>.js</code> en la carpeta Scripts y acepta un script de inicio <code>.js</code>. " +
|
||||
"De forma predeterminada, Obsidian Sync no sincroniza archivos que no sean Markdown, Obsidian no abre archivos <code>.js</code> para editarlos y el Explorador de archivos los oculta. Activa <b>Sincronizar todos los demás tipos</b> y <b>Mostrar todos los tipos de archivo</b> en Obsidian cuando sea necesario. Si existen scripts <code>.md</code> y <code>.js</code> con el mismo nombre, se utiliza el archivo Markdown.",
|
||||
STORE_SCRIPTS_AS_JS_NAME: "Guardar los scripts descargados como",
|
||||
STORE_SCRIPTS_AS_JS_DESC:
|
||||
"Elige el tipo de archivo local para las nuevas descargas y actualizaciones de la Biblioteca de scripts. Es independiente de si la fuente remota es <code>.md</code> o <code>.js</code>.",
|
||||
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
|
||||
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
|
||||
MIGRATE_SCRIPT_FILES_NAME: "Mover archivos de script existentes",
|
||||
MIGRATE_SCRIPTS_TO_JS_BUTTON: "Mover scripts existentes a .js",
|
||||
MIGRATE_SCRIPTS_TO_MD_BUTTON: "Mover scripts existentes a .md",
|
||||
MIGRATE_SCRIPT_FILES_STATUS:
|
||||
"Se pueden mover {eligible} archivo(s) de script a {extension}. {skipped}",
|
||||
MIGRATE_SCRIPT_FILES_CONFIRM:
|
||||
"Haz una copia de seguridad de tu bóveda antes de continuar.<br><br>Se cambiará la extensión de <b>{count}</b> archivo(s) de script a <code>{extension}</code>. Se actualizarán las rutas de los scripts fijados. {startup} {skipped}",
|
||||
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
|
||||
"También se actualizarán el script de inicio configurado y su ajuste.",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED:
|
||||
"No se moverán {count} par(es) .md/.js con el mismo nombre.",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
|
||||
"Se omitieron {count} archivo(s) de script porque el destino ya existe:\n{files}",
|
||||
MIGRATE_SCRIPT_FILES_NONE:
|
||||
"No se encontraron archivos de script aptos para mover.",
|
||||
MIGRATE_SCRIPT_FILES_COMPLETE:
|
||||
"Se movieron {count} archivo(s) de script a {extension}.",
|
||||
MIGRATE_SCRIPT_FILES_FAILED:
|
||||
"No se pudieron mover los archivos de script. Los cambios completados se revirtieron cuando fue posible.",
|
||||
ENABLE_ONLOAD_SCRIPTS_NAME: "Habilitar scripts de carga",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
|
||||
"Este archivo incluye un <code>excalidraw-onload-script</code>. ¿Quieres habilitar los scripts de carga?",
|
||||
@@ -1185,6 +1335,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 → Excalidraw Automate → 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?",
|
||||
@@ -1195,9 +1359,10 @@ export default {
|
||||
"Esto crea un riesgo si abres dibujos de fuentes desconocidas: un dibujo malicioso puede hacer que un clic normal ejecute comandos privilegiados. " +
|
||||
"Actívalo solo si confías en el archivo y en su origen.",
|
||||
STARTUP_SCRIPT_NAME: "Script de inicio",
|
||||
STARTUP_SCRIPT_JS_DISABLED:
|
||||
"Los scripts de inicio JavaScript están desactivados. Primero habilita los archivos JavaScript en la configuración de Excalidraw Automate.",
|
||||
STARTUP_SCRIPT_DESC:
|
||||
"Si está configurado, Excalidraw ejecutará el script al iniciar el complemento. Esto es útil si quieres establecer cualquiera de los hooks de Excalidraw Automate. El script de inicio es un archivo Markdown " +
|
||||
"que debe contener el código Javascript que quieres ejecutar cuando Excalidraw se inicie",
|
||||
"Si está configurado, Excalidraw ejecutará el script al iniciar el complemento. Es útil para configurar hooks de Excalidraw Automate. Las rutas sin extensión utilizan un archivo Markdown; los archivos <code>.js</code> se aceptan cuando está habilitada la carga de archivos JavaScript.",
|
||||
STARTUP_SCRIPT_BUTTON_CREATE: "Crear script de inicio",
|
||||
STARTUP_SCRIPT_BUTTON_OPEN: "Abrir script de inicio",
|
||||
FILETYPE_NAME:
|
||||
@@ -1244,6 +1409,8 @@ export default {
|
||||
"Otros formatos de fuente incrustarán la fuente completa en el archivo exportado, lo que podría resultar en tamaños de archivo significativamente mayores.",
|
||||
OFFLINE_CJK_NAME:
|
||||
"Soporte de fuentes CJK (chino, japonés y coreano) sin conexión",
|
||||
OFFLINE_CJK_GROUP_DESC:
|
||||
"Descarga y precarga de forma selectiva fuentes chinas, japonesas y coreanas para que Excalidraw pueda mostrarlas sin conexión a internet.",
|
||||
OFFLINE_CJK_DESC: `<strong>Los cambios que hagas aquí solo se aplicarán después de reiniciar Obsidian.</strong><br>
|
||||
Excalidraw.com ofrece fuentes CJK (chino, japonés, coreano) escritas a mano. Por defecto, estas fuentes no se incluyen en el complemento de forma local, sino que se obtienen de internet.
|
||||
Si prefieres que Excalidraw funcione completamente sin conexión a internet, puedes descargar los <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RAW_REFS_HEADS_MASTER_ASSETS_EXCALIDRAW_FONTS_ZIP}" target="_blank">archivos de fuentes necesarios desde GitHub</a>.
|
||||
@@ -1262,6 +1429,8 @@ export default {
|
||||
SCRIPT_SETTINGS_DESC:
|
||||
"Algunos de los scripts de Excalidraw Automate incluyen configuraciones. Las configuraciones están organizadas por script. Solo se harán visibles en esta lista después de que hayas ejecutado el script recién descargado al menos una vez.",
|
||||
TASKBONE_HEAD: "Reconocimiento Óptico de Caracteres de Taskbone",
|
||||
TASKBONE_GROUP_DESC:
|
||||
"Configura el servicio opcional de OCR en línea Taskbone para extraer texto que se pueda buscar de dibujos e imágenes.",
|
||||
TASKBONE_DESC:
|
||||
"Esta es una integración experimental del reconocimiento óptico de caracteres en Excalidraw. Ten en cuenta que Taskbone es un servicio externo independiente y no es proporcionado por Excalidraw ni por el proyecto del complemento Excalidraw-Obsidian. " +
|
||||
"El servicio de OCR capturará texto legible de las líneas de dibujo a mano alzada y de las imágenes incrustadas en tu lienzo y colocará el texto reconocido en el frontmatter de tu bosquejo, así como en el portapapeles. " +
|
||||
@@ -1429,6 +1598,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 +1626,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 +1835,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.",
|
||||
};
|
||||
+201
-3
@@ -15,6 +15,21 @@ import {
|
||||
// русский
|
||||
export default {
|
||||
// main.ts
|
||||
SETTINGS_DATA_INVALID:
|
||||
"Excalidraw ожидает корректный файл data.json. Изменения настроек не будут сохранены, пока файл не будет восстановлен или вы не перезапустите Obsidian и не выберете сброс настроек.",
|
||||
SETTINGS_DATA_REPAIRED_FROM_MEMORY:
|
||||
"Получен пустой или нечитаемый файл настроек Excalidraw, поэтому он был отклонён. Активные настройки записаны обратно для восстановления data.json.",
|
||||
SETTINGS_DATA_RECOVERED:
|
||||
"Файл Excalidraw data.json был пуст или недоступен для чтения. Последняя исправная версия настроек восстановлена автоматически.",
|
||||
SETTINGS_RECOVERY_MISSING_TITLE: "Файл настроек Excalidraw отсутствует",
|
||||
SETTINGS_RECOVERY_MISSING_DESC:
|
||||
"На этом устройстве есть последняя исправная резервная копия настроек. Восстановите её или сбросьте Excalidraw к заводским настройкам. При закрытии этого сообщения будет восстановлена резервная копия.",
|
||||
SETTINGS_RECOVERY_CORRUPT_TITLE: "Файл настроек Excalidraw повреждён",
|
||||
SETTINGS_RECOVERY_CORRUPT_DESC:
|
||||
"Файл пуст или недоступен для чтения, а резервная копия на этом устройстве отсутствует. Сбросьте Excalidraw к заводским настройкам или оставьте файл без изменений, пока восстанавливаете корректный data.json из другого источника. При закрытии этого сообщения Excalidraw будет ждать замену файла.",
|
||||
SETTINGS_RECOVERY_RESTORE_BACKUP: "Восстановить копию",
|
||||
SETTINGS_RECOVERY_RESET_DEFAULTS: "Сбросить настройки",
|
||||
SETTINGS_RECOVERY_WAIT_FOR_FILE: "Ждать восстановленный файл",
|
||||
CONVERT_URL_TO_FILE: "Сохранить изображение из URL в локальный файл",
|
||||
UNZIP_CURRENT_FILE: "Распаковать текущий файл Excalidraw",
|
||||
PUBLISH_SVG_CHECK:
|
||||
@@ -352,6 +367,18 @@ export default {
|
||||
"Для повышения производительности рассмотрите возможность разделения больших рисунков на несколько файлов меньшего размера.",
|
||||
|
||||
//settings.ts
|
||||
SETTINGS_TOOLBAR_COPY: "Копировать настройки",
|
||||
SETTINGS_TOOLBAR_NOTEBOOKLM: "NotebookLM",
|
||||
SETTINGS_TOOLBAR_BUGS: "Ошибки",
|
||||
SETTINGS_TOOLBAR_WIKI: "Вики",
|
||||
SETTINGS_TOOLBAR_YOUTUBE: "YouTube",
|
||||
SETTINGS_TOOLBAR_LEARN: "Обучение",
|
||||
SETTINGS_TOOLBAR_FOLLOW: "Twitter",
|
||||
SETTINGS_TOOLBAR_READ: "Читать книгу",
|
||||
SETTINGS_TOOLBAR_KOFI: "Ko-fi",
|
||||
USE_DECLARATIVE_SETTINGS_NAME: "Использовать настройки с поиском",
|
||||
USE_DECLARATIVE_SETTINGS_DESC:
|
||||
"Использовать многостраничный интерфейс настроек Obsidian с поиском. Отключите, чтобы использовать прежнюю одностраничную страницу настроек Excalidraw. Требуется перезапуск Obsidian.",
|
||||
RELEASE_NOTES_NAME: "Отображение информации о выпуске после обновления",
|
||||
RELEASE_NOTES_DESC:
|
||||
`<b><u>Переключатель ВКЛ:</u></b> Отображение информации о выпуске при каждом обновлении Excalidraw до новой версии.<br>` +
|
||||
@@ -366,6 +393,15 @@ export default {
|
||||
"<b><u>Переключатель ВЫКЛ:</u></b> Тихий режим. Вам необходимо проверить обновления плагинов в разделе Community Plugins.",
|
||||
|
||||
BASIC_HEAD: "Основные",
|
||||
BASIC_UPDATES_STARTUP_HEAD: "Обновления и запуск",
|
||||
BASIC_UPDATES_STARTUP_DESC:
|
||||
"Примечания к выпуску, проверка и уведомления об обновлениях, а также заставка при запуске.",
|
||||
BASIC_FILES_FOLDERS_HEAD: "Файлы и папки",
|
||||
BASIC_FILES_FOLDERS_DESC:
|
||||
"Папки и пути по умолчанию для рисунков, обрезок, аннотаций, шаблонов и скриптов Excalidraw Automate.",
|
||||
BASIC_STENCIL_LIBRARY_HEAD: "Библиотека элементов",
|
||||
BASIC_STENCIL_LIBRARY_DESC:
|
||||
"Выберите место хранения библиотеки элементов и настройте её папку в хранилище и локальный файл.",
|
||||
BASIC_DESC: `В настройках "Основные" можно настроить такие параметры, как отображение заметок о выпуске после обновлений, получение уведомлений об обновлении плагинов, установка местоположения по умолчанию для новых чертежей, указание папки Excalidraw для вставки чертежей в активные документы, определение файла шаблона Excalidraw и указание папки сценария Excalidraw Automate для управления сценариями автоматизации.`,
|
||||
FOLDER_NAME: "Папка Excalidraw",
|
||||
FOLDER_DESC:
|
||||
@@ -564,6 +600,9 @@ export default {
|
||||
AI_USAGE_SETTINGS_BUTTON_DESC:
|
||||
"Просмотр потребления токенов ИИ в текущей сессии Obsidian с разбивкой по моделям. Данные сбрасываются при перезапуске.",
|
||||
SAVING_HEAD: "Сохранение",
|
||||
SAVING_STORAGE_AUTOSAVE_HEAD: "Хранение и автосохранение",
|
||||
SAVING_STORAGE_AUTOSAVE_DESC:
|
||||
"Настройте сжатие JSON рисунков и интервалы автосохранения на компьютере и мобильных устройствах.",
|
||||
SAVING_DESC:
|
||||
"В разделе 'Сохранение' раздела Настройки Excalidraw вы можете настроить способ сохранения ваших чертежей. Сюда входят опции сжатия Excalidraw JSON в Markdown, установки интервалов автосохранения для настольных и мобильных компьютеров, определения форматов имен файлов, а также выбора расширения файла .excalidraw.md или .md. ",
|
||||
COMPRESS_NAME: "Сжатие Excalidraw JSON в формате Markdown",
|
||||
@@ -599,6 +638,8 @@ export default {
|
||||
"Excalidraw не сможет сохранить вашу работу при прямом завершении работы Obsidian (т.е. смахнув ее). Также обратите внимание, что при переключении приложений на мобильном устройстве, иногда Android и iOS закрываются " +
|
||||
"Obsidian в фоновом режиме для экономии системных ресурсов. В этом случае Excalidraw не сможет сохранить последние изменения.",
|
||||
FILENAME_HEAD: "Имя файла",
|
||||
FILENAME_GROUP_DESC:
|
||||
"Настройте создание имён новых, встроенных, обрезанных и аннотированных рисунков.",
|
||||
FILENAME_DESC:
|
||||
`<p>Нажмите на эту ссылку, чтобы получить <a href="${URLs.MOMENTJS_COM_DOCS}">` +
|
||||
`справочник по формату даты и времени</a>.</p>`,
|
||||
@@ -626,6 +667,9 @@ export default {
|
||||
DISPLAY_HEAD: "Внешний вид и поведение Excalidraw",
|
||||
DISPLAY_DESC:
|
||||
"В разделе 'Внешний вид и поведение' раздела Настройки Excalidraw вы можете настроить внешний вид и поведение Excalidraw. Сюда входят опции динамической стилизации, режима для левой руки, соответствия тем Excalidraw и Obsidian, режимов по умолчанию и многое другое.",
|
||||
DISPLAY_EDITOR_PREVIEWS_HEAD: "Редактирование и предпросмотр",
|
||||
DISPLAY_EDITOR_PREVIEWS_DESC:
|
||||
"Настройте жесты редактирования холста и отображение файлов Excalidraw в режиме чтения и предпросмотре при наведении.",
|
||||
DYNAMICSTYLE_NAME: "Динамическая стилизация",
|
||||
DYNAMICSTYLE_DESC:
|
||||
"Изменение цветов пользовательского интерфейса Excalidraw в соответствии с цветом холста",
|
||||
@@ -688,13 +732,23 @@ export default {
|
||||
"<li>Если <b>заблокировать</b>, то в PDF будет отображаться разметка документа.</li></ul>" +
|
||||
`См. другие связанные настройки для <a href='#${TAG_MDREADINGMODE}'>режима чтения разметки</a> в разделе 'Внешний вид и поведение' выше.<br>` +
|
||||
"⚠️ Обратите внимание, что необходимо закрыть активный файл excalidraw/markdown и открыть его снова, чтобы изменения вступили в силу. ⚠️",
|
||||
MODES_HEAD: "Режимы интерфейса",
|
||||
MODES_DESC:
|
||||
"Выберите интерфейс Excalidraw для каждого устройства, кнопки заголовка и расположение панели для правой или левой руки.",
|
||||
HOTKEY_OVERRIDE_HEAD: "Переопределение горячих клавиш",
|
||||
HOTKEY_OVERRIDE_GROUP_DESC:
|
||||
"Управляйте сочетаниями Excalidraw, которые должны иметь приоритет над конфликтующими горячими клавишами Obsidian.",
|
||||
HOTKEY_OVERRIDE_CONTROL_NAME: "Управление переопределениями клавиш",
|
||||
HOTKEY_OVERRIDE_DESC:
|
||||
`Некоторые горячие клавиши Excalidraw, такие как <code>${labelCTRL()}+Enter</code> для редактирования текста или <code>${labelCTRL()}+K</code> создания ссылки на элемент ` +
|
||||
"конфликтуют с настройками горячих клавиш Obsidian. Комбинации горячих клавиш, которые вы добавите ниже, отменят настройки горячих клавиш Obsidian при использовании Excalidraw, таким образом " +
|
||||
`Вы можете добавить <code>${labelCTRL()}+G</code>, если хотите по умолчанию перейти к Группе Объектов в Excalidraw вместо открытия Режима просмотра Графиков.`,
|
||||
THEME_HEAD: "Тема и стиль",
|
||||
THEME_DESC:
|
||||
"Настройте стиль интерфейса, темы рисунков и вставок, режим открытия и безопасные отступы на мобильных устройствах.",
|
||||
ZOOM_AND_PAN_HEAD: "Масштаб и панорамирование",
|
||||
ZOOM_AND_PAN_DESC:
|
||||
"Настройте поведение мыши, сенсорного ввода, открытия, изменения размера и диапазона масштаба.",
|
||||
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME:
|
||||
"Перемещение холста правой кнопкой мыши (открыть меню с 'm')",
|
||||
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
|
||||
@@ -719,7 +773,12 @@ export default {
|
||||
"Увеличение до максимального уровня масштабирования",
|
||||
ZOOM_TO_FIT_MAX_LEVEL_DESC:
|
||||
"Установите максимальный уровень, до которого масштабирование будет увеличивать чертеж. Минимальное значение - 0,5 (50 %), максимальное - 10 (1000 %).",
|
||||
PEN_HEAD: "Перо",
|
||||
PEN_DESC:
|
||||
"Настройте автоматический режим пера, сенсорные жесты, ластик и перекрестие свободного рисования.",
|
||||
GRID_HEAD: "Сетка",
|
||||
GRID_DESC:
|
||||
"Настройте направление сетки, автоматический или пользовательский цвет и прозрачность.",
|
||||
GRID_DYNAMIC_COLOR_NAME: "Динамический цвет сетки",
|
||||
GRID_DYNAMIC_COLOR_DESC:
|
||||
"<b><u>Переключатель ВКЛ:</u></b>Измените цвет сетки, чтобы он соответствовал цвету холста<br><b><u>Переключатель ВЫКЛ:</u></b>Используйте цвет, указанный ниже, в качестве цвета сетки",
|
||||
@@ -729,6 +788,8 @@ export default {
|
||||
"Прозрачность сетки также будет управлять прозрачностью поля привязки при привязке стрелки к элементу.<br>" +
|
||||
"Установите прозрачность сетки. 0 - прозрачная, 100 - непрозрачная.",
|
||||
LASER_HEAD: "Лазерный указатель",
|
||||
LASER_DESC:
|
||||
"Настройте цвет лазерного указателя, скорость и длину затухания его следа.",
|
||||
LASER_COLOR: "Цвет лазерного указателя",
|
||||
LASER_DECAY_TIME_NAME: "Время затухания лазерного указателя",
|
||||
LASER_DECAY_TIME_DESC:
|
||||
@@ -748,6 +809,21 @@ export default {
|
||||
"Когда файлы Obsidian изменяются, соответствующие <code>[[link]]</code> в ваших чертежах также изменится. " +
|
||||
"Если вы не хотите, чтобы текст случайно менялся в ваших чертежах, используйте <code>[[links|with aliases]]</code>.",
|
||||
DRAG_MODIFIER_NAME: "Щелкните ссылку и перетащите клавиши-модификаторы",
|
||||
DRAG_MODIFIER_GROUP_DESC:
|
||||
"Настройте жесты открытия ссылок и платформенные сочетания модификаторов для щелчков и перетаскивания.",
|
||||
LINK_OPENING_GESTURES_HEAD: "Жесты открытия ссылок",
|
||||
LINK_OPENING_GESTURES_DESC:
|
||||
"Настройте задержку долгого нажатия и открытие ссылок двойным щелчком во встроенных рисунках и режиме просмотра.",
|
||||
WEB_BROWSER_DRAG_ACTION_DESC:
|
||||
"Выберите модификаторы для ссылок, изображений, импорта и вставок, перетаскиваемых из веб-браузера.",
|
||||
LOCAL_FILE_DRAG_ACTION_DESC:
|
||||
"Выберите модификаторы для ссылок, изображений, импорта и вставок, перетаскиваемых из операционной системы.",
|
||||
INTERNAL_DRAG_ACTION_DESC:
|
||||
"Выберите модификаторы для ссылок, изображений, полноразмерных изображений и вставок внутри Obsidian.",
|
||||
PANE_TARGET_DESC:
|
||||
"Выберите сочетания модификаторов, определяющие место открытия ссылок.",
|
||||
MODIFIER_KEY_USAGE_NAME: "Настройка клавиш-модификаторов",
|
||||
MODIFIER_KEY_COMBINATIONS: "Сочетания модификаторов",
|
||||
DRAG_MODIFIER_DESC:
|
||||
`Поведение клавиши-модификатора при нажатии на ссылки и перетаскивании элементов. ` +
|
||||
`Excalidraw не будет проверять вашу конфигурацию... обратите внимание, чтобы избежать конфликтов настроек. ` +
|
||||
@@ -844,6 +920,22 @@ export default {
|
||||
"Используйте <code>http" +
|
||||
"s://noembed" +
|
||||
".com/embed?url=</code> для получения заголовка страницы при переходе по HTTPS-ссылке в Excalidraw",
|
||||
LINK_BEHAVIOR_HEAD: "Поведение ссылок",
|
||||
LINK_BEHAVIOR_DESC:
|
||||
"Настройте синхронизацию ссылок, связанные ссылки, предпросмотр, щелчки и получение заголовков веб-страниц.",
|
||||
LINK_USAGE_NAME: "Использование ссылок в Excalidraw",
|
||||
LINK_OPENING_HEAD: "Поведение панелей и вкладок",
|
||||
LINK_OPENING_DESC:
|
||||
"Выберите, будут ли ссылки повторно использовать, фокусировать или переключать панели, вкладки и главное рабочее пространство.",
|
||||
LINK_APPEARANCE_HEAD: "Внешний вид ссылок",
|
||||
LINK_APPEARANCE_DESC:
|
||||
"Настройте скобки, префиксы, значки и прозрачность отображаемых ссылок.",
|
||||
TODO_HEAD: "Задачи TODO",
|
||||
TODO_GROUP_DESC:
|
||||
"Настройте распознавание TODO и значки открытых и завершенных задач.",
|
||||
TRANSCLUSION_HEAD: "Текстовые включения",
|
||||
TRANSCLUSION_DESC:
|
||||
"Настройте ограничения символов, перенос строк и очистку цитат для включенного текста Markdown.",
|
||||
PDF_TO_IMAGE: "PDF в изображение",
|
||||
PDF_TO_IMAGE_SCALE_NAME: "Шкала преобразования PDF в изображения",
|
||||
PDF_TO_IMAGE_SCALE_DESC:
|
||||
@@ -853,7 +945,13 @@ export default {
|
||||
EMBED_TOEXCALIDRAW_DESC:
|
||||
"В разделе Встраивание файлов раздела Настройки Excalidraw вы можете настроить, как различные файлы будут встраиваться в Excalidraw. Сюда входят опции для встраивания интерактивных файлов разметки (Markdown), PDF-файлов и файлов разметки (Markdown) в виде изображений.",
|
||||
MD_HEAD: "Встраивать разметку в Excalidraw в виде изображения",
|
||||
MD_GROUP_DESC:
|
||||
"Настройте размеры, шрифт, цвета, границы и CSS для файлов Markdown, отображаемых как изображения.",
|
||||
MD_EMBED_CUSTOMDATA_HEAD_NAME: "Интерактивные файлы Markdown",
|
||||
MD_EMBED_CUSTOMDATA_GROUP_DESC:
|
||||
"Настройте редактирование и внешний вид по умолчанию для будущих интерактивных вставок Markdown.",
|
||||
MD_EMBED_DEFAULTS_CONTROL_NAME:
|
||||
"Внешний вид интерактивного Markdown по умолчанию",
|
||||
MD_EMBED_CUSTOMDATA_HEAD_DESC: `Приведенные ниже настройки будут влиять только на будущие вставки. Текущие вставки остаются неизменными. Настройки темы для встроенных фреймов находятся в разделе "Внешний вид и поведение Excalidraw".`,
|
||||
MD_EMBED_SINGLECLICK_EDIT_NAME:
|
||||
"Редактирование встроенной разметки (Markdown) одним щелчком мыши",
|
||||
@@ -899,12 +997,17 @@ export default {
|
||||
EMBED_HEAD: "Встраивание Excalidraw в заметки и экспорт",
|
||||
EMBED_DESC: `В настройках "Вставка и экспорт" можно настроить вставку и экспорт изображений и рисунков Excalidraw в документы. Основные настройки включают выбор типа изображения для предварительного просмотра в формате разметки (например, Native SVG или PNG), указание типа файла для вставки в документ (оригинальный Excalidraw, PNG или SVG) и управление кэшированием изображений для вставки в разметку. Вы также можете управлять размерами изображений, вставлять рисунки с помощью ссылок на вики или ссылок на разметку, а также настраивать темы изображений, цвета фона и интеграцию с Obsidian.
|
||||
Кроме того, есть настройки автоэкспорта, который автоматически генерирует файлы SVG и/или PNG, соответствующие названию ваших рисунков Excalidraw, сохраняя их синхронизацию при переименовании и удалении файлов.`,
|
||||
EMBED_PREVIEW_LINKS_HEAD: "Предпросмотр, ссылки и Canvas",
|
||||
EMBED_PREVIEW_LINKS_DESC:
|
||||
"Выберите форматы предпросмотра и вставляемых файлов, поведение исходных ссылок, заполнители и иммерсивные вставки Canvas.",
|
||||
EMBED_CANVAS: "Поддержка Obsidian Canvas",
|
||||
EMBED_CANVAS_NAME: "Иммерсивное встраивание",
|
||||
EMBED_CANVAS_DESC:
|
||||
"Скрывайте границы и фон узлов холста при встраивании чертежа Excalidraw в холст. " +
|
||||
"Обратите внимание, что для создания полностью прозрачного фона изображения вам все равно придется настроить Excalidraw на экспорт изображений с прозрачным фоном.",
|
||||
EMBED_CACHING: "Кэширование изображений",
|
||||
EMBED_CACHING_DESC:
|
||||
"Настройте параллельный рендеринг и локальные кэши, очищайте изображения или резервные копии и повторно используйте экспортированные предпросмотры.",
|
||||
IMAGE_CACHE_RETENTION_DAYS_NAME: "Срок хранения локального кэша изображений",
|
||||
IMAGE_CACHE_RETENTION_DAYS_DESC:
|
||||
"Определяет, сколько дней Excalidraw должен хранить локально закэшированные отрендеренные ресурсы, такие как вложенные изображения Excalidraw и страницы PDF, прежде чем неиспользуемые записи кэша будут удалены. " +
|
||||
@@ -913,8 +1016,14 @@ export default {
|
||||
"Практически это влияет только на локальное использование диска или браузерного хранилища внутри Obsidian. Это может быть особенно заметно на телефонах и на настольных системах с более жёсткими лимитами браузерного хранилища или ограниченным свободным местом на диске.<br><br>" +
|
||||
"Меньшие значения быстрее освобождают локальное место, но могут приводить к более частому повторному рендерингу PDF и встроенных рисунков. Большие значения ускоряют повторные загрузки ценой большего локального кэша.",
|
||||
EXPORT_SUBHEAD: "Настройки экспорта",
|
||||
EXPORT_SUBHEAD_DESC:
|
||||
"Настройте рендеринг PDF, данные экспортируемой сцены, размеры, тему и фон, параметры PDF по умолчанию и автоматические копии PNG/SVG.",
|
||||
EMBED_SIZING: "Размер изображения",
|
||||
EMBED_SIZING_DESC:
|
||||
"Задайте размеры встроенных изображений по умолчанию, масштаб PNG и отступ экспорта.",
|
||||
EMBED_THEME_BACKGROUND: "Тема изображения и цвет фона",
|
||||
EMBED_THEME_BACKGROUND_DESC:
|
||||
"Выберите фон и тему экспортируемых изображений, а также следование предпросмотра теме Obsidian.",
|
||||
EMBED_IMAGE_CACHE_NAME: "Кэширование изображений для вставки в markdown",
|
||||
EMBED_IMAGE_CACHE_DESC:
|
||||
"Кэшируйте изображения для вставки в markdown. Это ускорит процесс встраивания, но в случае, если вы составите изображения из нескольких чертежей-субкомпонентов, " +
|
||||
@@ -996,7 +1105,19 @@ export default {
|
||||
EXPORT_EMBED_SCENE_DESC:
|
||||
"Вставка сцены Excalidraw в экспортируемое изображение. Можно переопределить на уровне файла, добавив ключ frontmatter. <code>excalidraw-export-embed-scene: true/false</code>. " +
|
||||
"Настройка вступит в силу только при следующем (повторном) открытии чертежей.",
|
||||
PDF_EXPORT_SETTINGS: "Настройки экспорта PDF",
|
||||
PDF_EXPORT_SETTINGS_DESC:
|
||||
"Выберите размер страницы PDF, ориентацию, разбиение, поля, цвет бумаги и выравнивание по умолчанию.",
|
||||
PDF_EXPORT_DEFAULTS_CONTROL_NAME: "Макет экспорта PDF по умолчанию",
|
||||
EXPORT_HEAD: "Настройки автоэкспорта",
|
||||
EXPORT_AUTOEXPORT_DESC:
|
||||
"Синхронизируйте экспортированные файлы и автоматически создавайте варианты SVG, PNG, для светлой и тёмной темы.",
|
||||
SETTINGS_NAVIGATION_OPEN: "Открыть",
|
||||
SETTINGS_BREADCRUMB_ARIA: "Путь настроек",
|
||||
SETTINGS_RELATED_AUTOEXPORT_DESC:
|
||||
"Включите автоматические копии PNG или SVG, чтобы эти форматы стали доступны в списке типа вставляемого файла.",
|
||||
SETTINGS_RELATED_EMBED_TYPE_DESC:
|
||||
"Выберите, что вставлять в документ при встраивании рисунка: Excalidraw, PNG или SVG.",
|
||||
EXPORT_SYNC_NAME:
|
||||
"Поддерживайте синхронизацию имен файлов .SVG и/или .PNG с файлом чертежа",
|
||||
EXPORT_SYNC_DESC:
|
||||
@@ -1069,8 +1190,11 @@ export default {
|
||||
CUSTOM_PEN_DESC:
|
||||
"Вы увидите эти ручки рядом с меню Obsidian на холсте. Вы можете настроить ручки на холсте, долго нажимая на кнопку ручки.",
|
||||
EXPERIMENTAL_HEAD: "Разные возможности",
|
||||
EXPERIMENTAL_DESC: `Среди прочих возможностей Excalidraw - установка формул LaTeX по умолчанию для новых уравнений, включение Предложение полей (Suggester) для автозаполнения, отображение индикаторов типов файлов Excalidraw, включение иммерсивного встраивания изображений в режиме предварительного просмотра и эксперименты с оптическим распознаванием символов Taskbone для извлечения текста из изображений и чертежей. Пользователи также могут ввести API-ключ Taskbone для расширенного использования сервиса OCR.`,
|
||||
EXPERIMENTAL_DESC:
|
||||
"Настройте значения LaTeX по умолчанию, индикаторы типов файлов, режим живого предварительного просмотра, подсказки свойств и экспериментальную интеграцию OCR Taskbone.",
|
||||
EA_HEAD: "Автоматизация Excalidraw",
|
||||
EA_GROUP_DESC:
|
||||
"Настройте сценарии Excalidraw Automate, запуск и автозапуск, командные ссылки и параметры, предоставляемые установленными сценариями.",
|
||||
EA_DESC:
|
||||
"Excalidraw Автоматизация - это скриптовый и автоматизированный API для Excalidraw. К сожалению, документация по API скудна. " +
|
||||
`Рекомендую прочитать <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_API_EXCALIDRAWAUTOMATE_D_TS}">ExcalidrawAutomate.d.ts</a> файл, ` +
|
||||
@@ -1081,6 +1205,34 @@ export default {
|
||||
FIELD_SUGGESTER_DESC:
|
||||
"Предложение полей (Suggester) позаимствован у плагинов Breadcrumbs и Templater. Предложение полей (Suggester) полей будет показывать " +
|
||||
"меню автозаполнения при вводе текста с описанием функций <code>excalidraw-</code> или <code>ea.</code> в качестве подсказок для отдельных элементов в списке.",
|
||||
ALLOW_JS_FILES_NAME: "Загружать файлы JavaScript из папки скриптов",
|
||||
ALLOW_JS_FILES_DESC:
|
||||
"Если включено, Excalidraw Automate отслеживает и запускает файлы <code>.js</code> в папке скриптов и принимает скрипт запуска <code>.js</code>. " +
|
||||
"По умолчанию Obsidian Sync не синхронизирует файлы, отличные от Markdown, Obsidian не открывает файлы <code>.js</code> для редактирования, а проводник файлов скрывает их. При необходимости включите <b>Синхронизировать все остальные типы</b> и <b>Показывать все типы файлов</b> в Obsidian. Если существуют одноимённые скрипты <code>.md</code> и <code>.js</code>, используется файл Markdown.",
|
||||
STORE_SCRIPTS_AS_JS_NAME: "Хранить загруженные скрипты как",
|
||||
STORE_SCRIPTS_AS_JS_DESC:
|
||||
"Выберите локальный тип файла для новых загрузок и обновлений из библиотеки скриптов. Он не зависит от того, имеет ли удалённый источник расширение <code>.md</code> или <code>.js</code>.",
|
||||
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
|
||||
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
|
||||
MIGRATE_SCRIPT_FILES_NAME: "Переместить существующие файлы скриптов",
|
||||
MIGRATE_SCRIPTS_TO_JS_BUTTON: "Переместить существующие скрипты в .js",
|
||||
MIGRATE_SCRIPTS_TO_MD_BUTTON: "Переместить существующие скрипты в .md",
|
||||
MIGRATE_SCRIPT_FILES_STATUS:
|
||||
"Можно переместить файлов скриптов в {extension}: {eligible}. {skipped}",
|
||||
MIGRATE_SCRIPT_FILES_CONFIRM:
|
||||
"Перед продолжением создайте резервную копию хранилища.<br><br><b>{count}</b> файл(ов) скриптов будет переименовано в <code>{extension}</code>. Пути закреплённых скриптов будут обновлены. {startup} {skipped}",
|
||||
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
|
||||
"Настроенный скрипт запуска и его параметр также будут обновлены.",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED:
|
||||
"Одноимённых пар .md/.js, которые не будут перемещены: {count}.",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
|
||||
"Пропущено файлов скриптов, поскольку целевой файл уже существует: {count}.\n{files}",
|
||||
MIGRATE_SCRIPT_FILES_NONE:
|
||||
"Не найдено подходящих файлов скриптов для перемещения.",
|
||||
MIGRATE_SCRIPT_FILES_COMPLETE:
|
||||
"Перемещено файлов скриптов в {extension}: {count}.",
|
||||
MIGRATE_SCRIPT_FILES_FAILED:
|
||||
"Не удалось переместить файлы скриптов. Выполненные переименования по возможности отменены.",
|
||||
ENABLE_ONLOAD_SCRIPTS_NAME: "Включить onload-скрипты",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
|
||||
"Этот файл содержит <code>excalidraw-onload-script</code>. Включить onload-скрипты?",
|
||||
@@ -1090,6 +1242,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:
|
||||
"Позже это можно изменить в командной палитре («Автозапуск скриптов») или в Настройках → Автоматизация Excalidraw → Автозапуск скриптов.",
|
||||
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>. Включить ссылки-команды?",
|
||||
@@ -1100,9 +1265,10 @@ export default {
|
||||
"Это создаёт риск при открытии рисунков из неизвестных источников: вредоносный рисунок может превратить обычный клик в запуск привилегированной команды. " +
|
||||
"Включайте это только если доверяете файлу и его источнику.",
|
||||
STARTUP_SCRIPT_NAME: "Сценарий запуска",
|
||||
STARTUP_SCRIPT_JS_DISABLED:
|
||||
"Сценарии запуска JavaScript отключены. Сначала включите файлы JavaScript в настройках Excalidraw Automate.",
|
||||
STARTUP_SCRIPT_DESC:
|
||||
"Если этот параметр установлен, excalidraw будет выполнять скрипт при запуске плагина. Это полезно, если вы хотите установить какой-либо из крючков Excalidraw Automate. " +
|
||||
"Скрипт запуска - это файл в формате markdown, который должен содержать код javascript, который вы хотите выполнять при запуске Excalidraw.",
|
||||
"Если задано, Excalidraw выполнит скрипт при запуске плагина. Это полезно для настройки крючков Excalidraw Automate. Пути без расширения используют файл Markdown; файлы <code>.js</code> принимаются, когда включена загрузка файлов JavaScript.",
|
||||
STARTUP_SCRIPT_BUTTON_CREATE: "Создание сценария запуска",
|
||||
STARTUP_SCRIPT_BUTTON_OPEN: "Открыть сценарий запуска",
|
||||
FILETYPE_NAME:
|
||||
@@ -1131,6 +1297,9 @@ export default {
|
||||
"Включение этой функции упрощает использование свойств титульного листа Excalidraw, позволяя использовать множество мощных настроек. Если вы предпочитаете не загружать эти свойства автоматически, " +
|
||||
"Вы можете отключить эту функцию, но при этом вам придется вручную удалить все ненужные свойства из предложения. " +
|
||||
"Обратите внимание, что включение этой настройки требует перезапуска плагина, так как свойства загружаются при запуске.",
|
||||
FONTS_HEAD: "Шрифты",
|
||||
FONTS_DESC:
|
||||
"Настройте локальные гарнитуры и загруженные шрифты CJK для Excalidraw.",
|
||||
CUSTOM_FONT_HEAD: "Локальный шрифт",
|
||||
ENABLE_FOURTH_FONT_NAME: "Включите опцию локального шрифта",
|
||||
ENABLE_FOURTH_FONT_DESC:
|
||||
@@ -1144,10 +1313,15 @@ export default {
|
||||
"Если файл не выбран, Excalidraw по умолчанию использует шрифт Virgil. " +
|
||||
"Для оптимальной производительности рекомендуется использовать файл .woff2, так как Excalidraw закодирует только необходимые глифы при экспорте изображений в SVG. " +
|
||||
"Другие форматы шрифтов будут встраивать весь шрифт в экспортируемый файл, что может привести к значительному увеличению размера файла.",
|
||||
OFFLINE_CJK_NAME: "Поддержка шрифтов CJK без подключения к Интернету",
|
||||
OFFLINE_CJK_GROUP_DESC:
|
||||
"Загрузите и выборочно предварительно загружайте китайские, японские и корейские шрифты, чтобы Excalidraw мог отображать их без подключения к Интернету.",
|
||||
SCRIPT_SETTINGS_HEAD: "Настройки для установленных сценариев",
|
||||
SCRIPT_SETTINGS_DESC:
|
||||
"Некоторые сценарии Excalidraw Automate Scripts включают в себя настройки. Настройки упорядочены по сценариям. Настройки станут видны в этом списке только после того, как вы один раз выполните загруженный скрипт.",
|
||||
TASKBONE_HEAD: "Taskbone Оптический распознаватель символов",
|
||||
TASKBONE_GROUP_DESC:
|
||||
"Настройте дополнительный онлайн-сервис OCR Taskbone для извлечения доступного для поиска текста из рисунков и изображений.",
|
||||
TASKBONE_DESC:
|
||||
"Это экспериментальная интеграция оптического распознавания символов в Excalidraw. Обратите внимание, что taskbone - это независимый внешний сервис, не предоставляемый ни Excalidraw, ни проектом плагинов Excalidraw-Obsidian. " +
|
||||
"Сервис OCR выхватывает разборчивый текст из произвольных линий и встроенных изображений на вашем холсте и помещает распознанный текст на передний план вашего рисунка, а также в буфер обмена. " +
|
||||
@@ -1266,6 +1440,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 +1466,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 +1477,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 занимает слишком много времени. Пожалуйста, попробуйте снова.",
|
||||
};
|
||||
+179
-4
@@ -15,6 +15,21 @@ export default {
|
||||
// Sugester
|
||||
SELECT_FILE_TO_INSERT: "选择要嵌入到当前绘图中的文件",
|
||||
// main.ts
|
||||
SETTINGS_DATA_INVALID:
|
||||
"Excalidraw 正在等待有效的替代 data.json。在恢复该文件,或重新启动 Obsidian 并选择重置为默认值之前,设置更改不会保存。",
|
||||
SETTINGS_DATA_REPAIRED_FROM_MEMORY:
|
||||
"收到的 Excalidraw 设置文件为空或无法读取,已拒绝该文件。当前设置已写回,以修复 data.json。",
|
||||
SETTINGS_DATA_RECOVERED:
|
||||
"Excalidraw 的 data.json 为空或无法读取。已自动恢复最近的有效设置。",
|
||||
SETTINGS_RECOVERY_MISSING_TITLE: "Excalidraw 设置文件缺失",
|
||||
SETTINGS_RECOVERY_MISSING_DESC:
|
||||
"此设备上存在最近的有效设置备份。你可以恢复该备份,或将 Excalidraw 重置为出厂默认值。关闭此消息将恢复备份。",
|
||||
SETTINGS_RECOVERY_CORRUPT_TITLE: "Excalidraw 设置文件已损坏",
|
||||
SETTINGS_RECOVERY_CORRUPT_DESC:
|
||||
"设置文件为空或无法读取,并且此设备上没有恢复备份。你可以将 Excalidraw 重置为出厂默认值,或保持文件不变,同时从其他来源恢复有效的 data.json。关闭此消息将等待替代文件。",
|
||||
SETTINGS_RECOVERY_RESTORE_BACKUP: "恢复备份",
|
||||
SETTINGS_RECOVERY_RESET_DEFAULTS: "重置为默认值",
|
||||
SETTINGS_RECOVERY_WAIT_FOR_FILE: "等待恢复文件",
|
||||
ERROR_INITIALIZING_EA: "初始化 Excalidraw Automate 时出错",
|
||||
CONVERT_URL_TO_FILE: "从 URL 下载图片到本地",
|
||||
UNZIP_CURRENT_FILE: "解压当前 Excalidraw 文件",
|
||||
@@ -215,6 +230,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 选中的元素:识别涂鸦和图片里的文本并复制到剪贴板",
|
||||
@@ -337,6 +355,18 @@ export default {
|
||||
SEARCH_SHOWHIDE_ARIA: "显示/隐藏搜索栏",
|
||||
SEARCH_NEXT: "下一个",
|
||||
SEARCH_PREVIOUS: "上一个",
|
||||
SETTINGS_TOOLBAR_COPY: "复制设置",
|
||||
SETTINGS_TOOLBAR_NOTEBOOKLM: "NotebookLM",
|
||||
SETTINGS_TOOLBAR_BUGS: "问题",
|
||||
SETTINGS_TOOLBAR_WIKI: "Wiki",
|
||||
SETTINGS_TOOLBAR_YOUTUBE: "YouTube",
|
||||
SETTINGS_TOOLBAR_LEARN: "学习",
|
||||
SETTINGS_TOOLBAR_FOLLOW: "Twitter",
|
||||
SETTINGS_TOOLBAR_READ: "阅读书籍",
|
||||
SETTINGS_TOOLBAR_KOFI: "Ko-fi",
|
||||
USE_DECLARATIVE_SETTINGS_NAME: "使用可搜索设置",
|
||||
USE_DECLARATIVE_SETTINGS_DESC:
|
||||
"使用 Obsidian 可搜索的多页面设置界面。关闭后将使用 Excalidraw 的旧版单页面设置。需要重启 Obsidian。",
|
||||
|
||||
//settings.ts
|
||||
FOLDER_PLACEHOLDER: "e.g.: Excalidraw",
|
||||
@@ -370,7 +400,6 @@ export default {
|
||||
"禁用 Excalidraw 的上下文菜单。这在移动设备上很有用,因为上下文菜单有时会在不需要的时候弹出。",
|
||||
NOTEBOOKLM_LINK_ARIA:
|
||||
"向 NotebookLM 咨询有关插件的帮助。此模型已预加载了我所有的视频转录稿、发布说明和其他帮助内容。与 NotebookLM 聊天,浏览我的 250+ 视频和 Excalidraw 文件。",
|
||||
NOTEBOOKLM_LINK_TEXT: "学习插件。访问 NotebookLM 知识库。",
|
||||
EXCALIDRAW_MASTERY: "Excalidraw Mastery",
|
||||
EXCALIDRAW_MASTERY_PROMO_ARIA: "打开 Excalidraw Mastery",
|
||||
EXCALIDRAW_MASTERY_PROMO_HTML: `<p><b>在各种开关和菜单里找不着北?</b></p><p>Excalidraw 是一款为高强度工作流打造的 Visual PKM 强力工具,适合 <b>Visual-First Daily Notes</b>、深度 <b>PDF 研究</b>、<b>自动化</b>、<b>AI 集成</b> 和 <b>Visual Zettelkasten</b>。但强大能力也伴随着复杂度。</p><p>跳过反复试错。<a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}" target="_blank">👉 加入 Excalidraw Mastery</a>,一步一步学会这些具体配置。减少工具摩擦,与视觉思维社区伙伴一起掌握知识!</p>`,
|
||||
@@ -401,6 +430,14 @@ export default {
|
||||
"<b>关闭:</b>您需要手动检查插件更新(设置 - 第三方插件 - 检查更新)。",
|
||||
|
||||
BASIC_HEAD: "基本",
|
||||
BASIC_UPDATES_STARTUP_HEAD: "更新与启动",
|
||||
BASIC_UPDATES_STARTUP_DESC: "发行说明、更新检查与通知,以及启动欢迎画面。",
|
||||
BASIC_FILES_FOLDERS_HEAD: "文件与文件夹",
|
||||
BASIC_FILES_FOLDERS_DESC:
|
||||
"设置绘图、裁剪、批注、模板和 Excalidraw Automate 脚本的默认文件夹与路径。",
|
||||
BASIC_STENCIL_LIBRARY_HEAD: "素材库",
|
||||
BASIC_STENCIL_LIBRARY_DESC:
|
||||
"选择素材库数据的存储位置,并配置其仓库文件夹和本地素材库文件。",
|
||||
BASIC_DESC: `包括:更新说明,更新通知,新绘图文件、模板文件、脚本文件的存储路径等。`,
|
||||
FOLDER_NAME: "Excalidraw 文件夹(區分大小寫!)",
|
||||
FOLDER_DESC: "新绘图的默认存储路径。若为空,将在仓库根目录中创建新绘图。",
|
||||
@@ -581,6 +618,9 @@ export default {
|
||||
AI_USAGE_SETTINGS_BUTTON_DESC:
|
||||
"按模型查看当前 Obsidian 会话的 AI Token 消耗明细。重启后将重置。",
|
||||
SAVING_HEAD: "保存",
|
||||
SAVING_STORAGE_AUTOSAVE_HEAD: "存储与自动保存",
|
||||
SAVING_STORAGE_AUTOSAVE_DESC:
|
||||
"控制绘图 JSON 压缩,并选择桌面端和移动端的自动保存间隔。",
|
||||
SAVING_DESC: "包括:压缩,自动保存的时间间隔,文件的命名格式和扩展名等。",
|
||||
COMPRESS_NAME: "压缩 Excalidraw JSON",
|
||||
COMPRESS_DESC:
|
||||
@@ -613,6 +653,8 @@ export default {
|
||||
"直接退出 Obsidian 应用(在应用切换器中划掉)不会触发自动保存。" +
|
||||
"此外,当您切换到其他应用时,有时系统会自动清理 Obsidian 后台以释放资源。这种情况下,自动保存会失效。",
|
||||
FILENAME_HEAD: "文件名",
|
||||
FILENAME_GROUP_DESC:
|
||||
"配置新建、嵌入、裁剪和批注绘图文件名的生成方式。",
|
||||
FILENAME_DESC: `<p>点击阅读 <a href="${URLs.MOMENTJS_COM_DOCS}">日期和时间格式参考</a>。</p>`,
|
||||
FILENAME_SAMPLE: "“新建绘图”系列命令创建的文件名如:",
|
||||
FILENAME_EMBED_SAMPLE:
|
||||
@@ -638,6 +680,9 @@ export default {
|
||||
DISPLAY_HEAD: "界面 & 行为",
|
||||
DISPLAY_DESC:
|
||||
"包括:左手模式、动态样式、匹配 Excalidraw 和 Obsidian 主题、默认运行模式等。",
|
||||
DISPLAY_EDITOR_PREVIEWS_HEAD: "编辑与预览",
|
||||
DISPLAY_EDITOR_PREVIEWS_DESC:
|
||||
"配置画布编辑手势,以及 Excalidraw 文件在阅读模式和悬停预览中的显示方式。",
|
||||
OVERRIDE_OBSIDIAN_FONT_SIZE_NAME: "限制 Obsidian 字体大小为编辑器文本",
|
||||
OVERRIDE_OBSIDIAN_FONT_SIZE_DESC:
|
||||
"Obsidian 的自定义字体大小设置会影响整个界面,包括 Excalidraw 和依赖默认字体大小的主题。" +
|
||||
@@ -712,6 +757,8 @@ export default {
|
||||
`请参阅下方 <a href='#${TAG_PDFEXPORT}'>PDF 导出设置</a>。<br>` +
|
||||
`⚠️ 关闭并重新打开 Excalidraw/Markdown 文件后生效。`,
|
||||
MODES_HEAD: "UI 模式",
|
||||
MODES_DESC:
|
||||
"选择不同设备的 Excalidraw 界面布局、标题栏控件和左右手托盘位置。",
|
||||
DESKTOP_UI_MODE_NAME: "桌面端偏好模式",
|
||||
DESKTOP_UI_MODE_DESC: "桌面端设备默认 UI 模式。",
|
||||
TABLET_UI_MODE_NAME: "平板端偏好模式",
|
||||
@@ -724,12 +771,19 @@ export default {
|
||||
MODE_PHONE: "Phone-mode",
|
||||
REAPPLY_UI_MODE_BUTTON: "重新应用 UI 模式",
|
||||
HOTKEY_OVERRIDE_HEAD: "热键覆盖",
|
||||
HOTKEY_OVERRIDE_GROUP_DESC:
|
||||
"管理应优先于冲突 Obsidian 热键的 Excalidraw 按键组合。",
|
||||
HOTKEY_OVERRIDE_CONTROL_NAME: "管理热键覆盖",
|
||||
HOTKEY_OVERRIDE_DESC:
|
||||
`一些 Excalidraw 的热键,如 ${labelCTRL()}+Enter 用于编辑文本,或 ${labelCTRL()}+K 用于创建元素链接,` +
|
||||
"与 Obsidian 的热键设置冲突。您在下面添加的热键组合将在使用 Excalidraw 时覆盖 Obsidian 的热键设置," +
|
||||
`因此如果您希望在 Excalidraw 中默认“编组”,而不是“查看关系图谱”(核心插件 - 关系图谱),您可以添加 ${labelCTRL()}+G。`,
|
||||
THEME_HEAD: "主题和样式",
|
||||
THEME_DESC:
|
||||
"控制界面样式、绘图和嵌入主题、打开模式以及移动设备安全区域间距。",
|
||||
ZOOM_AND_PAN_HEAD: "缩放和平移",
|
||||
ZOOM_AND_PAN_DESC:
|
||||
"配置鼠标、触控、打开、调整大小和缩放范围行为。",
|
||||
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "右键拖动平移",
|
||||
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
|
||||
"右键点击并拖动来平移绘图(和在线白板工具 Miro 类似)。按 'm' 键打开上下文菜单。",
|
||||
@@ -762,7 +816,9 @@ export default {
|
||||
ZOOM_MAX_DESC:
|
||||
"绘图放大的极限。默认:3000%。通常无需修改,考虑完整性而提供。",
|
||||
PEN_HEAD: "手写笔",
|
||||
PEN_DESC: "配置自动手写笔模式、触控手势、橡皮擦和自由绘制十字线。",
|
||||
GRID_HEAD: "网格",
|
||||
GRID_DESC: "配置网格方向、自动或自定义颜色以及不透明度。",
|
||||
GRID_DYNAMIC_COLOR_NAME: "动态网格颜色",
|
||||
GRID_DYNAMIC_COLOR_DESC:
|
||||
"<b>开启:</b>更改网格颜色以匹配绘图颜色。<br><b>关闭:</b>将以下颜色用作网格颜色。",
|
||||
@@ -775,6 +831,7 @@ export default {
|
||||
GRID_HORIZONTAL: "渲染水平网格",
|
||||
GRID_VERTICAL: "渲染垂直网格",
|
||||
LASER_HEAD: "激光笔工具(更多工具 > 激光笔)",
|
||||
LASER_DESC: "配置激光笔颜色及其轨迹淡出的速度和长度。",
|
||||
LASER_COLOR: "激光笔颜色",
|
||||
LASER_DECAY_TIME_NAME: "激光笔消失时间",
|
||||
LASER_DECAY_TIME_DESC: "单位是毫秒,默认 1000(即 1 秒)。",
|
||||
@@ -793,6 +850,20 @@ export default {
|
||||
"链接的源文件被重命名时,绘图中相应的 <code>[[内部链接]]</code> 也会同步更新。" +
|
||||
"若您不愿绘图中的链接外观因此而变化,可使用 <code>[[内部链接|别名]]</code>。",
|
||||
DRAG_MODIFIER_NAME: "修饰键",
|
||||
DRAG_MODIFIER_GROUP_DESC:
|
||||
"配置链接打开手势,以及点击和拖放操作的平台特定修饰键组合。",
|
||||
LINK_OPENING_GESTURES_HEAD: "链接打开手势",
|
||||
LINK_OPENING_GESTURES_DESC:
|
||||
"配置嵌入绘图和查看模式中的长按延迟与双击打开链接。",
|
||||
WEB_BROWSER_DRAG_ACTION_DESC:
|
||||
"选择从网页浏览器拖入链接、图片、导入项和嵌入内容时的修饰键组合。",
|
||||
LOCAL_FILE_DRAG_ACTION_DESC:
|
||||
"选择从操作系统拖入链接、图片、导入项和嵌入内容时的修饰键组合。",
|
||||
INTERNAL_DRAG_ACTION_DESC:
|
||||
"选择在 Obsidian 内拖动链接、图片、全尺寸图片和嵌入内容时的修饰键组合。",
|
||||
PANE_TARGET_DESC: "选择决定点击链接打开位置的修饰键组合。",
|
||||
MODIFIER_KEY_USAGE_NAME: "配置修饰键",
|
||||
MODIFIER_KEY_COMBINATIONS: "修饰键组合",
|
||||
DRAG_MODIFIER_DESC:
|
||||
`在您按住点击链接或拖动元素时,可以触发某些行为。您可以为这些行为添加修饰键。` +
|
||||
`Excalidraw 不会检查您的设置是否合理,因此请谨慎设置,避免冲突。` +
|
||||
@@ -888,6 +959,20 @@ export default {
|
||||
"拖动链接到 Excalidraw 时,使用 <code>http" +
|
||||
"s://noembed" +
|
||||
".com/embed?url=</code> 来获取 HTTPS 页面标题。",
|
||||
LINK_BEHAVIOR_HEAD: "链接行为",
|
||||
LINK_BEHAVIOR_DESC:
|
||||
"配置链接同步、相关链接、悬停预览、点击处理和网页标题查询。",
|
||||
LINK_USAGE_NAME: "在 Excalidraw 中使用链接",
|
||||
LINK_OPENING_HEAD: "窗格和标签页行为",
|
||||
LINK_OPENING_DESC:
|
||||
"选择链接是否复用、聚焦或切换窗格、标签页和主工作区。",
|
||||
LINK_APPEARANCE_HEAD: "链接外观",
|
||||
LINK_APPEARANCE_DESC: "配置链接显示时使用的括号、前缀、图标和不透明度。",
|
||||
TODO_HEAD: "待办事项",
|
||||
TODO_GROUP_DESC: "配置待办事项解析以及未完成和已完成任务使用的图标。",
|
||||
TRANSCLUSION_HEAD: "文本嵌入",
|
||||
TRANSCLUSION_DESC:
|
||||
"配置嵌入 Markdown 文本的字符限制、换行和引用符号清理。",
|
||||
PDF_TO_IMAGE: "以图像形式嵌入到绘图中的 PDF",
|
||||
PDF_TO_IMAGE_SCALE_NAME: "分辨率",
|
||||
PDF_TO_IMAGE_SCALE_DESC:
|
||||
@@ -897,8 +982,13 @@ export default {
|
||||
EMBED_TOEXCALIDRAW_DESC:
|
||||
"包括:以图像形式嵌入到绘图中的 PDF、以交互或图像形式嵌入到绘图中的 Markdown 文档等。",
|
||||
MD_HEAD: "以图像形式嵌入到绘图中的 Markdown 文档(MD-Embed)",
|
||||
MD_GROUP_DESC:
|
||||
"设置以图像呈现的 Markdown 文件的尺寸、字体、颜色、边框和 CSS。",
|
||||
MD_EMBED_CUSTOMDATA_HEAD_NAME:
|
||||
"以交互形式嵌入到绘图中的 Markdown 文档(MD-Embeddable)",
|
||||
MD_EMBED_CUSTOMDATA_GROUP_DESC:
|
||||
"配置未来交互式 Markdown 嵌入的编辑方式和默认外观。",
|
||||
MD_EMBED_DEFAULTS_CONTROL_NAME: "交互式 Markdown 默认外观",
|
||||
MD_EMBED_CUSTOMDATA_HEAD_DESC: `以下设置只会影响以后的嵌入。已存在的嵌入保持不变。嵌入框的主题设置位于“界面 & 行为”部分。`,
|
||||
MD_EMBED_SINGLECLICK_EDIT_NAME: "单击编辑嵌入的 Markdown",
|
||||
MD_EMBED_SINGLECLICK_EDIT_DESC:
|
||||
@@ -938,12 +1028,17 @@ export default {
|
||||
EMBED_HEAD: "嵌入到 Markdown 文档中的绘图",
|
||||
EMBED_DESC: `包括:嵌入到 Markdown 文档中的绘图的预览图类型(SVG、PNG)、源文件类型(Excalidraw、SVG、PNG)、缓存、图像尺寸、图像主题,以及嵌入的语法等。
|
||||
此外,还有自动导出 SVG 或 PNG 文件并保持与绘图文件状态同步的设置。`,
|
||||
EMBED_PREVIEW_LINKS_HEAD: "预览、链接与 Canvas",
|
||||
EMBED_PREVIEW_LINKS_DESC:
|
||||
"选择预览和插入文件的格式、源链接行为、占位图像及沉浸式 Canvas 嵌入。",
|
||||
EMBED_CANVAS: "Obsidian 白板支持",
|
||||
EMBED_CANVAS_NAME: "沉浸式嵌入",
|
||||
EMBED_CANVAS_DESC:
|
||||
"当嵌入绘图到 Obsidian 白板中时,隐藏节点的边界和背景。" +
|
||||
"注意:如果想要背景完全透明,您依然需要设置导出背景为透明(关闭“导出图片包含背景”)。",
|
||||
EMBED_CACHING: "图像缓存和渲染优化",
|
||||
EMBED_CACHING_DESC:
|
||||
"调整并行渲染和本地图像缓存,清除缓存图像或备份,并可复用已导出的预览。",
|
||||
RENDERING_CONCURRENCY_NAME: "图像渲染并发性",
|
||||
RENDERING_CONCURRENCY_DESC:
|
||||
"用于图像渲染的并行工作线程数。增加该值可以加快渲染速度,但可能会减慢系统其他部分的运行速度。" +
|
||||
@@ -956,8 +1051,13 @@ export default {
|
||||
"实际影响在于 Obsidian 内部的本地磁盘或浏览器存储占用。在手机以及浏览器存储配额较紧、剩余磁盘空间有限的桌面设备上需要留意。<br><br>" +
|
||||
"较小的值会更快回收本地缓存空间,但可能导致 PDF 和嵌入绘图更频繁地重新渲染。较大的值会保留更久的缓存,以换取更快的加载速度。",
|
||||
EXPORT_SUBHEAD: "导出",
|
||||
EXPORT_SUBHEAD_DESC:
|
||||
"配置 PDF 渲染、导出的场景数据、图像尺寸、主题与背景、PDF 默认值及自动 PNG/SVG 副本。",
|
||||
EMBED_SIZING: "图像尺寸",
|
||||
EMBED_SIZING_DESC: "设置嵌入图像的默认尺寸、PNG 缩放比例和导出边距。",
|
||||
EMBED_THEME_BACKGROUND: "图像的主题和背景色",
|
||||
EMBED_THEME_BACKGROUND_DESC:
|
||||
"选择导出图像的背景和主题,以及预览是否跟随 Obsidian 主题。",
|
||||
EMBED_IMAGE_CACHE_NAME: "为嵌入到 Markdown 文档中的绘图创建预览图缓存",
|
||||
EMBED_IMAGE_CACHE_DESC:
|
||||
"可提高下次嵌入的速度。" +
|
||||
@@ -1037,7 +1137,18 @@ export default {
|
||||
"在导出图片中嵌入 Excalidraw 场景。可以在其 frontmatter 中添加如 <code>excalidraw-export-embed-scene: true/false</code> 的键值对来覆盖该项。" +
|
||||
"该项仅在您下次(重新)打开绘图时生效。",
|
||||
PDF_EXPORT_SETTINGS: "PDF 导出设置",
|
||||
PDF_EXPORT_SETTINGS_DESC:
|
||||
"选择默认 PDF 页面大小、方向、分页、边距、纸张颜色和对齐方式。",
|
||||
PDF_EXPORT_DEFAULTS_CONTROL_NAME: "默认 PDF 导出布局",
|
||||
EXPORT_HEAD: "导出设置",
|
||||
EXPORT_AUTOEXPORT_DESC:
|
||||
"保持导出文件同步,并自动创建 SVG、PNG、浅色和深色版本。",
|
||||
SETTINGS_NAVIGATION_OPEN: "打开",
|
||||
SETTINGS_BREADCRUMB_ARIA: "设置路径",
|
||||
SETTINGS_RELATED_AUTOEXPORT_DESC:
|
||||
"启用自动 PNG 或 SVG 副本,使这些格式可在插入文件类型下拉列表中选择。",
|
||||
SETTINGS_RELATED_EMBED_TYPE_DESC:
|
||||
"选择在文档中嵌入绘图时插入 Excalidraw、PNG 还是 SVG。",
|
||||
EXPORT_SYNC_NAME: "保持 SVG/PNG 文件名与绘图文件同步",
|
||||
EXPORT_SYNC_DESC:
|
||||
"打开后,当绘图文件被重命名时,插件将同步更新同文件夹下的同名 .SVG 和 .PNG 文件。" +
|
||||
@@ -1110,8 +1221,11 @@ export default {
|
||||
CUSTOM_PEN_DESC:
|
||||
"在绘图上的 Obsidian 菜单按钮旁边切换自定义画笔。长按(双击)画笔按钮可以修改其样式。",
|
||||
EXPERIMENTAL_HEAD: "杂项",
|
||||
EXPERIMENTAL_DESC: `包括:默认的 LaTeX 公式,字段建议,绘图文件的类型标识符,OCR 等。`,
|
||||
EXPERIMENTAL_DESC:
|
||||
"配置 LaTeX 默认值、文件类型标识、实时预览行为、属性建议以及实验性的 Taskbone OCR 集成。",
|
||||
EA_HEAD: "Excalidraw 自动化",
|
||||
EA_GROUP_DESC:
|
||||
"配置 Excalidraw Automate 脚本、启动和自动启动行为、命令链接,以及已安装脚本提供的设置。",
|
||||
EA_DESC:
|
||||
`ExcalidrawAutomate 是用于 Excalidraw 自动化脚本的 API,但是目前说明文档还不够完善,` +
|
||||
`建议阅读 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_API_EXCALIDRAWAUTOMATE_D_TS}">ExcalidrawAutomate.d.ts</a> 文件源码,` +
|
||||
@@ -1122,6 +1236,33 @@ export default {
|
||||
FIELD_SUGGESTER_DESC:
|
||||
"开启后,当您在编辑器中输入 <code>excalidraw-</code> 或者 <code>ea.</code> 时,会弹出一个带有函数说明的自动补全提示菜单。<br>" +
|
||||
"该功能借鉴了 Breadcrumbs 和 Templater 插件。",
|
||||
ALLOW_JS_FILES_NAME: "从 Scripts 文件夹加载 JavaScript 文件",
|
||||
ALLOW_JS_FILES_DESC:
|
||||
"启用后,Excalidraw Automate 会监视并运行 Scripts 文件夹中的 <code>.js</code> 文件,也允许使用 <code>.js</code> 启动脚本。" +
|
||||
"默认情况下,Obsidian Sync 不同步非 Markdown 文件,Obsidian 不会打开 <code>.js</code> 文件进行编辑,文件列表也会隐藏它们。需要时请在 Obsidian 中启用<b>同步所有其他文件类型</b>和<b>显示所有文件类型</b>。如果存在同名的 <code>.md</code> 和 <code>.js</code> 脚本,将使用 Markdown 文件。",
|
||||
STORE_SCRIPTS_AS_JS_NAME: "将下载的脚本存储为",
|
||||
STORE_SCRIPTS_AS_JS_DESC:
|
||||
"选择脚本库新下载和更新在本地使用的文件类型。无论远程源是 <code>.md</code> 还是 <code>.js</code>,都会使用此设置。",
|
||||
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
|
||||
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
|
||||
MIGRATE_SCRIPT_FILES_NAME: "迁移现有脚本文件",
|
||||
MIGRATE_SCRIPTS_TO_JS_BUTTON: "将现有脚本迁移为 .js",
|
||||
MIGRATE_SCRIPTS_TO_MD_BUTTON: "将现有脚本迁移为 .md",
|
||||
MIGRATE_SCRIPT_FILES_STATUS:
|
||||
"有 {eligible} 个脚本文件可迁移为 {extension}。{skipped}",
|
||||
MIGRATE_SCRIPT_FILES_CONFIRM:
|
||||
"继续前请备份仓库。<br><br><b>{count}</b> 个脚本文件将重命名为 <code>{extension}</code>,固定脚本的路径也会更新。{startup} {skipped}",
|
||||
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
|
||||
"已配置的启动脚本及其设置也会更新。",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED:
|
||||
"有 {count} 对同名 .md/.js 文件不会被迁移。",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
|
||||
"因目标文件已存在,已跳过 {count} 个脚本文件:\n{files}",
|
||||
MIGRATE_SCRIPT_FILES_NONE: "没有找到可迁移的脚本文件。",
|
||||
MIGRATE_SCRIPT_FILES_COMPLETE:
|
||||
"已将 {count} 个脚本文件迁移为 {extension}。",
|
||||
MIGRATE_SCRIPT_FILES_FAILED:
|
||||
"无法迁移脚本文件。已尽可能回滚完成的重命名。",
|
||||
ENABLE_ONLOAD_SCRIPTS_NAME: "加载期脚本(onload)",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
|
||||
"此文件包含 <code>excalidraw-onload-script</code>。是否启用加载期脚本?",
|
||||
@@ -1131,6 +1272,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:
|
||||
"你以后可以在命令面板(“自动启动脚本”)或设置 → Excalidraw 自动化 → 自动启动脚本中更改此设置。",
|
||||
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 命令。是否启用命令链接?",
|
||||
@@ -1141,9 +1294,10 @@ export default {
|
||||
"如果你打开未知来源的绘图,这会带来风险:恶意绘图可以让一次普通点击触发高权限命令。" +
|
||||
"只有在你信任该文件及其来源时才启用此功能。",
|
||||
STARTUP_SCRIPT_NAME: "启动期脚本(startup)",
|
||||
STARTUP_SCRIPT_JS_DISABLED:
|
||||
"JavaScript 启动脚本已禁用。请先在 Excalidraw Automate 设置中启用 JavaScript 文件。",
|
||||
STARTUP_SCRIPT_DESC:
|
||||
"插件启动时将自动执行该脚本。可用于设置 Excalidraw 自动化钩子。" +
|
||||
"该脚本是包含 javascript 代码的 Markdown 文件。",
|
||||
"插件启动时将自动执行该脚本,可用于设置 Excalidraw Automate 钩子。没有扩展名的路径使用 Markdown 文件;启用 JavaScript 文件加载后可使用 <code>.js</code> 文件。",
|
||||
STARTUP_SCRIPT_BUTTON_CREATE: "创建启动期脚本",
|
||||
STARTUP_SCRIPT_BUTTON_OPEN: "打开启动期脚本",
|
||||
FILETYPE_NAME: "在文件浏览器中为 excalidraw.md 文件添加类型标识符(如 ✏️)",
|
||||
@@ -1184,6 +1338,8 @@ export default {
|
||||
"为了获得最佳性能,建议使用 .woff2 文件,因为当导出 SVG 格式的图片时,Excalidraw 只会编码必要的字形。" +
|
||||
`其他字体格式将在导出文件中嵌入整个字体,可能会导致文件大小显著增加。<b>译者注:</b>可在 <a href="${URLs.WANGCHUJIANG_COM_FREE_FONT}" target='_blank'>Free Font</a> 获取免费商用中文手写字体。`,
|
||||
OFFLINE_CJK_NAME: "离线 CJK 字体支持",
|
||||
OFFLINE_CJK_GROUP_DESC:
|
||||
"下载并按需预加载中文、日文和韩文字体,使 Excalidraw 无需互联网连接也能显示这些字体。",
|
||||
OFFLINE_CJK_DESC: `<strong>该项需要重启 Obsidian 才能生效。</strong><br>
|
||||
Excalidraw.com 提供手写风格的 CJK 字体。默认情况下,这些字体不会包含在插件本地,而是从互联网获取。
|
||||
如果您希望 Excalidraw 完全本地化,以便在没有互联网连接的情况下使用,可以从 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RAW_REFS_HEADS_MASTER_ASSETS_EXCALIDRAW_FONTS_ZIP}" target="_blank">GitHub 下载所需的字体文件</a>。
|
||||
@@ -1200,6 +1356,8 @@ export default {
|
||||
SCRIPT_SETTINGS_DESC:
|
||||
"有些 Excalidraw 自动化脚本包含设置项,当执行这些脚本时,它们会在该列表下添加设置项。",
|
||||
TASKBONE_HEAD: "Taskbone OCR(光学符号识别)",
|
||||
TASKBONE_GROUP_DESC:
|
||||
"配置可选的 Taskbone 在线 OCR 服务,从绘图和图像中提取可搜索文本。",
|
||||
TASKBONE_DESC:
|
||||
"这是一个将 OCR 融入 Excalidraw 的实验性功能。请注意,Taskbone 是一项独立的外部服务,而不是由 Excalidraw 或 obsidian-excalidraw-plugin 项目提供的。" +
|
||||
"OCR 能够对绘图上用自由画笔工具写下的涂鸦或者嵌入的图像进行文本识别,并将识别出来的文本写入绘图文件的 frontmatter,同时复制到剪贴板。" +
|
||||
@@ -1370,6 +1528,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 +1554,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 +1796,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 绘图耗时过长。请重试。",
|
||||
};
|
||||
+179
-4
@@ -15,6 +15,21 @@ export default {
|
||||
// Sugester
|
||||
SELECT_FILE_TO_INSERT: "選擇要嵌入到當前繪圖中的檔案",
|
||||
// main.ts
|
||||
SETTINGS_DATA_INVALID:
|
||||
"Excalidraw 正在等待有效的替代 data.json。在復原該檔案,或重新啟動 Obsidian 並選擇重設為預設值之前,設定變更不會儲存。",
|
||||
SETTINGS_DATA_REPAIRED_FROM_MEMORY:
|
||||
"收到的 Excalidraw 設定檔為空或無法讀取,已拒絕該檔案。目前的設定已寫回,以修復 data.json。",
|
||||
SETTINGS_DATA_RECOVERED:
|
||||
"Excalidraw 的 data.json 為空或無法讀取。已自動復原最近的有效設定。",
|
||||
SETTINGS_RECOVERY_MISSING_TITLE: "Excalidraw 設定檔遺失",
|
||||
SETTINGS_RECOVERY_MISSING_DESC:
|
||||
"此裝置上有最近的有效設定備份。你可以復原該備份,或將 Excalidraw 重設為出廠預設值。關閉此訊息將復原備份。",
|
||||
SETTINGS_RECOVERY_CORRUPT_TITLE: "Excalidraw 設定檔已損壞",
|
||||
SETTINGS_RECOVERY_CORRUPT_DESC:
|
||||
"設定檔為空或無法讀取,且此裝置上沒有復原備份。你可以將 Excalidraw 重設為出廠預設值,或保持檔案不變,同時從其他來源復原有效的 data.json。關閉此訊息將等待替代檔案。",
|
||||
SETTINGS_RECOVERY_RESTORE_BACKUP: "復原備份",
|
||||
SETTINGS_RECOVERY_RESET_DEFAULTS: "重設為預設值",
|
||||
SETTINGS_RECOVERY_WAIT_FOR_FILE: "等待復原檔案",
|
||||
ERROR_INITIALIZING_EA: "初始化 Excalidraw Automate 時出錯",
|
||||
CONVERT_URL_TO_FILE: "從 URL 下載圖片到本地",
|
||||
UNZIP_CURRENT_FILE: "解壓當前 Excalidraw 檔案",
|
||||
@@ -215,6 +230,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 選中的元素:識別塗鴉和圖片裡的文字並複製到剪貼簿",
|
||||
@@ -337,6 +355,18 @@ export default {
|
||||
SEARCH_SHOWHIDE_ARIA: "顯示/隱藏搜尋欄",
|
||||
SEARCH_NEXT: "下一個",
|
||||
SEARCH_PREVIOUS: "上一個",
|
||||
SETTINGS_TOOLBAR_COPY: "複製設定",
|
||||
SETTINGS_TOOLBAR_NOTEBOOKLM: "NotebookLM",
|
||||
SETTINGS_TOOLBAR_BUGS: "問題",
|
||||
SETTINGS_TOOLBAR_WIKI: "Wiki",
|
||||
SETTINGS_TOOLBAR_YOUTUBE: "YouTube",
|
||||
SETTINGS_TOOLBAR_LEARN: "學習",
|
||||
SETTINGS_TOOLBAR_FOLLOW: "Twitter",
|
||||
SETTINGS_TOOLBAR_READ: "閱讀書籍",
|
||||
SETTINGS_TOOLBAR_KOFI: "Ko-fi",
|
||||
USE_DECLARATIVE_SETTINGS_NAME: "使用可搜尋設定",
|
||||
USE_DECLARATIVE_SETTINGS_DESC:
|
||||
"使用 Obsidian 可搜尋的多頁面設定介面。關閉後將使用 Excalidraw 的舊版單頁面設定。需要重新啟動 Obsidian。",
|
||||
|
||||
//settings.ts
|
||||
FOLDER_PLACEHOLDER: "e.g.: Excalidraw",
|
||||
@@ -370,7 +400,6 @@ export default {
|
||||
"停用 Excalidraw 的上下文選單。這在移動裝置上很有用,因為上下文選單有時會在不需要的時候彈出。",
|
||||
NOTEBOOKLM_LINK_ARIA:
|
||||
"向 NotebookLM 諮詢有關外掛的幫助。此模型已預載入了我所有的影片轉錄稿、釋出說明和其他幫助內容。與 NotebookLM 聊天,瀏覽我的 250+ 影片和 Excalidraw 檔案。",
|
||||
NOTEBOOKLM_LINK_TEXT: "學習外掛。訪問 NotebookLM 知識庫。",
|
||||
EXCALIDRAW_MASTERY: "Excalidraw Mastery",
|
||||
EXCALIDRAW_MASTERY_PROMO_ARIA: "開啟 Excalidraw Mastery",
|
||||
EXCALIDRAW_MASTERY_PROMO_HTML: `<p><b>在各種開關和選單裡找不著北?</b></p><p>Excalidraw 是一款為高強度工作流打造的 Visual PKM 強力工具,適合 <b>Visual-First Daily Notes</b>、深度 <b>PDF 研究</b>、<b>自動化</b>、<b>AI 整合</b> 和 <b>Visual Zettelkasten</b>。但強大能力也伴隨著複雜度。</p><p>跳過反覆試錯。<a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}" target="_blank">👉 加入 Excalidraw Mastery</a>,一步一步學會這些具體配置。減少工具摩擦,與視覺思維社群夥伴一起掌握知識!</p>`,
|
||||
@@ -401,6 +430,14 @@ export default {
|
||||
"<b>關閉:</b>您需要手動檢查外掛更新(設定 - 第三方外掛 - 檢查更新)。",
|
||||
|
||||
BASIC_HEAD: "基本",
|
||||
BASIC_UPDATES_STARTUP_HEAD: "更新與啟動",
|
||||
BASIC_UPDATES_STARTUP_DESC: "版本說明、更新檢查與通知,以及啟動歡迎畫面。",
|
||||
BASIC_FILES_FOLDERS_HEAD: "檔案與資料夾",
|
||||
BASIC_FILES_FOLDERS_DESC:
|
||||
"設定繪圖、裁切、註解、範本和 Excalidraw Automate 指令碼的預設資料夾與路徑。",
|
||||
BASIC_STENCIL_LIBRARY_HEAD: "素材庫",
|
||||
BASIC_STENCIL_LIBRARY_DESC:
|
||||
"選擇素材庫資料的儲存位置,並設定其儲存庫資料夾和本機素材庫檔案。",
|
||||
BASIC_DESC: `包括:更新說明,更新通知,新繪圖檔案、模板檔案、指令碼檔案的儲存路徑等。`,
|
||||
FOLDER_NAME: "Excalidraw 資料夾(區分大小寫!)",
|
||||
FOLDER_DESC: "新繪圖的預設儲存路徑。若為空,將在倉庫根目錄中建立新繪圖。",
|
||||
@@ -581,6 +618,9 @@ export default {
|
||||
AI_USAGE_SETTINGS_BUTTON_DESC:
|
||||
"按模型檢視當前 Obsidian 會話的 AI Token 消耗明細。重啟後將重置。",
|
||||
SAVING_HEAD: "儲存",
|
||||
SAVING_STORAGE_AUTOSAVE_HEAD: "儲存與自動儲存",
|
||||
SAVING_STORAGE_AUTOSAVE_DESC:
|
||||
"控制繪圖 JSON 壓縮,並選擇桌面版和行動版的自動儲存間隔。",
|
||||
SAVING_DESC: "包括:壓縮,自動儲存的時間間隔,檔案的命名格式和副檔名等。",
|
||||
COMPRESS_NAME: "壓縮 Excalidraw JSON",
|
||||
COMPRESS_DESC:
|
||||
@@ -613,6 +653,8 @@ export default {
|
||||
"直接退出 Obsidian 應用(在應用切換器中劃掉)不會觸發自動儲存。" +
|
||||
"此外,當您切換到其他應用時,有時系統會自動清理 Obsidian 後臺以釋放資源。這種情況下,自動儲存會失效。",
|
||||
FILENAME_HEAD: "檔名",
|
||||
FILENAME_GROUP_DESC:
|
||||
"設定新建、嵌入、裁切和註解繪圖檔名的產生方式。",
|
||||
FILENAME_DESC: `<p>點選閱讀 <a href="${URLs.MOMENTJS_COM_DOCS}">日期和時間格式參考</a>。</p>`,
|
||||
FILENAME_SAMPLE: "“新建繪圖”系列命令建立的檔名如:",
|
||||
FILENAME_EMBED_SAMPLE:
|
||||
@@ -638,6 +680,9 @@ export default {
|
||||
DISPLAY_HEAD: "介面 & 行為",
|
||||
DISPLAY_DESC:
|
||||
"包括:左手模式、動態樣式、匹配 Excalidraw 和 Obsidian 主題、預設執行模式等。",
|
||||
DISPLAY_EDITOR_PREVIEWS_HEAD: "編輯與預覽",
|
||||
DISPLAY_EDITOR_PREVIEWS_DESC:
|
||||
"設定畫布編輯手勢,以及 Excalidraw 檔案在閱讀模式和懸停預覽中的顯示方式。",
|
||||
OVERRIDE_OBSIDIAN_FONT_SIZE_NAME: "限制 Obsidian 字型大小為編輯器文字",
|
||||
OVERRIDE_OBSIDIAN_FONT_SIZE_DESC:
|
||||
"Obsidian 的自定義字型大小設定會影響整個介面,包括 Excalidraw 和依賴預設字型大小的主題。" +
|
||||
@@ -712,6 +757,8 @@ export default {
|
||||
`請參閱下方 <a href='#${TAG_PDFEXPORT}'>PDF 匯出設定</a>。<br>` +
|
||||
`⚠️ 關閉並重新開啟 Excalidraw/Markdown 檔案後生效。`,
|
||||
MODES_HEAD: "UI 模式",
|
||||
MODES_DESC:
|
||||
"選擇不同裝置的 Excalidraw 介面配置、標題列控制項和左右手托盤位置。",
|
||||
DESKTOP_UI_MODE_NAME: "桌面端偏好模式",
|
||||
DESKTOP_UI_MODE_DESC: "桌面端裝置預設 UI 模式。",
|
||||
TABLET_UI_MODE_NAME: "平板端偏好模式",
|
||||
@@ -724,12 +771,19 @@ export default {
|
||||
MODE_PHONE: "Phone-mode",
|
||||
REAPPLY_UI_MODE_BUTTON: "重新應用 UI 模式",
|
||||
HOTKEY_OVERRIDE_HEAD: "熱鍵覆蓋",
|
||||
HOTKEY_OVERRIDE_GROUP_DESC:
|
||||
"管理應優先於衝突 Obsidian 熱鍵的 Excalidraw 按鍵組合。",
|
||||
HOTKEY_OVERRIDE_CONTROL_NAME: "管理熱鍵覆蓋",
|
||||
HOTKEY_OVERRIDE_DESC:
|
||||
`一些 Excalidraw 的熱鍵,如 ${labelCTRL()}+Enter 用於編輯文字,或 ${labelCTRL()}+K 用於建立元素連結,` +
|
||||
"與 Obsidian 的熱鍵設定衝突。您在下面新增的熱鍵組合將在使用 Excalidraw 時覆蓋 Obsidian 的熱鍵設定," +
|
||||
`因此如果您希望在 Excalidraw 中預設“編組”,而不是“檢視關係圖譜”(核心外掛 - 關係圖譜),您可以新增 ${labelCTRL()}+G。`,
|
||||
THEME_HEAD: "主題和樣式",
|
||||
THEME_DESC:
|
||||
"控制介面樣式、繪圖和嵌入主題、開啟模式以及行動裝置安全區域間距。",
|
||||
ZOOM_AND_PAN_HEAD: "縮放和平移",
|
||||
ZOOM_AND_PAN_DESC:
|
||||
"設定滑鼠、觸控、開啟、調整大小和縮放範圍行為。",
|
||||
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "右鍵拖動平移",
|
||||
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC:
|
||||
"右鍵點選並拖動來平移繪圖(和線上白板工具 Miro 類似)。按 'm' 鍵開啟上下文選單。",
|
||||
@@ -762,7 +816,9 @@ export default {
|
||||
ZOOM_MAX_DESC:
|
||||
"繪圖放大的極限。預設:3000%。通常無需修改,考慮完整性而提供。",
|
||||
PEN_HEAD: "手寫筆",
|
||||
PEN_DESC: "設定自動手寫筆模式、觸控手勢、橡皮擦和自由繪製十字線。",
|
||||
GRID_HEAD: "網格",
|
||||
GRID_DESC: "設定網格方向、自動或自訂顏色以及不透明度。",
|
||||
GRID_DYNAMIC_COLOR_NAME: "動態網格顏色",
|
||||
GRID_DYNAMIC_COLOR_DESC:
|
||||
"<b>開啟:</b>更改網格顏色以匹配繪圖顏色。<br><b>關閉:</b>將以下顏色用作網格顏色。",
|
||||
@@ -775,6 +831,7 @@ export default {
|
||||
GRID_HORIZONTAL: "渲染水平網格",
|
||||
GRID_VERTICAL: "渲染垂直網格",
|
||||
LASER_HEAD: "雷射筆工具(更多工具 > 雷射筆)",
|
||||
LASER_DESC: "設定雷射筆顏色及其軌跡淡出的速度和長度。",
|
||||
LASER_COLOR: "雷射筆顏色",
|
||||
LASER_DECAY_TIME_NAME: "雷射筆消失時間",
|
||||
LASER_DECAY_TIME_DESC: "單位是毫秒,預設 1000(即 1 秒)。",
|
||||
@@ -793,6 +850,20 @@ export default {
|
||||
"連結的原始檔被重新命名時,繪圖中相應的 <code>[[內部連結]]</code> 也會同步更新。" +
|
||||
"若您不願繪圖中的連結外觀因此而變化,可使用 <code>[[內部連結|別名]]</code>。",
|
||||
DRAG_MODIFIER_NAME: "修飾鍵",
|
||||
DRAG_MODIFIER_GROUP_DESC:
|
||||
"設定連結開啟手勢,以及點擊和拖放操作的平台特定修飾鍵組合。",
|
||||
LINK_OPENING_GESTURES_HEAD: "連結開啟手勢",
|
||||
LINK_OPENING_GESTURES_DESC:
|
||||
"設定嵌入繪圖和檢視模式中的長按延遲與雙擊開啟連結。",
|
||||
WEB_BROWSER_DRAG_ACTION_DESC:
|
||||
"選擇從網頁瀏覽器拖入連結、圖片、匯入項目和嵌入內容時的修飾鍵組合。",
|
||||
LOCAL_FILE_DRAG_ACTION_DESC:
|
||||
"選擇從作業系統拖入連結、圖片、匯入項目和嵌入內容時的修飾鍵組合。",
|
||||
INTERNAL_DRAG_ACTION_DESC:
|
||||
"選擇在 Obsidian 內拖動連結、圖片、完整尺寸圖片和嵌入內容時的修飾鍵組合。",
|
||||
PANE_TARGET_DESC: "選擇決定點擊連結開啟位置的修飾鍵組合。",
|
||||
MODIFIER_KEY_USAGE_NAME: "設定修飾鍵",
|
||||
MODIFIER_KEY_COMBINATIONS: "修飾鍵組合",
|
||||
DRAG_MODIFIER_DESC:
|
||||
`在您按住點選連結或拖動元素時,可以觸發某些行為。您可以為這些行為新增修飾鍵。` +
|
||||
`Excalidraw 不會檢查您的設定是否合理,因此請謹慎設定,避免衝突。` +
|
||||
@@ -888,6 +959,20 @@ export default {
|
||||
"拖動連結到 Excalidraw 時,使用 <code>http" +
|
||||
"s://noembed" +
|
||||
".com/embed?url=</code> 來獲取 HTTPS 頁面標題。",
|
||||
LINK_BEHAVIOR_HEAD: "連結行為",
|
||||
LINK_BEHAVIOR_DESC:
|
||||
"設定連結同步、相關連結、懸停預覽、點擊處理和網頁標題查詢。",
|
||||
LINK_USAGE_NAME: "在 Excalidraw 中使用連結",
|
||||
LINK_OPENING_HEAD: "窗格和分頁行為",
|
||||
LINK_OPENING_DESC:
|
||||
"選擇連結是否重複使用、聚焦或切換窗格、分頁和主要工作區。",
|
||||
LINK_APPEARANCE_HEAD: "連結外觀",
|
||||
LINK_APPEARANCE_DESC: "設定連結顯示時使用的括號、前綴、圖示和不透明度。",
|
||||
TODO_HEAD: "待辦事項",
|
||||
TODO_GROUP_DESC: "設定待辦事項解析以及未完成和已完成任務使用的圖示。",
|
||||
TRANSCLUSION_HEAD: "文字嵌入",
|
||||
TRANSCLUSION_DESC:
|
||||
"設定嵌入 Markdown 文字的字元限制、換行和引用符號清理。",
|
||||
PDF_TO_IMAGE: "以影像形式嵌入到繪圖中的 PDF",
|
||||
PDF_TO_IMAGE_SCALE_NAME: "解析度",
|
||||
PDF_TO_IMAGE_SCALE_DESC:
|
||||
@@ -897,8 +982,13 @@ export default {
|
||||
EMBED_TOEXCALIDRAW_DESC:
|
||||
"包括:以影像形式嵌入到繪圖中的 PDF、以互動或影像形式嵌入到繪圖中的 Markdown 文件等。",
|
||||
MD_HEAD: "以影像形式嵌入到繪圖中的 Markdown 文件(MD-Embed)",
|
||||
MD_GROUP_DESC:
|
||||
"設定以影像呈現的 Markdown 檔案之尺寸、字型、顏色、邊框和 CSS。",
|
||||
MD_EMBED_CUSTOMDATA_HEAD_NAME:
|
||||
"以互動形式嵌入到繪圖中的 Markdown 文件(MD-Embeddable)",
|
||||
MD_EMBED_CUSTOMDATA_GROUP_DESC:
|
||||
"設定未來互動式 Markdown 嵌入的編輯方式和預設外觀。",
|
||||
MD_EMBED_DEFAULTS_CONTROL_NAME: "互動式 Markdown 預設外觀",
|
||||
MD_EMBED_CUSTOMDATA_HEAD_DESC: `以下設定只會影響以後的嵌入。已存在的嵌入保持不變。嵌入框的主題設定位於“介面 & 行為”部分。`,
|
||||
MD_EMBED_SINGLECLICK_EDIT_NAME: "單擊編輯嵌入的 Markdown",
|
||||
MD_EMBED_SINGLECLICK_EDIT_DESC:
|
||||
@@ -938,12 +1028,17 @@ export default {
|
||||
EMBED_HEAD: "嵌入到 Markdown 文件中的繪圖",
|
||||
EMBED_DESC: `包括:嵌入到 Markdown 文件中的繪圖的預覽圖型別(SVG、PNG)、原始檔型別(Excalidraw、SVG、PNG)、快取、影像尺寸、影像主題,以及嵌入的語法等。
|
||||
此外,還有自動匯出 SVG 或 PNG 檔案並保持與繪圖檔案狀態同步的設定。`,
|
||||
EMBED_PREVIEW_LINKS_HEAD: "預覽、連結與 Canvas",
|
||||
EMBED_PREVIEW_LINKS_DESC:
|
||||
"選擇預覽和插入檔案的格式、來源連結行為、預留影像及沉浸式 Canvas 嵌入。",
|
||||
EMBED_CANVAS: "Obsidian 白板支援",
|
||||
EMBED_CANVAS_NAME: "沉浸式嵌入",
|
||||
EMBED_CANVAS_DESC:
|
||||
"當嵌入繪圖到 Obsidian 白板中時,隱藏節點的邊界和背景。" +
|
||||
"注意:如果想要背景完全透明,您依然需要設定匯出背景為透明(關閉“匯出圖片包含背景”)。",
|
||||
EMBED_CACHING: "影像快取和渲染最佳化",
|
||||
EMBED_CACHING_DESC:
|
||||
"調整平行渲染和本機圖片快取、清除快取圖片或備份,並可重用已匯出的預覽。",
|
||||
RENDERING_CONCURRENCY_NAME: "影像渲染併發性",
|
||||
RENDERING_CONCURRENCY_DESC:
|
||||
"用於影像渲染的並行工作執行緒數。增加該值可以加快渲染速度,但可能會減慢系統其他部分的執行速度。" +
|
||||
@@ -956,8 +1051,13 @@ export default {
|
||||
"實際影響在於 Obsidian 內部的本地磁碟或瀏覽器儲存佔用。在手機以及瀏覽器儲存配額較緊、剩餘磁碟空間有限的桌面裝置上需要留意。<br><br>" +
|
||||
"較小的值會更快回收本地快取空間,但可能導致 PDF 和嵌入繪圖更頻繁地重新渲染。較大的值會保留更久的快取,以換取更快的載入速度。",
|
||||
EXPORT_SUBHEAD: "匯出",
|
||||
EXPORT_SUBHEAD_DESC:
|
||||
"設定 PDF 渲染、匯出的場景資料、影像尺寸、主題與背景、PDF 預設值及自動 PNG/SVG 副本。",
|
||||
EMBED_SIZING: "影像尺寸",
|
||||
EMBED_SIZING_DESC: "設定嵌入影像的預設尺寸、PNG 縮放比例和匯出邊距。",
|
||||
EMBED_THEME_BACKGROUND: "影像的主題和背景色",
|
||||
EMBED_THEME_BACKGROUND_DESC:
|
||||
"選擇匯出影像的背景和主題,以及預覽是否跟隨 Obsidian 主題。",
|
||||
EMBED_IMAGE_CACHE_NAME: "為嵌入到 Markdown 文件中的繪圖建立預覽圖快取",
|
||||
EMBED_IMAGE_CACHE_DESC:
|
||||
"可提高下次嵌入的速度。" +
|
||||
@@ -1037,7 +1137,18 @@ export default {
|
||||
"在匯出圖片中嵌入 Excalidraw 場景。可以在其 frontmatter 中新增如 <code>excalidraw-export-embed-scene: true/false</code> 的鍵值對來覆蓋該項。" +
|
||||
"該項僅在您下次(重新)開啟繪圖時生效。",
|
||||
PDF_EXPORT_SETTINGS: "PDF 匯出設定",
|
||||
PDF_EXPORT_SETTINGS_DESC:
|
||||
"選擇預設 PDF 頁面大小、方向、分頁、邊距、紙張顏色和對齊方式。",
|
||||
PDF_EXPORT_DEFAULTS_CONTROL_NAME: "預設 PDF 匯出配置",
|
||||
EXPORT_HEAD: "匯出設定",
|
||||
EXPORT_AUTOEXPORT_DESC:
|
||||
"保持匯出檔案同步,並自動建立 SVG、PNG、淺色和深色版本。",
|
||||
SETTINGS_NAVIGATION_OPEN: "開啟",
|
||||
SETTINGS_BREADCRUMB_ARIA: "設定路徑",
|
||||
SETTINGS_RELATED_AUTOEXPORT_DESC:
|
||||
"啟用自動 PNG 或 SVG 副本,使這些格式可在插入檔案類型下拉清單中選擇。",
|
||||
SETTINGS_RELATED_EMBED_TYPE_DESC:
|
||||
"選擇在文件中嵌入繪圖時插入 Excalidraw、PNG 還是 SVG。",
|
||||
EXPORT_SYNC_NAME: "保持 SVG/PNG 檔名與繪圖檔案同步",
|
||||
EXPORT_SYNC_DESC:
|
||||
"開啟後,當繪圖檔案被重新命名時,外掛將同步更新同文件夾下的同名 .SVG 和 .PNG 檔案。" +
|
||||
@@ -1110,8 +1221,11 @@ export default {
|
||||
CUSTOM_PEN_DESC:
|
||||
"在繪圖上的 Obsidian 選單按鈕旁邊切換自定義畫筆。長按(雙擊)畫筆按鈕可以修改其樣式。",
|
||||
EXPERIMENTAL_HEAD: "雜項",
|
||||
EXPERIMENTAL_DESC: `包括:預設的 LaTeX 公式,欄位建議,繪圖檔案的型別識別符號,OCR 等。`,
|
||||
EXPERIMENTAL_DESC:
|
||||
"設定 LaTeX 預設值、檔案類型標記、即時預覽行為、屬性建議,以及實驗性的 Taskbone OCR 整合。",
|
||||
EA_HEAD: "Excalidraw 自動化",
|
||||
EA_GROUP_DESC:
|
||||
"設定 Excalidraw Automate 指令碼、啟動與自動啟動行為、命令連結,以及已安裝指令碼提供的設定。",
|
||||
EA_DESC:
|
||||
`ExcalidrawAutomate 是用於 Excalidraw 自動化指令碼的 API,但是目前說明文件還不夠完善,` +
|
||||
`建議閱讀 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_API_EXCALIDRAWAUTOMATE_D_TS}">ExcalidrawAutomate.d.ts</a> 檔案原始碼,` +
|
||||
@@ -1122,6 +1236,33 @@ export default {
|
||||
FIELD_SUGGESTER_DESC:
|
||||
"開啟後,當您在編輯器中輸入 <code>excalidraw-</code> 或者 <code>ea.</code> 時,會彈出一個帶有函式說明的自動補全提示選單。<br>" +
|
||||
"該功能借鑑了 Breadcrumbs 和 Templater 外掛。",
|
||||
ALLOW_JS_FILES_NAME: "從 Scripts 資料夾載入 JavaScript 檔案",
|
||||
ALLOW_JS_FILES_DESC:
|
||||
"啟用後,Excalidraw Automate 會監視並執行 Scripts 資料夾中的 <code>.js</code> 檔案,也允許使用 <code>.js</code> 啟動指令碼。" +
|
||||
"預設情況下,Obsidian Sync 不會同步非 Markdown 檔案,Obsidian 不會開啟 <code>.js</code> 檔案進行編輯,檔案總管也會隱藏它們。需要時請在 Obsidian 中啟用<b>同步所有其他檔案類型</b>和<b>顯示所有檔案類型</b>。如果存在同名的 <code>.md</code> 和 <code>.js</code> 指令碼,將使用 Markdown 檔案。",
|
||||
STORE_SCRIPTS_AS_JS_NAME: "將下載的指令碼儲存為",
|
||||
STORE_SCRIPTS_AS_JS_DESC:
|
||||
"選擇指令碼庫新下載與更新在本機使用的檔案類型。無論遠端來源是 <code>.md</code> 或 <code>.js</code>,都會使用此設定。",
|
||||
SCRIPT_FILE_EXTENSION_MARKDOWN: "Markdown (.md)",
|
||||
SCRIPT_FILE_EXTENSION_JAVASCRIPT: "JavaScript (.js)",
|
||||
MIGRATE_SCRIPT_FILES_NAME: "遷移現有指令碼檔案",
|
||||
MIGRATE_SCRIPTS_TO_JS_BUTTON: "將現有指令碼遷移為 .js",
|
||||
MIGRATE_SCRIPTS_TO_MD_BUTTON: "將現有指令碼遷移為 .md",
|
||||
MIGRATE_SCRIPT_FILES_STATUS:
|
||||
"有 {eligible} 個指令碼檔案可遷移為 {extension}。{skipped}",
|
||||
MIGRATE_SCRIPT_FILES_CONFIRM:
|
||||
"繼續前請先備份儲存庫。<br><br><b>{count}</b> 個指令碼檔案將重新命名為 <code>{extension}</code>,釘選指令碼的路徑也會更新。{startup} {skipped}",
|
||||
MIGRATE_SCRIPT_FILES_STARTUP_INCLUDED:
|
||||
"已設定的啟動指令碼及其設定也會更新。",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED:
|
||||
"有 {count} 對同名 .md/.js 檔案不會被遷移。",
|
||||
MIGRATE_SCRIPT_FILES_SKIPPED_DETAILS:
|
||||
"因目標檔案已存在,已略過 {count} 個指令碼檔案:\n{files}",
|
||||
MIGRATE_SCRIPT_FILES_NONE: "找不到可遷移的指令碼檔案。",
|
||||
MIGRATE_SCRIPT_FILES_COMPLETE:
|
||||
"已將 {count} 個指令碼檔案遷移為 {extension}。",
|
||||
MIGRATE_SCRIPT_FILES_FAILED:
|
||||
"無法遷移指令碼檔案。已盡可能回復完成的重新命名。",
|
||||
ENABLE_ONLOAD_SCRIPTS_NAME: "載入期指令碼(onload)",
|
||||
ENABLE_ONLOAD_SCRIPTS_CONFIRMATION:
|
||||
"此檔案包含 <code>excalidraw-onload-script</code>。是否啟用載入期指令碼?",
|
||||
@@ -1131,6 +1272,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:
|
||||
"你之後可以在命令選擇區(「自動啟動指令碼」)或設定 → Excalidraw 自動化 → 自動啟動指令碼中變更此設定。",
|
||||
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 命令。是否啟用命令連結?",
|
||||
@@ -1141,9 +1294,10 @@ export default {
|
||||
"如果你開啟未知來源的繪圖,這會帶來風險:惡意繪圖可以讓一次普通點選觸發高許可權命令。" +
|
||||
"只有在你信任該檔案及其來源時才啟用此功能。",
|
||||
STARTUP_SCRIPT_NAME: "啟動期指令碼(startup)",
|
||||
STARTUP_SCRIPT_JS_DISABLED:
|
||||
"JavaScript 啟動指令碼已停用。請先在 Excalidraw Automate 設定中啟用 JavaScript 檔案。",
|
||||
STARTUP_SCRIPT_DESC:
|
||||
"外掛啟動時將自動執行該指令碼。可用於設定 Excalidraw 自動化鉤子。" +
|
||||
"該指令碼是包含 javascript 程式碼的 Markdown 檔案。",
|
||||
"外掛啟動時將自動執行該指令碼,可用於設定 Excalidraw Automate 鉤子。沒有副檔名的路徑使用 Markdown 檔案;啟用 JavaScript 檔案載入後可使用 <code>.js</code> 檔案。",
|
||||
STARTUP_SCRIPT_BUTTON_CREATE: "建立啟動期指令碼",
|
||||
STARTUP_SCRIPT_BUTTON_OPEN: "開啟啟動期指令碼",
|
||||
FILETYPE_NAME: "在檔案瀏覽器中為 excalidraw.md 檔案新增型別識別符號(如 ✏️)",
|
||||
@@ -1184,6 +1338,8 @@ export default {
|
||||
"為了獲得最佳效能,建議使用 .woff2 檔案,因為當匯出 SVG 格式的圖片時,Excalidraw 只會編碼必要的字形。" +
|
||||
`其他字型格式將在匯出檔案中嵌入整個字型,可能會導致檔案大小顯著增加。<b>譯者注:</b>可在 <a href="${URLs.WANGCHUJIANG_COM_FREE_FONT}" target='_blank'>Free Font</a> 獲取免費商用中文手寫字型。`,
|
||||
OFFLINE_CJK_NAME: "離線 CJK 字型支援",
|
||||
OFFLINE_CJK_GROUP_DESC:
|
||||
"下載並按需預先載入中文、日文和韓文字型,讓 Excalidraw 在沒有網際網路連線時也能顯示這些字型。",
|
||||
OFFLINE_CJK_DESC: `<strong>該項需要重啟 Obsidian 才能生效。</strong><br>
|
||||
Excalidraw.com 提供手寫風格的 CJK 字型。預設情況下,這些字型不會包含在外掛本地,而是從網際網路獲取。
|
||||
如果您希望 Excalidraw 完全本地化,以便在沒有網際網路連線的情況下使用,可以從 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RAW_REFS_HEADS_MASTER_ASSETS_EXCALIDRAW_FONTS_ZIP}" target="_blank">GitHub 下載所需的字型檔案</a>。
|
||||
@@ -1200,6 +1356,8 @@ export default {
|
||||
SCRIPT_SETTINGS_DESC:
|
||||
"有些 Excalidraw 自動化指令碼包含設定項,當執行這些指令碼時,它們會在該列表下新增設定項。",
|
||||
TASKBONE_HEAD: "Taskbone OCR(光學符號識別)",
|
||||
TASKBONE_GROUP_DESC:
|
||||
"設定選用的 Taskbone 線上 OCR 服務,從繪圖與影像中擷取可搜尋文字。",
|
||||
TASKBONE_DESC:
|
||||
"這是一個將 OCR 融入 Excalidraw 的實驗性功能。請注意,Taskbone 是一項獨立的外部服務,而不是由 Excalidraw 或 obsidian-excalidraw-plugin 專案提供的。" +
|
||||
"OCR 能夠對繪圖上用自由畫筆工具寫下的塗鴉或者嵌入的影像進行文字識別,並將識別出來的文字寫入繪圖檔案的 frontmatter,同時複製到剪貼簿。" +
|
||||
@@ -1370,6 +1528,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 +1554,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 +1796,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,165 @@
|
||||
type PendingBackup = {
|
||||
data: string;
|
||||
};
|
||||
|
||||
type BackupWriteState = {
|
||||
timer: number | null;
|
||||
inFlight: Promise<void> | null;
|
||||
pending: PendingBackup | null;
|
||||
};
|
||||
|
||||
type BackupPersistenceQueueOptions = {
|
||||
ownerWindow: Window;
|
||||
write: (filepath: string, data: string) => Promise<void>;
|
||||
onError?: (error: unknown, stage: "write") => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Coalesces plugin-global drawing backups by vault path.
|
||||
*
|
||||
* @remarks
|
||||
* Each path owns at most one IndexedDB write and one latest trailing payload.
|
||||
* The timer belongs to the main application window because persistent plugin
|
||||
* storage is shared by main and popout views.
|
||||
*/
|
||||
export class BackupPersistenceQueue {
|
||||
private readonly ownerWindow: Window;
|
||||
private readonly write: BackupPersistenceQueueOptions["write"];
|
||||
private readonly onError?: BackupPersistenceQueueOptions["onError"];
|
||||
private readonly writes = new Map<string, BackupWriteState>();
|
||||
|
||||
constructor(options: BackupPersistenceQueueOptions) {
|
||||
this.ownerWindow = options.ownerWindow;
|
||||
this.write = options.write;
|
||||
this.onError = options.onError;
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules the latest payload for a path.
|
||||
*
|
||||
* @returns `true` when an older pending payload was replaced or the new
|
||||
* payload was coalesced behind an active write.
|
||||
*/
|
||||
public schedule(filepath: string, data: string, delayMs: number): boolean {
|
||||
let state = this.writes.get(filepath);
|
||||
if (!state) {
|
||||
state = { timer: null, inFlight: null, pending: null };
|
||||
this.writes.set(filepath, state);
|
||||
}
|
||||
|
||||
const coalesced = state.pending !== null || state.inFlight !== null;
|
||||
state.pending = { data };
|
||||
this.clearTimer(state);
|
||||
if (state.inFlight === null) {
|
||||
this.scheduleDrain(filepath, state, delayMs);
|
||||
}
|
||||
return coalesced;
|
||||
}
|
||||
|
||||
/** Writes all currently pending data for one path without the normal delay. */
|
||||
public async flush(filepath: string): Promise<void> {
|
||||
const state = this.writes.get(filepath);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.clearTimer(state);
|
||||
while (this.writes.get(filepath) === state) {
|
||||
this.clearTimer(state);
|
||||
if (state.inFlight !== null) {
|
||||
try {
|
||||
await state.inFlight;
|
||||
} catch {
|
||||
// The owning drain reports the write failure and releases state.
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (state.pending === null) {
|
||||
break;
|
||||
}
|
||||
await this.drain(filepath, state, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/** Cancels queued data and waits for an already-active write to settle. */
|
||||
public async cancel(filepath: string): Promise<void> {
|
||||
const state = this.writes.get(filepath);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
this.clearTimer(state);
|
||||
state.pending = null;
|
||||
this.writes.delete(filepath);
|
||||
if (state.inFlight !== null) {
|
||||
try {
|
||||
await state.inFlight;
|
||||
} catch {
|
||||
// The owning drain reports the write failure; cancellation still wins.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Cancels every queued backup before the backup store is cleared. */
|
||||
public async cancelAll(): Promise<void> {
|
||||
await Promise.all(
|
||||
Array.from(this.writes.keys(), (filepath) => this.cancel(filepath)),
|
||||
);
|
||||
}
|
||||
|
||||
/** Drops timers and references during plugin unload without starting writes. */
|
||||
public destroy(): void {
|
||||
this.writes.forEach((state) => this.clearTimer(state));
|
||||
this.writes.clear();
|
||||
}
|
||||
|
||||
private clearTimer(state: BackupWriteState): void {
|
||||
if (state.timer !== null) {
|
||||
this.ownerWindow.clearTimeout(state.timer);
|
||||
state.timer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private scheduleDrain(
|
||||
filepath: string,
|
||||
state: BackupWriteState,
|
||||
delayMs: number,
|
||||
): void {
|
||||
state.timer = this.ownerWindow.setTimeout(() => {
|
||||
state.timer = null;
|
||||
void this.drain(filepath, state, delayMs);
|
||||
}, delayMs);
|
||||
}
|
||||
|
||||
private async drain(
|
||||
filepath: string,
|
||||
state: BackupWriteState,
|
||||
trailingDelayMs: number,
|
||||
): Promise<void> {
|
||||
if (
|
||||
this.writes.get(filepath) !== state ||
|
||||
state.inFlight !== null ||
|
||||
state.pending === null
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pending = state.pending;
|
||||
state.pending = null;
|
||||
const write = this.write(filepath, pending.data);
|
||||
state.inFlight = write;
|
||||
try {
|
||||
await write;
|
||||
} catch (error: unknown) {
|
||||
this.onError?.(error, "write");
|
||||
} finally {
|
||||
if (this.writes.get(filepath) === state) {
|
||||
state.inFlight = null;
|
||||
if (state.pending !== null) {
|
||||
this.scheduleDrain(filepath, state, trailingDelayMs);
|
||||
} else {
|
||||
this.writes.delete(filepath);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,7 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
|
||||
.setValue(this.mdCustomData.filenameVisible)
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.filenameVisible = value;
|
||||
this.update();
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -72,6 +73,7 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
|
||||
.setValue(this.mdCustomData.propertiesVisible ?? true)
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.propertiesVisible = value;
|
||||
this.update();
|
||||
});
|
||||
if (!this.isFullFile || isGlobalHidden) {
|
||||
toggle.setDisabled(true);
|
||||
@@ -91,6 +93,7 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
|
||||
.setValue(!!this.mdCustomData.lockedReadingMode)
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.lockedReadingMode = value;
|
||||
this.update();
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -120,6 +123,7 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
|
||||
if (value) {
|
||||
hideElement(bgSetting.settingEl);
|
||||
if (this.mdCustomData.backgroundMatchCanvas) {
|
||||
this.mdCustomData.backgroundMatchCanvas = false;
|
||||
bgMatchCanvasToggle.setValue(false);
|
||||
}
|
||||
} else if (!this.mdCustomData.backgroundMatchCanvas) {
|
||||
@@ -140,6 +144,7 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
|
||||
if (value) {
|
||||
hideElement(bgSetting.settingEl);
|
||||
if (this.mdCustomData.backgroundMatchElement) {
|
||||
this.mdCustomData.backgroundMatchElement = false;
|
||||
bgMatchElementToggle.setValue(false);
|
||||
}
|
||||
} else if (!this.mdCustomData.backgroundMatchElement) {
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -18,18 +18,53 @@ 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>
|
||||
`,
|
||||
"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.
|
||||
## New
|
||||
- On Obsidian 1.13 and newer, Excalidraw now uses Obsidian's searchable, multi-page settings. Settings are organized into clearer sections with breadcrumbs, compact help links, and clickable links between related options.
|
||||
- Prefer the previous experience? Turn off **Use searchable settings** at the top of Excalidraw settings and restart Obsidian. Older Obsidian versions continue using the legacy single-page layout automatically.
|
||||
- Settings exposed by installed Excalidraw Automate scripts have moved to **Excalidraw Automate → Settings for installed scripts** and update when a script adds or changes its settings.
|
||||
- Excalidraw Automate can optionally load and monitor JavaScript (\`.js\`) files in the Scripts folder, use an explicit \`.js\` startup script, and store Script Library downloads as either Markdown or JavaScript. Existing scripts can be moved between the two formats while updating startup and pinned-script paths. [#2901](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2901)
|
||||
- Markdown notes created from unresolved links in a drawing now follow Obsidian's **Default location for new notes** setting. [#2916](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2916)
|
||||
|
||||
## New from Excalidraw.com
|
||||
- Improved bucket tool and eyedropper support [#11849](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11849)
|
||||
- Improved bucket tool and eyedropper support. [#11849](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11849)
|
||||
- Lasso selection now respects box selection mode: contain or overlap. [#11862](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11862)
|
||||
- Customize color-picker top picks by dragging colors onto the strip; right-click the strip to reset it. [#11872](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11872)
|
||||
|
||||
## Fixed
|
||||
- Moving a dirty drawing out of a popout window now safely transfers and persists its latest edits from the replacement main-window view.
|
||||
- Opening the command palette or another Obsidian modal reliably saves dirty drawings, while inline link suggestions no longer trigger a save that can end text editing.
|
||||
- Converting a legacy ".excalidraw" drawing now persists its embedded images as vault attachments during conversion, before the source file can be removed. [#2898](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2898)
|
||||
- Entering text editing no longer scans and sorts the entire vault for link suggestions; file-link candidates are loaded only after typing \`[[\`. [#2907](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2907)
|
||||
- Settings changes are saved promptly without collapsing sections or interrupting fast typing. Writes are serialized, and Excalidraw keeps a device-local recovery copy so an empty or corrupted synchronized **data.json** cannot silently erase a large settings configuration.
|
||||
- Interdependent settings now initialize and refresh consistently, including TODO icons, auto-export formats, Taskbone credentials, filename previews, and custom grid colors. Built-in font previews also use the correct typeface in secondary Obsidian windows.
|
||||
- Applying a rendering-related setting no longer resets the live zoom and scroll position of an open drawing. New configurations use ☑ as the completed-TODO marker.
|
||||
- Interactive Markdown embed defaults now save filename, properties, locked-reading-mode, and background-source changes reliably.
|
||||
- The color palette uses the available height, keeps its native picker aligned, remembers customized top picks after reload, and updates popover theming immediately after a canvas background change.
|
||||
- Text-to-diagram chat history is visible again, so saved chats can be restored or deleted.
|
||||
- Stencil-library JSON is now tab-indented for cleaner Git diffs. [#2883](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2883)
|
||||
|
||||
## Maintenance
|
||||
- This is one of the Plugin's largest internal maintenance releases. The settings system, persistence pipeline, plugin lifecycle, runtime packaging, and several major managers were reorganized into clearer, independently maintained components. The visible workflow remains familiar, but the foundation is substantially safer for future features and fixes.
|
||||
- The embedded Excalidraw runtime now uses a modern ESM-source build and React 19 instead of the retired UMD pipeline. Offline use and popout windows remain supported; the Assistant UI font is bundled locally and Mermaid still loads on demand through Excalidraw Extras.
|
||||
- Drawings with many cached embedded files load more efficiently by avoiding redundant cache rewrites, SVG reconstruction, image measurement, hashing, and normalization. Cached and direct images can appear before slower generated drawings, while drawing backups remain protected.
|
||||
- Removed unused code and the obsolete Draw.io/Diagram integration, and retired the non-functional Create DrawIO file script.
|
||||
|
||||
## New in Excalidraw Automate
|
||||
- \`setView(null)\` now explicitly clears \`ea.targetView\`. Use \`setView()\` or \`setView("auto")\` when you want EA to select a sensible default drawing.
|
||||
- Scripts can register custom buttons in the selected-element context menu:
|
||||
\`\`\`ts
|
||||
registerElementActionProvider(getActions: (element: ExcalidrawElement) => readonly {id: string, title: string, icon: string, action: () => void}[]): (() => void) | null;
|
||||
\`\`\`
|
||||
- Scripts can request permission to run automatically whenever an Excalidraw view opens. Manage permissions with the **Autostart scripts** command or under Excalidraw Automate settings:
|
||||
\`\`\`ts
|
||||
registerAutostart(message?: string): Promise<"allow" | "deny" | "pending">;
|
||||
\`\`\`
|
||||
- Pass an optional message to explain what the script does during autostart. It appears between the permission question and the settings hint.
|
||||
- Scripts can release listeners, timers, observers, and other external resources with EA-owned cleanup:
|
||||
\`\`\`ts
|
||||
registerCleanup(cleanup: () => void): () => void;
|
||||
\`\`\`
|
||||
- Scripts can distinguish \`manual\`, \`plugin-startup\`, \`view-autostart\`, \`sidepanel-restore\`, \`sidepanel-reload\`, and \`drawing-onload\` execution through \`utils.executionSource\`. Compilation caching is transparent and does not retain script runtime state.
|
||||
`,
|
||||
"2.26.4": `
|
||||
## Fixed
|
||||
|
||||
@@ -8,17 +8,26 @@ import {
|
||||
} from "src/utils/modifierkeyHelper";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
|
||||
type ModifierKeyCategories = Partial<{
|
||||
[modifierSetType in ModifierSetType]: string;
|
||||
}>;
|
||||
|
||||
const CATEGORIES: ModifierKeyCategories = {
|
||||
const CATEGORIES: Record<ModifierSetType, string> = {
|
||||
WebBrowserDragAction: t("WEB_BROWSER_DRAG_ACTION"),
|
||||
LocalFileDragAction: t("LOCAL_FILE_DRAG_ACTION"),
|
||||
InternalDragAction: t("INTERNAL_DRAG_ACTION"),
|
||||
LinkClickAction: t("PANE_TARGET"),
|
||||
};
|
||||
|
||||
/** Modifier-key categories rendered by the settings component. */
|
||||
export const MODIFIER_KEY_CATEGORIES = [
|
||||
"WebBrowserDragAction",
|
||||
"LocalFileDragAction",
|
||||
"InternalDragAction",
|
||||
"LinkClickAction",
|
||||
] as const satisfies readonly ModifierSetType[];
|
||||
|
||||
/** Returns the localized heading for one modifier-key category. */
|
||||
export const getModifierKeyCategoryName = (
|
||||
modifierSetType: ModifierSetType,
|
||||
): string => CATEGORIES[modifierSetType];
|
||||
|
||||
export class ModifierKeySettingsComponent {
|
||||
private isMacOS: boolean;
|
||||
|
||||
@@ -28,12 +37,22 @@ export class ModifierKeySettingsComponent {
|
||||
Mac: Record<string, ModifierKeySet>;
|
||||
Win: Record<string, ModifierKeySet>;
|
||||
},
|
||||
private update?: () => void,
|
||||
private update: () => void,
|
||||
) {
|
||||
this.isMacOS = DEVICE.isMacOS || DEVICE.isIOS;
|
||||
}
|
||||
|
||||
render() {
|
||||
render(): void {
|
||||
MODIFIER_KEY_CATEGORIES.forEach((modifierSetType) =>
|
||||
this.renderCategory(modifierSetType, true),
|
||||
);
|
||||
}
|
||||
|
||||
/** Renders one modifier-key category, optionally with its legacy fold. */
|
||||
renderCategory(
|
||||
modifierSetType: ModifierSetType,
|
||||
includeSummary: boolean,
|
||||
): void {
|
||||
const platform = this.isMacOS ? "Mac" : "Win";
|
||||
const modifierKeysConfig = this.modifierKeyConfig[platform];
|
||||
const tooltipMessages = modifierKeyTooltipMessages() as Record<
|
||||
@@ -41,102 +60,104 @@ export class ModifierKeySettingsComponent {
|
||||
Record<string, string>
|
||||
>;
|
||||
|
||||
Object.entries(CATEGORIES).forEach(([modifierSetType, label]) => {
|
||||
const detailsEl = this.contentEl.createEl("details");
|
||||
const detailsEl = includeSummary
|
||||
? this.contentEl.createEl("details")
|
||||
: this.contentEl;
|
||||
if (includeSummary) {
|
||||
detailsEl.createEl("summary", {
|
||||
text: label,
|
||||
text: getModifierKeyCategoryName(modifierSetType),
|
||||
cls: "excalidraw-setting-h4",
|
||||
});
|
||||
}
|
||||
|
||||
const modifierKeys = modifierKeysConfig[modifierSetType];
|
||||
detailsEl.createDiv({
|
||||
text:
|
||||
t("DEFAULT_ACTION_DESC") +
|
||||
(tooltipMessages[modifierSetType]?.[modifierKeys.defaultAction] ??
|
||||
""),
|
||||
cls: "setting-item-description",
|
||||
});
|
||||
// Ensure all LinkClickAction rules have ctrl_cmd enabled
|
||||
if (modifierSetType === "LinkClickAction") {
|
||||
let dirty = false;
|
||||
modifierKeys.rules.forEach((rule) => {
|
||||
if (!rule.ctrl_cmd) {
|
||||
rule.ctrl_cmd = true;
|
||||
dirty = true;
|
||||
}
|
||||
});
|
||||
if (dirty) {
|
||||
this.update?.();
|
||||
const modifierKeys = modifierKeysConfig[modifierSetType];
|
||||
detailsEl.createDiv({
|
||||
text:
|
||||
t("DEFAULT_ACTION_DESC") +
|
||||
(tooltipMessages[modifierSetType]?.[modifierKeys.defaultAction] ??
|
||||
""),
|
||||
cls: "setting-item-description",
|
||||
});
|
||||
// Ensure all LinkClickAction rules have ctrl_cmd enabled
|
||||
if (modifierSetType === "LinkClickAction") {
|
||||
let dirty = false;
|
||||
modifierKeys.rules.forEach((rule) => {
|
||||
if (!rule.ctrl_cmd) {
|
||||
rule.ctrl_cmd = true;
|
||||
dirty = true;
|
||||
}
|
||||
});
|
||||
if (dirty) {
|
||||
this.update();
|
||||
}
|
||||
}
|
||||
|
||||
// Column header row
|
||||
const headerSetting = new Setting(detailsEl);
|
||||
headerSetting.settingEl.addClass("modifier-key-header-row");
|
||||
headerSetting.infoEl.remove();
|
||||
[
|
||||
"SHIFT",
|
||||
this.isMacOS ? "CMD" : "CTRL",
|
||||
this.isMacOS ? "OPT" : "ALT",
|
||||
this.isMacOS ? "CTRL" : "META",
|
||||
].forEach((key) => {
|
||||
headerSetting.controlEl.createSpan({
|
||||
text: key,
|
||||
cls: "modifier-key-col-header",
|
||||
});
|
||||
// Column header row
|
||||
const headerSetting = new Setting(detailsEl);
|
||||
headerSetting.settingEl.addClass("modifier-key-header-row");
|
||||
headerSetting.infoEl.remove();
|
||||
[
|
||||
"SHIFT",
|
||||
this.isMacOS ? "CMD" : "CTRL",
|
||||
this.isMacOS ? "OPT" : "ALT",
|
||||
this.isMacOS ? "CTRL" : "META",
|
||||
].forEach((key) => {
|
||||
headerSetting.controlEl.createSpan({
|
||||
text: key,
|
||||
cls: "modifier-key-col-header",
|
||||
});
|
||||
});
|
||||
|
||||
modifierKeys.rules.forEach((rule) => {
|
||||
const setting = new Setting(detailsEl).setName(
|
||||
tooltipMessages[modifierSetType]?.[rule.result],
|
||||
);
|
||||
|
||||
setting.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(rule.shift)
|
||||
.setTooltip("SHIFT")
|
||||
.onChange((value) => {
|
||||
rule.shift = value;
|
||||
this.update();
|
||||
}),
|
||||
);
|
||||
setting.addToggle((toggle) => {
|
||||
const isLinkClick = modifierSetType === "LinkClickAction";
|
||||
toggle
|
||||
.setValue(isLinkClick ? true : rule.ctrl_cmd)
|
||||
.setTooltip(this.isMacOS ? "CMD" : "CTRL")
|
||||
.onChange((value) => {
|
||||
rule.ctrl_cmd = value;
|
||||
this.update();
|
||||
});
|
||||
if (isLinkClick || this.isMacOS) {
|
||||
// CMD is always required for link-click actions (Excalidraw detects
|
||||
// the click via CMD being held). On macOS, CMD is also reserved for
|
||||
// non-link-click actions.
|
||||
toggle.setDisabled(true);
|
||||
setStyle(toggle.toggleEl, { opacity: "0.5" });
|
||||
}
|
||||
});
|
||||
|
||||
Object.entries(modifierKeys.rules).forEach(([_, rule]) => {
|
||||
const setting = new Setting(detailsEl).setName(
|
||||
tooltipMessages[modifierSetType]?.[rule.result],
|
||||
);
|
||||
|
||||
setting.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(rule.shift)
|
||||
.setTooltip("SHIFT")
|
||||
.onChange((value) => {
|
||||
rule.shift = value;
|
||||
this.update();
|
||||
}),
|
||||
);
|
||||
setting.addToggle((toggle) => {
|
||||
const isLinkClick = modifierSetType === "LinkClickAction";
|
||||
toggle
|
||||
.setValue(isLinkClick ? true : rule.ctrl_cmd)
|
||||
.setTooltip(this.isMacOS ? "CMD" : "CTRL")
|
||||
.onChange((value) => {
|
||||
rule.ctrl_cmd = value;
|
||||
this.update();
|
||||
});
|
||||
if (isLinkClick || this.isMacOS) {
|
||||
// CMD is always required for link-click actions (Excalidraw detects
|
||||
// the click via CMD being held). On macOS, CMD is also reserved for
|
||||
// non-link-click actions.
|
||||
toggle.setDisabled(true);
|
||||
setStyle(toggle.toggleEl, { opacity: "0.5" });
|
||||
}
|
||||
});
|
||||
|
||||
setting.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(rule.alt_opt)
|
||||
.setTooltip(this.isMacOS ? "OPT" : "ALT")
|
||||
.onChange((value) => {
|
||||
rule.alt_opt = value;
|
||||
this.update();
|
||||
}),
|
||||
);
|
||||
setting.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(rule.meta_ctrl)
|
||||
.setTooltip(this.isMacOS ? "CTRL" : "META")
|
||||
.onChange((value) => {
|
||||
rule.meta_ctrl = value;
|
||||
this.update();
|
||||
}),
|
||||
);
|
||||
});
|
||||
setting.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(rule.alt_opt)
|
||||
.setTooltip(this.isMacOS ? "OPT" : "ALT")
|
||||
.onChange((value) => {
|
||||
rule.alt_opt = value;
|
||||
this.update();
|
||||
}),
|
||||
);
|
||||
setting.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(rule.meta_ctrl)
|
||||
.setTooltip(this.isMacOS ? "CTRL" : "META")
|
||||
.onChange((value) => {
|
||||
rule.meta_ctrl = value;
|
||||
this.update();
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
FuzzyMatch,
|
||||
FuzzySuggestModal,
|
||||
Instruction,
|
||||
normalizePath,
|
||||
TFile,
|
||||
Notice,
|
||||
TextAreaComponent,
|
||||
@@ -1096,6 +1097,7 @@ export class NewFileActions extends Modal {
|
||||
private openNewFile: boolean;
|
||||
private parentFile: TFile;
|
||||
private sourceElement: ExcalidrawElement;
|
||||
private followObsidianNewNoteLocation: boolean;
|
||||
|
||||
constructor({
|
||||
plugin,
|
||||
@@ -1105,6 +1107,7 @@ export class NewFileActions extends Modal {
|
||||
openNewFile = true,
|
||||
parentFile,
|
||||
sourceElement,
|
||||
followObsidianNewNoteLocation = false,
|
||||
}: {
|
||||
plugin: ExcalidrawPlugin;
|
||||
path: string;
|
||||
@@ -1113,6 +1116,7 @@ export class NewFileActions extends Modal {
|
||||
openNewFile?: boolean;
|
||||
parentFile?: TFile;
|
||||
sourceElement?: ExcalidrawElement;
|
||||
followObsidianNewNoteLocation?: boolean;
|
||||
}) {
|
||||
super(plugin.app);
|
||||
this.plugin = plugin;
|
||||
@@ -1122,6 +1126,7 @@ export class NewFileActions extends Modal {
|
||||
this.openNewFile = openNewFile;
|
||||
this.sourceElement = sourceElement;
|
||||
this.parentFile = parentFile ?? view.file;
|
||||
this.followObsidianNewNoteLocation = followObsidianNewNoteLocation;
|
||||
this.waitForClose = new Promise<TFile | null>((resolve, reject) => {
|
||||
this.resolvePromise = resolve;
|
||||
this.rejectPromise = reject;
|
||||
@@ -1183,15 +1188,42 @@ export class NewFileActions extends Modal {
|
||||
return true;
|
||||
};
|
||||
|
||||
const createFile = async (data: string): Promise<TFile> => {
|
||||
if (!this.path.includes("/")) {
|
||||
const re = new RegExp(`${escapeRegExp(this.parentFile.name)}$`, "g");
|
||||
this.path = this.parentFile.path.replace(re, this.path);
|
||||
const createFile = async (
|
||||
data: string,
|
||||
useObsidianNewNoteLocation: boolean,
|
||||
): Promise<TFile> => {
|
||||
let path = this.path;
|
||||
if (!path.match(/\.md$/)) {
|
||||
path = `${path}.md`;
|
||||
}
|
||||
if (!this.path.match(/\.md$/)) {
|
||||
this.path = `${this.path}.md`;
|
||||
if (!path.includes("/")) {
|
||||
if (
|
||||
useObsidianNewNoteLocation &&
|
||||
this.followObsidianNewNoteLocation
|
||||
) {
|
||||
const newFileLocation = this.app.vault.getConfig("newFileLocation");
|
||||
let targetFolder = this.parentFile.parent?.path ?? "";
|
||||
if (newFileLocation === "root") {
|
||||
targetFolder = "";
|
||||
} else if (newFileLocation === "folder") {
|
||||
const configuredFolder = this.app.vault.getConfig(
|
||||
"newFileFolderPath",
|
||||
);
|
||||
targetFolder =
|
||||
typeof configuredFolder === "string" ? configuredFolder : "";
|
||||
}
|
||||
path = normalizePath(
|
||||
targetFolder ? `${targetFolder}/${path}` : path,
|
||||
);
|
||||
} else {
|
||||
const re = new RegExp(
|
||||
`${escapeRegExp(this.parentFile.name)}$`,
|
||||
"g",
|
||||
);
|
||||
path = this.parentFile.path.replace(re, path);
|
||||
}
|
||||
}
|
||||
return await createOrOverwriteFile(this.app, this.path, data);
|
||||
return await createOrOverwriteFile(this.app, path, data);
|
||||
};
|
||||
|
||||
if (this.sourceElement) {
|
||||
@@ -1203,7 +1235,7 @@ export class NewFileActions extends Modal {
|
||||
if (!checks) {
|
||||
return;
|
||||
}
|
||||
const f = await createFile("");
|
||||
const f = await createFile("", true);
|
||||
if (f) {
|
||||
const ea: ExcalidrawAutomate = getEA(this.view);
|
||||
ea.copyViewElementsToEAforEditing([this.sourceElement]);
|
||||
@@ -1231,7 +1263,7 @@ export class NewFileActions extends Modal {
|
||||
if (!checks) {
|
||||
return;
|
||||
}
|
||||
const f = await createFile("");
|
||||
const f = await createFile("", true);
|
||||
this.openFile(f);
|
||||
this.close();
|
||||
};
|
||||
@@ -1244,7 +1276,10 @@ export class NewFileActions extends Modal {
|
||||
if (!checks) {
|
||||
return;
|
||||
}
|
||||
const f = await createFile(await this.plugin.getBlankDrawing());
|
||||
const f = await createFile(
|
||||
await this.plugin.getBlankDrawing(),
|
||||
false,
|
||||
);
|
||||
await sleep(200); //wait for metadata cache to update, so file opens as excalidraw
|
||||
this.openFile(f);
|
||||
this.close();
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { type App, Modal, Setting } from "obsidian";
|
||||
import { t } from "src/lang/helpers";
|
||||
|
||||
export type SettingsRecoveryChoice =
|
||||
| "restore-recovery"
|
||||
| "reset-defaults"
|
||||
| "wait-for-file";
|
||||
|
||||
export type SettingsRecoveryPromptMode =
|
||||
| "missing-with-recovery"
|
||||
| "invalid-without-recovery";
|
||||
|
||||
/** Resolves ambiguous startup settings loss without silently choosing for the user. */
|
||||
export class SettingsRecoveryPrompt extends Modal {
|
||||
private resolvePromise: (choice: SettingsRecoveryChoice) => void;
|
||||
private choice: SettingsRecoveryChoice;
|
||||
|
||||
public constructor(
|
||||
app: App,
|
||||
private readonly mode: SettingsRecoveryPromptMode,
|
||||
) {
|
||||
super(app);
|
||||
this.choice =
|
||||
mode === "missing-with-recovery"
|
||||
? "restore-recovery"
|
||||
: "wait-for-file";
|
||||
}
|
||||
|
||||
/** Opens the prompt and resolves after the user chooses or closes it. */
|
||||
public start(): Promise<SettingsRecoveryChoice> {
|
||||
const result = new Promise<SettingsRecoveryChoice>((resolve) => {
|
||||
this.resolvePromise = resolve;
|
||||
});
|
||||
this.open();
|
||||
return result;
|
||||
}
|
||||
|
||||
public onOpen(): void {
|
||||
const hasRecovery = this.mode === "missing-with-recovery";
|
||||
this.titleEl.setText(
|
||||
t(
|
||||
hasRecovery
|
||||
? "SETTINGS_RECOVERY_MISSING_TITLE"
|
||||
: "SETTINGS_RECOVERY_CORRUPT_TITLE",
|
||||
),
|
||||
);
|
||||
this.contentEl.createEl("p", {
|
||||
text: t(
|
||||
hasRecovery
|
||||
? "SETTINGS_RECOVERY_MISSING_DESC"
|
||||
: "SETTINGS_RECOVERY_CORRUPT_DESC",
|
||||
),
|
||||
});
|
||||
|
||||
const buttons = new Setting(this.contentEl);
|
||||
buttons.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("SETTINGS_RECOVERY_RESET_DEFAULTS"))
|
||||
.onClick(() => {
|
||||
this.choice = "reset-defaults";
|
||||
this.close();
|
||||
}),
|
||||
);
|
||||
buttons.addButton((button) =>
|
||||
button
|
||||
.setCta()
|
||||
.setButtonText(
|
||||
t(
|
||||
hasRecovery
|
||||
? "SETTINGS_RECOVERY_RESTORE_BACKUP"
|
||||
: "SETTINGS_RECOVERY_WAIT_FOR_FILE",
|
||||
),
|
||||
)
|
||||
.onClick(() => {
|
||||
this.choice = hasRecovery ? "restore-recovery" : "wait-for-file";
|
||||
this.close();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
public onClose(): void {
|
||||
this.contentEl.empty();
|
||||
this.resolvePromise?.(this.choice);
|
||||
}
|
||||
}
|
||||
@@ -287,7 +287,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
},
|
||||
{
|
||||
field: "createViewSVG",
|
||||
code: "async createViewSVG({withBackground?: boolean, theme?: 'light' | 'dark', frameRendering?: FrameRenderingOptions, padding?: number, selectedOnly?: boolean, skipInliningFonts?: boolean, embedScene?: boolean}): Promise<SVGSVGElement>",
|
||||
code: "async createViewSVG({withBackground?: boolean, theme?: 'light' | 'dark', frameRendering?: FrameRenderingOptions, padding?: number, selectedOnly?: boolean, skipInliningFonts?: boolean, embedScene?: boolean, elementsOverride?: readonly ExcalidrawElement[]}): Promise<SVGSVGElement>",
|
||||
desc:
|
||||
"Creates an SVG representation of the current view with specified options.\n" +
|
||||
"\n" +
|
||||
@@ -299,6 +299,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
"@param {boolean} [options.selectedOnly=false] - Whether to include only the selected elements in the SVG.\n" +
|
||||
"@param {boolean} [options.skipInliningFonts=false] - Whether to skip inlining fonts in the SVG.\n" +
|
||||
"@param {boolean} [options.embedScene=false] - Whether to embed the scene in the SVG.\n" +
|
||||
"@param {readonly ExcalidrawElement[]} [options.elementsOverride] - Complete replacement for the exported elements. It is not merged with the current scene or treated as a patch by ID. Include every element that should appear in the SVG.\n" +
|
||||
"@returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.\n" +
|
||||
"\n" +
|
||||
"@typedef {Object} FrameRenderingOptions\n" +
|
||||
@@ -315,6 +316,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
" selectedOnly: false,\n" +
|
||||
" skipInliningFonts: false,\n" +
|
||||
" embedScene: false,\n" +
|
||||
" // elementsOverride: ea.getElements(), // Must contain the complete export set.\n" +
|
||||
"});",
|
||||
},
|
||||
{
|
||||
@@ -506,24 +508,25 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
},
|
||||
{
|
||||
field: "targetView",
|
||||
code: "targetView: ExcalidrawView;",
|
||||
desc: "The Obsidian view currently edited",
|
||||
code: "targetView: ExcalidrawView | null;",
|
||||
desc: "The targeted Obsidian Excalidraw view, or null when EA is unbound",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "setView",
|
||||
code: 'setView(view?: ExcalidrawView | "auto" | "first" | "active" | null, show: boolean = false): ExcalidrawView;',
|
||||
code: 'setView(view?: ExcalidrawView | "auto" | "first" | "active" | null, show: boolean = false): ExcalidrawView | null;',
|
||||
desc:
|
||||
"Sets the target view for EA. All the view operations and the access to Excalidraw API will be performed on this view. " +
|
||||
"Typically you will use setView() (to pick a sensible default) or setView(excalidrawView) (to explicitly target a specific view).\n" +
|
||||
"Typically you will use setView() (to pick a sensible default), setView(excalidrawView) (to explicitly target a specific view), or setView(null) (to explicitly clear targetView).\n" +
|
||||
'"auto" is equivalent to calling setView() and can read nicer when you want to show the view (e.g. setView("auto", true)).\n' +
|
||||
'"active" and "first" are deprecated and are kept for backward compatibility.\n' +
|
||||
'If view is null or undefined (or "auto"), EA will pick a sensible default: first the currently active Excalidraw view (if any), otherwise the last active Excalidraw view (if it is still available), otherwise the "first" Excalidraw view in the workspace.\n' +
|
||||
'If view is undefined (or "auto"), EA will pick a sensible default: first the currently active Excalidraw view (if any), otherwise the last active Excalidraw view (if it is still available), otherwise the "first" Excalidraw view in the workspace.\n' +
|
||||
"If view is explicitly null, EA clears targetView. This is useful when a sidepanel becomes unbound because focus moved to a Markdown view or no drawing is eligible.\n" +
|
||||
"If show is true, the view will be brought to front and focused.\n" +
|
||||
'If "first" is provided, the target will be the first Excalidraw view returned by Obsidian\'s workspace leaf collection (i.e., the first item in getExcalidrawViews()). ' +
|
||||
"This ordering is managed by Obsidian and does not necessarily match what a user would consider the “first” view; from a user's perspective it may appear random.\n" +
|
||||
'If "active" is provided, the currently active Excalidraw view in the workspace will be used. If that is not available, then the last active Excalidraw view will be used.\n' +
|
||||
"The function returns the ExcalidrawView that was set as targetView.",
|
||||
"The function returns the ExcalidrawView that was set as targetView, or null when cleared or no view was found.",
|
||||
after: '("auto",true);',
|
||||
},
|
||||
{
|
||||
@@ -996,6 +999,40 @@ 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: "registerCleanup",
|
||||
code: "registerCleanup(cleanup: () => void): () => void;",
|
||||
desc:
|
||||
"Registers synchronous cleanup owned by this ExcalidrawAutomate instance. " +
|
||||
"Use it for external Obsidian or DOM listeners, observers, timers, and subscriptions. " +
|
||||
"The callback runs when this EA is destroyed; the returned function unregisters it without running it. " +
|
||||
"The exact lifetime depends on the lifecycle that created the EA.",
|
||||
after: "(() => releaseExternalResource());",
|
||||
},
|
||||
{
|
||||
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. " +
|
||||
"The menu is temporarily hidden while the selected frame title is being edited. " +
|
||||
"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(message?: string): Promise<"allow" | "deny" | "pending">;',
|
||||
desc:
|
||||
"Requests permission for this script to be automatically re-run every time a new Excalidraw view is opened. " +
|
||||
"The optional message is shown as a separate second paragraph after the permission question and before the hint explaining where the permission can be changed. Use it to clarify what the script registers or performs during autostart. " +
|
||||
"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(). Use utils.executionSource === "view-autostart" when only the view-autostart execution should stop after registration.',
|
||||
after: '("Autostart registers this script’s drawing tools; it does not run its main action.");',
|
||||
},
|
||||
{
|
||||
field: "getSidepanelLeaf",
|
||||
code: "getSidepanelLeaf(): WorkspaceLeaf | null;",
|
||||
@@ -1391,6 +1428,15 @@ export const EXCALIDRAW_SCRIPTENGINE_INFO: SuggesterInfo[] = [
|
||||
desc: "The TFile of the currently running script",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "executionSource",
|
||||
code: 'executionSource: "manual" | "plugin-startup" | "view-autostart" | "sidepanel-restore" | "sidepanel-reload" | "drawing-onload"',
|
||||
desc:
|
||||
"Identifies why the script engine invoked the current script. " +
|
||||
'Use "view-autostart" for registration-only setup, while "manual" covers the script button, command palette, and hotkey. ' +
|
||||
"This value describes the trigger, not compilation-cache reuse or retained runtime state.",
|
||||
after: "",
|
||||
},
|
||||
];
|
||||
|
||||
export const FRONTMATTER_KEYS_INFO: SuggesterInfo[] = [
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+439
-110
@@ -31,9 +31,10 @@ import {
|
||||
getMimeType,
|
||||
getPDFDoc,
|
||||
getURLImageExtension,
|
||||
hasExcalidrawEmbeddedImagesTreeChanged,
|
||||
readLocalFileBinary,
|
||||
} from "../utils/fileUtils";
|
||||
import { errorlog, getDataURL } from "../utils/coreUtils";
|
||||
import { blobToDataURL, errorlog, getDataURL } from "../utils/coreUtils";
|
||||
import {
|
||||
getExportTheme,
|
||||
getLinkParts,
|
||||
@@ -102,11 +103,34 @@ declare const mainDocument: Document;
|
||||
const markdownRendererRecursionWatcthdog = new Set<TFile>();
|
||||
|
||||
type CacheValidationMode = "validated" | "stale-first";
|
||||
const SCENE_FILE_LOAD_STALL_TIMEOUT_MS = 30_000;
|
||||
const SCENE_FILE_PROGRESSIVE_BATCH_SIZE = 8;
|
||||
|
||||
export type EmbeddedFilesLoaderTerminalState =
|
||||
| "idle"
|
||||
| "running"
|
||||
| "completed"
|
||||
| "terminated"
|
||||
| "timed-out"
|
||||
| "failed";
|
||||
|
||||
/** Describes the lightweight work required after a stale-first cache hit. */
|
||||
export type DeferredCacheValidation =
|
||||
| {
|
||||
kind: "excalidraw-dependencies";
|
||||
cacheMtime: number;
|
||||
}
|
||||
| {
|
||||
kind: "reload";
|
||||
};
|
||||
|
||||
type LoadImageOptions = {
|
||||
cacheValidation?: CacheValidationMode;
|
||||
onStaleCacheHit?: () => void;
|
||||
onStaleCacheHit?: (validation: DeferredCacheValidation) => void;
|
||||
deferUncachedExcalidraw?: boolean;
|
||||
onExcalidrawGenerationDeferred?: () => void;
|
||||
markdownTransclusionRender?: MarkdownImageRenderSettings;
|
||||
fileId?: FileId;
|
||||
};
|
||||
|
||||
type MarkdownRenderOverrides = {
|
||||
@@ -667,6 +691,7 @@ export class EmbeddedFilesLoader {
|
||||
private plugin: ExcalidrawPlugin;
|
||||
private isDark: boolean;
|
||||
public terminate = false;
|
||||
public terminalState: EmbeddedFilesLoaderTerminalState = "idle";
|
||||
public uid: string;
|
||||
|
||||
constructor(plugin: ExcalidrawPlugin, isDark?: boolean) {
|
||||
@@ -758,6 +783,7 @@ export class EmbeddedFilesLoader {
|
||||
elements = [],
|
||||
cacheValidation = "validated",
|
||||
onStaleCacheHit,
|
||||
deferUncachedGeneration = false,
|
||||
}: {
|
||||
isDark: boolean;
|
||||
file: TFile;
|
||||
@@ -766,11 +792,14 @@ export class EmbeddedFilesLoader {
|
||||
hasSVGwithBitmap: boolean;
|
||||
elements?: ExcalidrawElement[];
|
||||
cacheValidation?: CacheValidationMode;
|
||||
onStaleCacheHit?: () => void;
|
||||
onStaleCacheHit?: (validation: DeferredCacheValidation) => void;
|
||||
deferUncachedGeneration?: boolean;
|
||||
}): Promise<{
|
||||
dataURL: DataURL;
|
||||
hasSVGwithBitmap: boolean;
|
||||
loadedFromCache?: boolean;
|
||||
size?: Size;
|
||||
generationDeferred?: boolean;
|
||||
}> {
|
||||
if (this.terminate) {
|
||||
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
|
||||
@@ -830,58 +859,85 @@ export class EmbeddedFilesLoader {
|
||||
isTransparent: !exportSettings.withBackground,
|
||||
};
|
||||
|
||||
let cachedSize: Size | undefined;
|
||||
let cachedHasSVGwithBitmap: boolean | undefined;
|
||||
const maybeSVG = shouldUseCache
|
||||
? await getImageCache().getImageFromCache(cacheKey, {
|
||||
skipDependencyCheck: cacheValidation === "stale-first",
|
||||
expectedPayloadKind: "svg",
|
||||
requireSvgInspectionMetadata: true,
|
||||
svgFormat: "data-url",
|
||||
onCacheHit: ({ mtime, size, hasSVGwithBitmap }) => {
|
||||
cachedSize = size;
|
||||
cachedHasSVGwithBitmap = hasSVGwithBitmap;
|
||||
if (cacheValidation === "stale-first") {
|
||||
onStaleCacheHit?.({
|
||||
kind: "excalidraw-dependencies",
|
||||
cacheMtime: mtime,
|
||||
});
|
||||
}
|
||||
},
|
||||
})
|
||||
: undefined;
|
||||
|
||||
if (this.terminate) {
|
||||
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
|
||||
}
|
||||
|
||||
if (maybeSVG && cacheValidation === "stale-first") {
|
||||
onStaleCacheHit?.();
|
||||
const cachedDataURL =
|
||||
typeof maybeSVG === "string" ? (maybeSVG as DataURL) : undefined;
|
||||
if (cachedDataURL) {
|
||||
return {
|
||||
dataURL: cachedDataURL,
|
||||
hasSVGwithBitmap: cachedHasSVGwithBitmap ?? hasSVGwithBitmap,
|
||||
loadedFromCache: true,
|
||||
size: cachedSize,
|
||||
};
|
||||
}
|
||||
|
||||
const svg =
|
||||
maybeSVG && maybeSVG instanceof SVGSVGElement
|
||||
? maybeSVG
|
||||
: (replaceSVGColors(
|
||||
await createSVG(
|
||||
hasFilenameParts
|
||||
? filenameParts.hasGroupref ||
|
||||
filenameParts.hasBlockref ||
|
||||
filenameParts.hasSectionref ||
|
||||
filenameParts.hasFrameref ||
|
||||
filenameParts.hasClippedFrameref
|
||||
? filenameParts.filepath + filenameParts.linkpartReference
|
||||
: file.path
|
||||
: file?.path,
|
||||
false, //false
|
||||
hasFilenameParts && filenameParts.hasClippedFrameref
|
||||
? {
|
||||
...exportSettings,
|
||||
frameRendering: {
|
||||
enabled: true,
|
||||
name: false,
|
||||
outline: false,
|
||||
clip: true,
|
||||
},
|
||||
}
|
||||
: exportSettings,
|
||||
this,
|
||||
forceTheme,
|
||||
null,
|
||||
null,
|
||||
elements,
|
||||
this.plugin,
|
||||
depth + 1,
|
||||
getExportPadding(this.plugin, file),
|
||||
),
|
||||
inFile instanceof EmbeddedFile ? inFile.colorMap : null,
|
||||
) as SVGSVGElement);
|
||||
if (deferUncachedGeneration) {
|
||||
return {
|
||||
dataURL: null,
|
||||
hasSVGwithBitmap,
|
||||
loadedFromCache: false,
|
||||
generationDeferred: true,
|
||||
};
|
||||
}
|
||||
|
||||
const generatedSVG = await createSVG(
|
||||
hasFilenameParts
|
||||
? filenameParts.hasGroupref ||
|
||||
filenameParts.hasBlockref ||
|
||||
filenameParts.hasSectionref ||
|
||||
filenameParts.hasFrameref ||
|
||||
filenameParts.hasClippedFrameref
|
||||
? filenameParts.filepath + filenameParts.linkpartReference
|
||||
: file.path
|
||||
: file?.path,
|
||||
false, //false
|
||||
hasFilenameParts && filenameParts.hasClippedFrameref
|
||||
? {
|
||||
...exportSettings,
|
||||
frameRendering: {
|
||||
enabled: true,
|
||||
name: false,
|
||||
outline: false,
|
||||
clip: true,
|
||||
},
|
||||
}
|
||||
: exportSettings,
|
||||
this,
|
||||
forceTheme,
|
||||
null,
|
||||
null,
|
||||
elements,
|
||||
this.plugin,
|
||||
depth + 1,
|
||||
getExportPadding(this.plugin, file),
|
||||
);
|
||||
const svg = replaceSVGColors(
|
||||
generatedSVG,
|
||||
inFile instanceof EmbeddedFile ? inFile.colorMap : null,
|
||||
) as SVGSVGElement;
|
||||
if (this.terminate) {
|
||||
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
|
||||
}
|
||||
@@ -894,7 +950,7 @@ export class EmbeddedFilesLoader {
|
||||
hasSVGwithBitmap = true;
|
||||
}
|
||||
|
||||
if (hasSVGwithBitmap && isDark && !maybeSVG) {
|
||||
if (hasSVGwithBitmap && isDark) {
|
||||
imageList.forEach((i) => {
|
||||
const id = i.parentElement?.id;
|
||||
if (id.endsWith("-invert-bitmap")) {
|
||||
@@ -912,7 +968,7 @@ export class EmbeddedFilesLoader {
|
||||
hasSVGwithBitmap = true;
|
||||
}
|
||||
|
||||
if (svgsToInvert.length > 0 && isDark && !maybeSVG) {
|
||||
if (svgsToInvert.length > 0 && isDark) {
|
||||
svgsToInvert.forEach((i) => {
|
||||
const id = i.id;
|
||||
svg.querySelectorAll(`use[href='#${id}']`).forEach((u) => {
|
||||
@@ -924,12 +980,6 @@ export class EmbeddedFilesLoader {
|
||||
if (!hasSVGwithBitmap && svg.getAttribute("hasbitmap")) {
|
||||
hasSVGwithBitmap = true;
|
||||
}
|
||||
if (shouldUseCache && !maybeSVG) {
|
||||
//cache SVG should have the width and height parameters and not the embedded font
|
||||
//see svgWithFont below
|
||||
getImageCache().addImageToCache(cacheKey, "", svg);
|
||||
}
|
||||
|
||||
if (!svg.hasAttribute("width") && svg.hasAttribute("viewBox")) {
|
||||
//2024.06.09
|
||||
//this addresses backward compatibility issues where the cache does not have the width and height attributes
|
||||
@@ -942,11 +992,32 @@ export class EmbeddedFilesLoader {
|
||||
svg.setAttribute("height", vb[3]);
|
||||
}
|
||||
}
|
||||
const dURL = svgToBase64(svg.outerHTML) as DataURL;
|
||||
const width = Number.parseFloat(svg.getAttribute("width") ?? "");
|
||||
const height = Number.parseFloat(svg.getAttribute("height") ?? "");
|
||||
const size =
|
||||
Number.isFinite(width) &&
|
||||
width > 0 &&
|
||||
Number.isFinite(height) &&
|
||||
height > 0
|
||||
? { width, height }
|
||||
: undefined;
|
||||
const svgBlob = new Blob([svg.outerHTML.replaceAll(" ", " ")], {
|
||||
type: "image/svg+xml",
|
||||
});
|
||||
const dURL = await blobToDataURL(svgBlob);
|
||||
if (shouldUseCache) {
|
||||
// Scene cache hits need enough metadata to avoid reparsing the SVG merely
|
||||
// to rediscover bitmap content and intrinsic dimensions.
|
||||
getImageCache().addImageToCache(cacheKey, "", svgBlob, {
|
||||
size,
|
||||
hasSVGwithBitmap,
|
||||
});
|
||||
}
|
||||
return {
|
||||
dataURL: dURL,
|
||||
hasSVGwithBitmap,
|
||||
loadedFromCache: Boolean(maybeSVG),
|
||||
size,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1029,13 +1100,13 @@ export class EmbeddedFilesLoader {
|
||||
this.getLocalPath((inFile as EmbeddedFile).hyperlink),
|
||||
)
|
||||
: await app.vault.readBinary(file);
|
||||
|
||||
if (this.terminate) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let dURL: DataURL = null;
|
||||
let excalidrawLoadedFromCache = false;
|
||||
let excalidrawSize: Size | undefined;
|
||||
if (isExcalidrawFile) {
|
||||
const res = await this.getExcalidrawSVG({
|
||||
isDark: this.isDark,
|
||||
@@ -1045,14 +1116,19 @@ export class EmbeddedFilesLoader {
|
||||
hasSVGwithBitmap,
|
||||
cacheValidation: options?.cacheValidation,
|
||||
onStaleCacheHit: options?.onStaleCacheHit,
|
||||
deferUncachedGeneration: options?.deferUncachedExcalidraw,
|
||||
});
|
||||
|
||||
if (this.terminate) {
|
||||
return null;
|
||||
}
|
||||
if (res.generationDeferred) {
|
||||
options?.onExcalidrawGenerationDeferred?.();
|
||||
return null;
|
||||
}
|
||||
dURL = res.dataURL;
|
||||
hasSVGwithBitmap = res.hasSVGwithBitmap;
|
||||
excalidrawLoadedFromCache = !!res.loadedFromCache;
|
||||
excalidrawSize = res.size;
|
||||
}
|
||||
|
||||
const excalidrawSVG = isExcalidrawFile ? dURL : null;
|
||||
@@ -1066,7 +1142,6 @@ export class EmbeddedFilesLoader {
|
||||
] = isPDF
|
||||
? await this.pdfToDataURL(file, linkParts, options)
|
||||
: [null, null, null, null, false];
|
||||
|
||||
if (this.terminate) {
|
||||
return null;
|
||||
}
|
||||
@@ -1096,7 +1171,6 @@ export class EmbeddedFilesLoader {
|
||||
: file?.extension === "md"
|
||||
? null
|
||||
: await getDataURL(ab, mimeType)));
|
||||
|
||||
if (this.terminate) {
|
||||
return null;
|
||||
}
|
||||
@@ -1131,27 +1205,33 @@ export class EmbeddedFilesLoader {
|
||||
}
|
||||
}
|
||||
|
||||
const size = isPDF ? pdfSize : await getImageSize(dataURL);
|
||||
const size = isPDF
|
||||
? pdfSize
|
||||
: (excalidrawSize ?? (await getImageSize(dataURL)));
|
||||
|
||||
if (this.terminate) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
mimeType,
|
||||
fileId: await generateIdFromFile(
|
||||
const generatedFileId =
|
||||
options?.fileId ??
|
||||
(await generateIdFromFile(
|
||||
isHyperLink || isPDF || isExcalidrawFile
|
||||
? new TextEncoder().encode(dataURL).buffer
|
||||
: ab,
|
||||
inFile instanceof EmbeddedFile
|
||||
? inFile.filenameparts?.linkpartReference
|
||||
: undefined,
|
||||
),
|
||||
));
|
||||
const loadedFromCache = isExcalidrawFile
|
||||
? excalidrawLoadedFromCache
|
||||
: pdfLoadedFromCache;
|
||||
return {
|
||||
mimeType,
|
||||
fileId: generatedFileId,
|
||||
dataURL,
|
||||
created: isHyperLink || isLocalLink ? 0 : file.stat.mtime,
|
||||
loadedFromCache: isExcalidrawFile
|
||||
? excalidrawLoadedFromCache
|
||||
: pdfLoadedFromCache,
|
||||
loadedFromCache,
|
||||
hasSVGwithBitmap,
|
||||
size,
|
||||
pdfPageViewProps,
|
||||
@@ -1186,7 +1266,10 @@ export class EmbeddedFilesLoader {
|
||||
validationConcurrency,
|
||||
emitPolicy = "all",
|
||||
onDeferredValidationCandidates,
|
||||
deferredCacheValidation,
|
||||
sceneElements,
|
||||
waitForRender,
|
||||
prioritizedFileIds,
|
||||
}: {
|
||||
excalidrawData: ExcalidrawData;
|
||||
addFiles: (files: FileData[], isDark: boolean, final?: boolean) => void;
|
||||
@@ -1197,14 +1280,41 @@ export class EmbeddedFilesLoader {
|
||||
cacheValidation?: CacheValidationMode;
|
||||
validationConcurrency?: number;
|
||||
emitPolicy?: LoadSceneEmitPolicy;
|
||||
onDeferredValidationCandidates?: (fileIds: Set<FileId>) => void;
|
||||
onDeferredValidationCandidates?: (
|
||||
candidates: Map<FileId, DeferredCacheValidation>,
|
||||
) => void;
|
||||
deferredCacheValidation?: ReadonlyMap<FileId, DeferredCacheValidation>;
|
||||
sceneElements?: readonly ExcalidrawElement[];
|
||||
waitForRender?: () => Promise<void>;
|
||||
prioritizedFileIds?: ReadonlySet<FileId>;
|
||||
}) {
|
||||
this.terminalState = "running";
|
||||
if (this.isDark === undefined) {
|
||||
this.isDark = excalidrawData?.scene?.appState?.theme === "dark";
|
||||
}
|
||||
if (depth > 7) {
|
||||
this.terminalState = "failed";
|
||||
new Notice(t("INFINITE_LOOP_WARNING") + depth.toString(), 6000);
|
||||
try {
|
||||
addFiles([], this.isDark, true);
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "EmbeddedFileLoader.loadSceneFiles",
|
||||
uid: this.uid,
|
||||
phase: "depth-limit",
|
||||
error,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
const entries = Array.from(excalidrawData.getFileEntries());
|
||||
if (prioritizedFileIds?.size) {
|
||||
entries.sort(
|
||||
([fileIdA], [fileIdB]) =>
|
||||
Number(prioritizedFileIds.has(fileIdB)) -
|
||||
Number(prioritizedFileIds.has(fileIdA)),
|
||||
);
|
||||
}
|
||||
const markdownImageElements = (
|
||||
sceneElements ?? excalidrawData.scene.elements
|
||||
).filter(
|
||||
@@ -1216,9 +1326,7 @@ export class EmbeddedFilesLoader {
|
||||
markdownImageElements.map((element) => element.fileId),
|
||||
);
|
||||
//debug({where:"EmbeddedFileLoader.loadSceneFiles",uid:this.uid,isDark:this.isDark,sceneTheme:excalidrawData.scene.appState.theme});
|
||||
if (this.isDark === undefined) {
|
||||
this.isDark = excalidrawData?.scene?.appState?.theme === "dark";
|
||||
}
|
||||
let onLoadTaskSettled: (() => void) | null = null;
|
||||
const createSafeLoadTask = (
|
||||
task: () => Promise<void>,
|
||||
context: Record<string, unknown>,
|
||||
@@ -1233,18 +1341,28 @@ export class EmbeddedFilesLoader {
|
||||
...context,
|
||||
error,
|
||||
});
|
||||
} finally {
|
||||
onLoadTaskSettled?.();
|
||||
}
|
||||
});
|
||||
const files: FileData[][] = [];
|
||||
files.push([]);
|
||||
let batch = 0;
|
||||
// Only stale-first cache hits are queued for the cheap second pass.
|
||||
const deferredValidationFileIds = new Set<FileId>();
|
||||
// Carry cache metadata into the second pass so unchanged Excalidraw
|
||||
// dependencies can be validated without reading the image payload again.
|
||||
const deferredValidationCandidates = new Map<
|
||||
FileId,
|
||||
DeferredCacheValidation
|
||||
>();
|
||||
const deferredGenerationEntries: typeof entries = [];
|
||||
|
||||
function* loadIterator(
|
||||
this: EmbeddedFilesLoader,
|
||||
loader: EmbeddedFilesLoader,
|
||||
embeddedEntries: typeof entries = entries,
|
||||
deferUncachedExcalidraw = false,
|
||||
includeAdditionalAssets = true,
|
||||
): Generator<Promise<void>> {
|
||||
for (const entry of entries) {
|
||||
for (const entry of embeddedEntries) {
|
||||
if (markdownImageFileIds.has(entry[0])) {
|
||||
continue;
|
||||
}
|
||||
@@ -1255,23 +1373,56 @@ export class EmbeddedFilesLoader {
|
||||
const id = entry[0];
|
||||
yield createSafeLoadTask(
|
||||
async () => {
|
||||
if (this.terminate) {
|
||||
if (loader.terminate) {
|
||||
return;
|
||||
}
|
||||
const shouldForceReload = forceReloadFileIDs?.has(id);
|
||||
if (shouldForceReload || !embeddedFile.isLoaded(this.isDark)) {
|
||||
const deferredValidation = deferredCacheValidation?.get(id);
|
||||
if (
|
||||
cacheValidation === "validated" &&
|
||||
emitPolicy === "changed-only" &&
|
||||
shouldForceReload &&
|
||||
deferredValidation?.kind === "excalidraw-dependencies"
|
||||
) {
|
||||
const file = embeddedFile.file;
|
||||
const cacheIsValid = Boolean(
|
||||
file &&
|
||||
file.stat.mtime <= deferredValidation.cacheMtime &&
|
||||
!hasExcalidrawEmbeddedImagesTreeChanged(
|
||||
file,
|
||||
deferredValidation.cacheMtime,
|
||||
loader.plugin,
|
||||
),
|
||||
);
|
||||
if (cacheIsValid) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (shouldForceReload || !embeddedFile.isLoaded(loader.isDark)) {
|
||||
//debug({where:"EmbeddedFileLoader.loadSceneFiles",uid:this.uid,status:"embedded Files are not loaded"});
|
||||
const data = await this._getObsidianImage(embeddedFile, depth, {
|
||||
let excalidrawGenerationDeferred = false;
|
||||
const data = await loader._getObsidianImage(embeddedFile, depth, {
|
||||
cacheValidation,
|
||||
fileId: id,
|
||||
deferUncachedExcalidraw,
|
||||
onExcalidrawGenerationDeferred: () => {
|
||||
excalidrawGenerationDeferred = true;
|
||||
},
|
||||
onStaleCacheHit:
|
||||
cacheValidation === "stale-first"
|
||||
? () => deferredValidationFileIds.add(id)
|
||||
? (validation) =>
|
||||
deferredValidationCandidates.set(id, validation)
|
||||
: undefined,
|
||||
});
|
||||
if (this.terminate) {
|
||||
if (loader.terminate) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (excalidrawGenerationDeferred) {
|
||||
deferredGenerationEntries.push(entry);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data) {
|
||||
const fileData: FileData = {
|
||||
mimeType: data.mimeType,
|
||||
@@ -1295,7 +1446,7 @@ export class EmbeddedFilesLoader {
|
||||
const fileData: FileData = {
|
||||
mimeType: embeddedFile.mimeType,
|
||||
id,
|
||||
dataURL: embeddedFile.getImage(this.isDark) as DataURL,
|
||||
dataURL: embeddedFile.getImage(loader.isDark) as DataURL,
|
||||
created: embeddedFile.mtime,
|
||||
size: embeddedFile.size,
|
||||
hasSVGwithBitmap: embeddedFile.isSVGwithBitmap,
|
||||
@@ -1315,6 +1466,10 @@ export class EmbeddedFilesLoader {
|
||||
);
|
||||
}
|
||||
|
||||
if (!includeAdditionalAssets) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const element of markdownImageElements) {
|
||||
const id = element.fileId;
|
||||
if (fileIDWhiteList && !fileIDWhiteList.has(id)) {
|
||||
@@ -1322,7 +1477,7 @@ export class EmbeddedFilesLoader {
|
||||
}
|
||||
yield createSafeLoadTask(
|
||||
async () => {
|
||||
if (this.terminate) {
|
||||
if (loader.terminate) {
|
||||
return;
|
||||
}
|
||||
const customData = element.customData?.[
|
||||
@@ -1332,7 +1487,7 @@ export class EmbeddedFilesLoader {
|
||||
return;
|
||||
}
|
||||
const render = resolveMarkdownImageRenderSettings(
|
||||
this.plugin.settings.markdownImageSettings.defaults,
|
||||
loader.plugin.settings.markdownImageSettings.defaults,
|
||||
customData.render,
|
||||
);
|
||||
const legacyRender = customData.render as MarkdownImageRenderSettings & {
|
||||
@@ -1369,7 +1524,7 @@ export class EmbeddedFilesLoader {
|
||||
sourceFile = embeddedFile.file;
|
||||
const transclusion = await getTransclusion(
|
||||
embeddedFile.linkParts,
|
||||
this.plugin.app,
|
||||
loader.plugin.app,
|
||||
sourceFile,
|
||||
);
|
||||
markdown =
|
||||
@@ -1380,12 +1535,12 @@ export class EmbeddedFilesLoader {
|
||||
if (markdown === undefined) {
|
||||
return;
|
||||
}
|
||||
const rendered = await this.renderMarkdownToSVG(
|
||||
const rendered = await loader.renderMarkdownToSVG(
|
||||
sourceFile,
|
||||
markdown,
|
||||
render,
|
||||
);
|
||||
if (!rendered.dataURL || this.terminate) {
|
||||
if (!rendered.dataURL || loader.terminate) {
|
||||
return;
|
||||
}
|
||||
files[batch].push({
|
||||
@@ -1412,13 +1567,13 @@ export class EmbeddedFilesLoader {
|
||||
}
|
||||
yield createSafeLoadTask(
|
||||
async () => {
|
||||
if (this.terminate) {
|
||||
if (loader.terminate) {
|
||||
return;
|
||||
}
|
||||
if (!excalidrawData.getEquation(id).isLoaded) {
|
||||
const latex = equation.latex;
|
||||
const data = await tex2dataURL(latex, 4, this.plugin);
|
||||
if (this.terminate) {
|
||||
const data = await tex2dataURL(latex, 4, loader.plugin);
|
||||
if (loader.terminate) {
|
||||
return null;
|
||||
}
|
||||
if (data) {
|
||||
@@ -1450,14 +1605,14 @@ export class EmbeddedFilesLoader {
|
||||
for (const element of mermaidElements) {
|
||||
yield createSafeLoadTask(
|
||||
async () => {
|
||||
if (this.terminate) {
|
||||
if (loader.terminate) {
|
||||
return;
|
||||
}
|
||||
const data = getMermaidText(element);
|
||||
const result = await mermaidToExcalidraw(data, {
|
||||
themeVariables: { fontSize: "20" },
|
||||
});
|
||||
if (!result || this.terminate) {
|
||||
if (!result || loader.terminate) {
|
||||
return;
|
||||
}
|
||||
if (result?.files) {
|
||||
@@ -1481,18 +1636,18 @@ export class EmbeddedFilesLoader {
|
||||
}
|
||||
if (result?.elements) {
|
||||
//handle case that mermaidToExcalidraw has implemented this type of diagram in the mean time
|
||||
if (this.terminate) {
|
||||
if (loader.terminate) {
|
||||
return;
|
||||
}
|
||||
const res = await this.getExcalidrawSVG({
|
||||
isDark: this.isDark,
|
||||
const res = await loader.getExcalidrawSVG({
|
||||
isDark: loader.isDark,
|
||||
file: null,
|
||||
depth,
|
||||
inFile: null,
|
||||
hasSVGwithBitmap: false,
|
||||
elements: result.elements as ExcalidrawElement[],
|
||||
elements: result.elements,
|
||||
});
|
||||
if (this.terminate) {
|
||||
if (loader.terminate) {
|
||||
return;
|
||||
}
|
||||
if (res?.dataURL) {
|
||||
@@ -1520,6 +1675,117 @@ export class EmbeddedFilesLoader {
|
||||
}
|
||||
}
|
||||
|
||||
const runLoadPool = async (
|
||||
iterator: Generator<Promise<void>>,
|
||||
concurrency: number,
|
||||
): Promise<boolean> => {
|
||||
let stallTimer: number | null = null;
|
||||
let resolveStall!: () => void;
|
||||
const stalled = new Promise<"stalled">((resolve) => {
|
||||
resolveStall = () => resolve("stalled");
|
||||
});
|
||||
const resetStallTimer = () => {
|
||||
if (stallTimer !== null) {
|
||||
window.clearTimeout(stallTimer);
|
||||
}
|
||||
stallTimer = window.setTimeout(
|
||||
resolveStall,
|
||||
SCENE_FILE_LOAD_STALL_TIMEOUT_MS,
|
||||
);
|
||||
};
|
||||
|
||||
onLoadTaskSettled = resetStallTimer;
|
||||
resetStallTimer();
|
||||
const poolCompleted = new PromisePool(iterator, concurrency)
|
||||
.all()
|
||||
.then(() => "completed" as const);
|
||||
const result = await Promise.race([poolCompleted, stalled]);
|
||||
onLoadTaskSettled = null;
|
||||
if (stallTimer !== null) {
|
||||
window.clearTimeout(stallTimer);
|
||||
}
|
||||
if (result === "completed") {
|
||||
return true;
|
||||
}
|
||||
|
||||
this.terminalState = "timed-out";
|
||||
this.terminate = true;
|
||||
return false;
|
||||
};
|
||||
|
||||
let finalFlushed = false;
|
||||
const flushFiles = (
|
||||
batchFiles: FileData[] | undefined,
|
||||
final: boolean,
|
||||
) => {
|
||||
if (final && finalFlushed) {
|
||||
return;
|
||||
}
|
||||
if (final) {
|
||||
finalFlushed = true;
|
||||
}
|
||||
try {
|
||||
addFiles(batchFiles, this.isDark, final);
|
||||
} catch (e: unknown) {
|
||||
errorlog({ where: "EmbeddedFileLoader.loadSceneFiles", error: e });
|
||||
}
|
||||
};
|
||||
|
||||
let progressivePaintPromise: Promise<void> | null = null;
|
||||
const flushProgressiveBatch = (): boolean => {
|
||||
if (
|
||||
!waitForRender ||
|
||||
files[batch].length <= SCENE_FILE_PROGRESSIVE_BATCH_SIZE
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (prioritizedFileIds?.size) {
|
||||
files[batch].sort(
|
||||
(fileA, fileB) =>
|
||||
Number(prioritizedFileIds.has(fileB.id)) -
|
||||
Number(prioritizedFileIds.has(fileA.id)),
|
||||
);
|
||||
}
|
||||
const batchFiles = files[batch]
|
||||
.splice(0, SCENE_FILE_PROGRESSIVE_BATCH_SIZE)
|
||||
.filter((f) => emitPolicy === "all" || !f.loadedFromCache);
|
||||
if (batchFiles.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
flushFiles(batchFiles, false);
|
||||
const paintPromise = Promise.resolve()
|
||||
.then(waitForRender)
|
||||
.catch((error: unknown) => {
|
||||
errorlog({
|
||||
where: "EmbeddedFileLoader.loadSceneFiles",
|
||||
phase: "progressive-batch-paint",
|
||||
error,
|
||||
});
|
||||
});
|
||||
progressivePaintPromise = paintPromise;
|
||||
void paintPromise.finally(() => {
|
||||
if (progressivePaintPromise === paintPromise) {
|
||||
progressivePaintPromise = null;
|
||||
}
|
||||
});
|
||||
return true;
|
||||
};
|
||||
|
||||
const waitForProgressivePaint = async () => {
|
||||
if (progressivePaintPromise !== null) {
|
||||
await progressivePaintPromise;
|
||||
}
|
||||
};
|
||||
|
||||
const drainProgressiveBatches = async () => {
|
||||
await waitForProgressivePaint();
|
||||
while (flushProgressiveBatch()) {
|
||||
await waitForProgressivePaint();
|
||||
}
|
||||
};
|
||||
|
||||
const addFilesTimer = window.setInterval(() => {
|
||||
if (this.terminate) {
|
||||
window.clearInterval(addFilesTimer);
|
||||
@@ -1528,47 +1794,109 @@ export class EmbeddedFilesLoader {
|
||||
if (files[batch].length === 0) {
|
||||
return;
|
||||
}
|
||||
if (progressivePaintPromise !== null) {
|
||||
return;
|
||||
}
|
||||
if (flushProgressiveBatch()) {
|
||||
return;
|
||||
}
|
||||
// During deferred validation, only regenerated results should reach addFiles.
|
||||
const batchFiles = files[batch].filter(
|
||||
(f) => emitPolicy === "all" || !f.loadedFromCache,
|
||||
);
|
||||
try {
|
||||
addFiles(batchFiles, this.isDark, false);
|
||||
} catch (e: unknown) {
|
||||
errorlog({ where: "EmbeddedFileLoader.loadSceneFiles", error: e });
|
||||
}
|
||||
flushFiles(batchFiles, false);
|
||||
files.push([]);
|
||||
batch++;
|
||||
}, 1200);
|
||||
|
||||
try {
|
||||
const iterator = loadIterator.bind(this)();
|
||||
const concurency =
|
||||
validationConcurrency ?? this.plugin.settings.renderingConcurrency;
|
||||
const iterator = loadIterator(this, entries, true, true);
|
||||
if (!this.terminate) {
|
||||
await new PromisePool(iterator, concurency).all();
|
||||
await runLoadPool(iterator, concurency);
|
||||
}
|
||||
|
||||
if (this.terminate) {
|
||||
addFiles(undefined, this.isDark, true);
|
||||
if (this.terminalState === "running") {
|
||||
this.terminalState = "terminated";
|
||||
}
|
||||
flushFiles(undefined, true);
|
||||
return;
|
||||
}
|
||||
if (deferredGenerationEntries.length > 0) {
|
||||
// Publish everything that was available from cache or direct file reads
|
||||
// before expensive generated SVG work can monopolize the main thread.
|
||||
await drainProgressiveBatches();
|
||||
const fastFiles = files[batch].filter(
|
||||
(f) => emitPolicy === "all" || !f.loadedFromCache,
|
||||
);
|
||||
if (fastFiles.length > 0) {
|
||||
flushFiles(fastFiles, false);
|
||||
}
|
||||
files.push([]);
|
||||
batch++;
|
||||
|
||||
// Yield a browser task after addFiles so the fast batch can paint before
|
||||
// starting potentially long synchronous sections of SVG generation.
|
||||
await new Promise<void>((resolve) => window.setTimeout(resolve, 0));
|
||||
if (!this.terminate) {
|
||||
const deferredIterator = loadIterator(
|
||||
this,
|
||||
deferredGenerationEntries,
|
||||
false,
|
||||
false,
|
||||
);
|
||||
await runLoadPool(deferredIterator, concurency);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.terminate) {
|
||||
if (this.terminalState === "running") {
|
||||
this.terminalState = "terminated";
|
||||
}
|
||||
flushFiles(undefined, true);
|
||||
return;
|
||||
}
|
||||
//debug({where:"EmbeddedFileLoader.loadSceneFiles",uid:this.uid,status:"add Files"});
|
||||
if (deferredValidationFileIds.size > 0) {
|
||||
onDeferredValidationCandidates?.(deferredValidationFileIds);
|
||||
if (deferredValidationCandidates.size > 0) {
|
||||
onDeferredValidationCandidates?.(deferredValidationCandidates);
|
||||
}
|
||||
await drainProgressiveBatches();
|
||||
// Same filter for the final flush so validated cache hits remain a no-op.
|
||||
const batchFiles = files[batch].filter(
|
||||
(f) => emitPolicy === "all" || !f.loadedFromCache,
|
||||
);
|
||||
try {
|
||||
//in try block because by the time files are loaded the user may have closed the view
|
||||
addFiles(batchFiles, this.isDark, true);
|
||||
} catch (e: unknown) {
|
||||
errorlog({ where: "EmbeddedFileLoader.loadSceneFiles", error: e });
|
||||
}
|
||||
// The helper retains the try/catch because the user may have closed the
|
||||
// view by the time the asynchronous image work completes.
|
||||
this.terminalState = "completed";
|
||||
flushFiles(batchFiles, true);
|
||||
} catch (error: unknown) {
|
||||
this.terminalState = "failed";
|
||||
errorlog({
|
||||
where: "EmbeddedFileLoader.loadSceneFiles",
|
||||
uid: this.uid,
|
||||
phase: "pool",
|
||||
error,
|
||||
});
|
||||
const batchFiles = files[batch].filter(
|
||||
(f) => emitPolicy === "all" || !f.loadedFromCache,
|
||||
);
|
||||
flushFiles(batchFiles, true);
|
||||
} finally {
|
||||
onLoadTaskSettled = null;
|
||||
window.clearInterval(addFilesTimer);
|
||||
if (!finalFlushed) {
|
||||
if (this.terminalState === "running") {
|
||||
this.terminalState = this.terminate ? "terminated" : "failed";
|
||||
}
|
||||
const batchFiles = this.terminate
|
||||
? undefined
|
||||
: files[batch].filter(
|
||||
(f) => emitPolicy === "all" || !f.loadedFromCache,
|
||||
);
|
||||
flushFiles(batchFiles, true);
|
||||
}
|
||||
this.emptyPDFDocsMap();
|
||||
}
|
||||
}
|
||||
@@ -1609,6 +1937,7 @@ export class EmbeddedFilesLoader {
|
||||
const cachedData = shouldUseCache
|
||||
? await getImageCache().getImageCacheData(cacheKey, {
|
||||
skipDependencyCheck: options?.cacheValidation === "stale-first",
|
||||
expectedPayloadKind: "raster",
|
||||
minRenderScale:
|
||||
options?.cacheValidation === "stale-first"
|
||||
? undefined
|
||||
@@ -1624,7 +1953,7 @@ export class EmbeddedFilesLoader {
|
||||
options?.cacheValidation === "stale-first" &&
|
||||
cachedScale < requestedScale
|
||||
) {
|
||||
options?.onStaleCacheHit?.();
|
||||
options?.onStaleCacheHit?.({ kind: "reload" });
|
||||
}
|
||||
return [
|
||||
`data:image/png;base64,${await blobToBase64(cachedData.blob)}` as DataURL,
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -236,10 +245,12 @@ const GAP = 4;
|
||||
/**
|
||||
* ExcalidrawAutomate is a utility class that provides a simplified API to interact with Excalidraw elements and the Excalidraw canvas.
|
||||
* Elements in the Excalidraw Scene are immutable. You should never directly change element properties in the scene object.
|
||||
* ExcalidrawAutomate provides a "workbench" where you can create, modify, and delete elements before committing them to the Excalidraw Scene.
|
||||
* The basic workflow is to create elements in ExcalidrawAutomate and once ready commit them to the Excalidraw Scene using addElementsToView().
|
||||
* To modify elements in the scene, you should first copy them over to EA using copyViewElementsToEAforEditing, make the necessary modifications,
|
||||
* then commit them back to the scene using addElementsToView().
|
||||
* ExcalidrawAutomate provides a stateful, in-memory "workbench" where you can create, modify, and delete elements independently of the Excalidraw Scene.
|
||||
* Begin each independent transaction with clear(). To modify existing scene elements while preserving their identity, copy them to the workbench with
|
||||
* copyViewElementsToEAforEditing() and modify the copies returned by getElement(originalId). Commit persistent edits with addElementsToView(),
|
||||
* or use the modified workbench elements for a temporary EA operation such as export and then discard them with clear() without committing.
|
||||
* cloneElement() and cloneElements() deliberately generate new IDs and are only for creating genuine duplicates, never for editing an existing scene element.
|
||||
* Do not interleave asynchronous operations that mutate the same EA workbench; await the operation, then clear before starting another transaction.
|
||||
* To delete an element from the view set element.isDeleted = true and commit the changes to the scene using addElementsToView().
|
||||
*
|
||||
* At a very high level, EA has 3 type of functions:
|
||||
@@ -574,7 +585,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") {
|
||||
@@ -832,6 +843,8 @@ export class ExcalidrawAutomate {
|
||||
};
|
||||
colorPalette: object;
|
||||
sidepanelTab: ExcalidrawSidepanelTab | null = null;
|
||||
private cleanupCallbacks: Array<{ callback: () => void }> = [];
|
||||
private destroyed = false;
|
||||
|
||||
constructor(plugin: ExcalidrawPlugin, view?: ExcalidrawView) {
|
||||
this.plugin = plugin;
|
||||
@@ -839,6 +852,37 @@ export class ExcalidrawAutomate {
|
||||
this.targetView = view;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers synchronous cleanup owned by this EA instance. Use this for
|
||||
* external listeners, observers, timers, and subscriptions that EA cannot
|
||||
* release itself. Cleanup runs when this EA is destroyed.
|
||||
* @param cleanup - Synchronous cleanup callback.
|
||||
* @returns A function that unregisters this callback without running it.
|
||||
*/
|
||||
public registerCleanup(cleanup: () => void): () => void {
|
||||
if (typeof cleanup !== "function") {
|
||||
errorMessage("cleanup must be a function", "registerCleanup()");
|
||||
return () => undefined;
|
||||
}
|
||||
if (this.destroyed) {
|
||||
try {
|
||||
cleanup();
|
||||
} catch (error: unknown) {
|
||||
log("ExcalidrawAutomate cleanup failed", error);
|
||||
}
|
||||
return () => undefined;
|
||||
}
|
||||
|
||||
const registration = { callback: cleanup };
|
||||
this.cleanupCallbacks.push(registration);
|
||||
return () => {
|
||||
const index = this.cleanupCallbacks.indexOf(registration);
|
||||
if (index !== -1) {
|
||||
this.cleanupCallbacks.splice(index, 1);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the active sidepanel tab for a script, if one exists.
|
||||
* If scriptName is omitted the function checks ea.activeScript.
|
||||
@@ -878,6 +922,18 @@ export class ExcalidrawAutomate {
|
||||
persist: boolean = false,
|
||||
reveal: boolean = true,
|
||||
): Promise<ExcalidrawSidepanelTab | null> {
|
||||
const existingSidepanel = ExcalidrawSidepanelView.getExisting(false);
|
||||
if (
|
||||
persist &&
|
||||
this.activeScript &&
|
||||
this.plugin?.scriptEngine?.isViewAutostartExecution(this) &&
|
||||
existingSidepanel?.hasPersistentScript(this.activeScript) &&
|
||||
existingSidepanel.getTabByScript(this.activeScript)
|
||||
) {
|
||||
log(
|
||||
`Warning: script "${this.activeScript}" attempted to create an already-active persistent sidepanel during view autostart. Consider branching on utils.executionSource === "view-autostart".`,
|
||||
);
|
||||
}
|
||||
if (this.sidepanelTab) {
|
||||
this.sidepanelTab.close();
|
||||
}
|
||||
@@ -1440,7 +1496,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,
|
||||
@@ -1662,7 +1718,7 @@ export class ExcalidrawAutomate {
|
||||
* @param {boolean} [options.selectedOnly=false] - Whether to include only the selected elements in the SVG.
|
||||
* @param {boolean} [options.skipInliningFonts=false] - Whether to skip inlining fonts in the SVG.
|
||||
* @param {boolean} [options.embedScene=false] - Whether to embed the scene in the SVG.
|
||||
* @param {ExcalidrawElement[]} [options.elementsOverride] - Optional override for the elements to include in the SVG. Primary to support the Printable Layout Wizard script
|
||||
* @param {readonly ExcalidrawElement[]} [options.elementsOverride] - Optional complete replacement for the view's exported elements. This array is not merged with the current scene or treated as a patch by ID: when supplied, only its non-deleted elements are exported. Include every element that should appear in the SVG.
|
||||
* @returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.
|
||||
*/
|
||||
async createViewSVG({
|
||||
@@ -1682,7 +1738,7 @@ export class ExcalidrawAutomate {
|
||||
selectedOnly?: boolean;
|
||||
skipInliningFonts?: boolean;
|
||||
embedScene?: boolean;
|
||||
elementsOverride?: ExcalidrawElement[];
|
||||
elementsOverride?: readonly ExcalidrawElement[];
|
||||
}): Promise<SVGSVGElement> {
|
||||
if (!this.targetView || !this.targetView.file || !this.targetView._loaded) {
|
||||
log("No view loaded");
|
||||
@@ -1715,7 +1771,7 @@ export class ExcalidrawAutomate {
|
||||
...{
|
||||
appState: {
|
||||
...scene.appState,
|
||||
theme: view.getViewExportTheme(theme),
|
||||
theme: view.getViewExportTheme(theme) as "dark" | "light",
|
||||
exportEmbedScene: view.getViewExportEmbedScene(embedScene),
|
||||
},
|
||||
},
|
||||
@@ -3075,7 +3131,9 @@ export class ExcalidrawAutomate {
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears elementsDict and imagesDict only.
|
||||
* Clears the EA workbench (`elementsDict` and `imagesDict`) without changing
|
||||
* the scene, target view, or current style. Call this before each independent
|
||||
* workbench transaction and before repurposing an EA instance.
|
||||
*/
|
||||
clear(): void {
|
||||
this.elementsDict = {};
|
||||
@@ -3122,7 +3180,7 @@ export class ExcalidrawAutomate {
|
||||
return this.plugin.isExcalidrawFile(f);
|
||||
}
|
||||
|
||||
targetView: ExcalidrawView = null; //the view currently edited
|
||||
targetView: ExcalidrawView | null = null; //the view currently edited
|
||||
/**
|
||||
* Sets the target view for EA. All view operations and all access to the Excalidraw API
|
||||
* will be performed on this view.
|
||||
@@ -3130,12 +3188,15 @@ export class ExcalidrawAutomate {
|
||||
* Typical usage:
|
||||
* - `setView()` to pick a sensible default automatically
|
||||
* - `setView(excalidrawView)` to explicitly target a specific view
|
||||
* - `setView(null)` to explicitly clear `targetView`
|
||||
*
|
||||
* Selectors:
|
||||
* - If `view` is `null` or `undefined` (or `"auto"`), EA will pick a sensible default:
|
||||
* - If `view` is `undefined` (or `"auto"`), EA will pick a sensible default:
|
||||
* 1) the currently active Excalidraw view (if any),
|
||||
* 2) otherwise the last active Excalidraw view (if it is still available),
|
||||
* 3) otherwise the `"first"` Excalidraw view in the workspace.
|
||||
* - If `view` is explicitly `null`, EA clears `targetView`. This is useful for
|
||||
* sidepanels when focus moves to a Markdown view or no drawing is eligible.
|
||||
* - If `show` is `true`, the view will be revealed (brought to front) and focused.
|
||||
*
|
||||
* Deprecated selectors (kept for backward compatibility):
|
||||
@@ -3147,18 +3208,22 @@ export class ExcalidrawAutomate {
|
||||
* necessarily match what a user would consider the “first”/“leftmost”/“topmost” view;
|
||||
* from a user's perspective it may appear effectively random.**
|
||||
*
|
||||
* @param {ExcalidrawView | "auto" | "first" | "active" | null | undefined} [view] - The view (or selector) to set as target.
|
||||
* @param {ExcalidrawView | "auto" | "first" | "active" | null | undefined} [view] - The view or selector to set as target. Pass `null` to clear the target.
|
||||
* @param {boolean} [show=false] - Whether to reveal/focus the target view.
|
||||
* @returns {ExcalidrawView} The ExcalidrawView that was set as `targetView` (or `null` if none found).
|
||||
* @returns {ExcalidrawView | null} The ExcalidrawView that was set as `targetView`, or `null` when cleared or none was found.
|
||||
*/
|
||||
setView(
|
||||
view?: ExcalidrawView | "auto" | "first" | "active" | null,
|
||||
show: boolean = false,
|
||||
): ExcalidrawView {
|
||||
): ExcalidrawView | null {
|
||||
const app = this.plugin.app;
|
||||
const workspace = app.workspace;
|
||||
const setView = () => {
|
||||
if (!view || view === "auto") {
|
||||
if (view === null) {
|
||||
this.targetView = null;
|
||||
return;
|
||||
}
|
||||
if (view === undefined || view === "auto") {
|
||||
view = workspace.getActiveViewOfType(ExcalidrawView);
|
||||
if (view instanceof ExcalidrawView) {
|
||||
this.targetView = view;
|
||||
@@ -3397,7 +3462,12 @@ export class ExcalidrawAutomate {
|
||||
if (fileIDWhiteList.size > 0) {
|
||||
this.targetView.setDirty();
|
||||
await new Promise<void>((resolve) => {
|
||||
void this.targetView.loadSceneFiles(false, fileIDWhiteList, resolve);
|
||||
void this.targetView.loadSceneFiles(
|
||||
false,
|
||||
fileIDWhiteList,
|
||||
resolve,
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -3558,12 +3628,15 @@ export class ExcalidrawAutomate {
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies elements from the view to elementsDict for editing.
|
||||
* Copies existing scene elements to the workbench as mutable, identity-preserving copies.
|
||||
* The copies can be committed with `addElementsToView()` to update the original
|
||||
* scene elements, or used temporarily by another EA operation and discarded with
|
||||
* `clear()` without modifying the scene.
|
||||
* @param {ExcalidrawElement[]} elements - Array of elements to copy.
|
||||
* @param {boolean} [copyImages=false] - Whether to copy images as well.
|
||||
*/
|
||||
copyViewElementsToEAforEditing(
|
||||
elements: ExcalidrawElement[],
|
||||
elements: readonly ExcalidrawElement[],
|
||||
copyImages: boolean = false,
|
||||
): void {
|
||||
if (copyImages && elements.some((el) => el.type === "image")) {
|
||||
@@ -3839,6 +3912,142 @@ 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). The menu is temporarily hidden while the selected frame's
|
||||
* title is being edited, so custom actions do not obstruct the title editor.
|
||||
* 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.
|
||||
* @param {string} [message] - Optional script-provided explanation displayed as the second paragraph of the permission prompt.
|
||||
* @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(
|
||||
message?: string,
|
||||
): 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 explanation = message?.trim();
|
||||
const prompt = new MultiOptionConfirmationPrompt<
|
||||
"allow" | "deny" | "pending" | null
|
||||
>(
|
||||
this.plugin,
|
||||
`<p><b>${scriptName}</b> ${t("AUTOSTART_SCRIPT_PROMPT")}</p>` +
|
||||
(explanation ? `<p>${explanation}</p>` : "") +
|
||||
`<p><span style="color: var(--text-muted); font-size: var(--font-smaller);">` +
|
||||
`${t("AUTOSTART_SCRIPT_PROMPT_MANAGE_HINT")}</span></p>`,
|
||||
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.
|
||||
*/
|
||||
@@ -4359,6 +4568,7 @@ export class ExcalidrawAutomate {
|
||||
}
|
||||
this.plugin.settings.scriptEngineSettings[this.activeScript] = settings;
|
||||
await this.plugin.saveSettings();
|
||||
this.plugin.refreshSettingsTab();
|
||||
}
|
||||
|
||||
public setScriptSettingValue(key: string, value: ScriptSettingValue): void {
|
||||
@@ -4383,6 +4593,7 @@ export class ExcalidrawAutomate {
|
||||
public async saveScriptSettings(): Promise<void> {
|
||||
ensureActiveScriptSettingsObject(this);
|
||||
await this.plugin.saveSettings();
|
||||
this.plugin.refreshSettingsTab();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4571,12 +4782,15 @@ export class ExcalidrawAutomate {
|
||||
}
|
||||
|
||||
/**
|
||||
* Clones the specified element with a new ID.
|
||||
* Clones the specified element with a new ID for insertion as a genuine duplicate.
|
||||
* Do not use this to edit an existing scene element; use
|
||||
* `copyViewElementsToEAforEditing()` and retrieve the workbench copy by its
|
||||
* original ID instead.
|
||||
* @param {ExcalidrawElement} element - The element to clone.
|
||||
* @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 +4811,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 +4865,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 +4896,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 +5118,7 @@ export class ExcalidrawAutomate {
|
||||
);
|
||||
return false;
|
||||
}
|
||||
this.copyViewElementsToEAforEditing(
|
||||
res.content as unknown as ExcalidrawElement[],
|
||||
);
|
||||
this.copyViewElementsToEAforEditing(res.content);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -4950,9 +5179,23 @@ export class ExcalidrawAutomate {
|
||||
}
|
||||
|
||||
/**
|
||||
* Destroys the ExcalidrawAutomate instance, clearing all references and data.
|
||||
* Destroys this EA once, first releasing registered external resources and
|
||||
* then clearing the ordinary EA state and references.
|
||||
*/
|
||||
destroy(): void {
|
||||
if (this.destroyed) {
|
||||
return;
|
||||
}
|
||||
this.destroyed = true;
|
||||
const cleanups = this.cleanupCallbacks.reverse();
|
||||
this.cleanupCallbacks = [];
|
||||
cleanups.forEach(({ callback }) => {
|
||||
try {
|
||||
callback();
|
||||
} catch (error: unknown) {
|
||||
log("ExcalidrawAutomate cleanup failed", error);
|
||||
}
|
||||
});
|
||||
this.sidepanelTab?.close();
|
||||
this.targetView = null;
|
||||
this.plugin = null;
|
||||
|
||||
@@ -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;
|
||||
|
||||
+326
-687
File diff suppressed because it is too large.
Load diff
+343
-134
@@ -1,4 +1,5 @@
|
||||
import { App, Notice, TFile } from "obsidian";
|
||||
import { App, Notice } 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";
|
||||
@@ -6,16 +7,26 @@ import { log } from "../utils/debugHelper";
|
||||
import { FILENAMEPARTS, PreviewImageType } from "../types/utilTypes";
|
||||
import { hasExcalidrawEmbeddedImagesTreeChanged } from "../utils/fileUtils";
|
||||
import { EXCALIDRAW_PLUGIN } from "src/constants/constants";
|
||||
import { blobToDataURL } from "../utils/coreUtils";
|
||||
import { isInstanceOfSVGSVGElement } from "../utils/typechecks";
|
||||
import { BackupPersistenceQueue } from "./BackupPersistenceQueue";
|
||||
|
||||
type FileCacheData = {
|
||||
schemaVersion: 2;
|
||||
payloadKind: "svg" | "raster";
|
||||
mtime: number;
|
||||
lastAccessed?: number;
|
||||
blob?: Blob;
|
||||
svg?: string;
|
||||
blob: Blob;
|
||||
renderScale?: number;
|
||||
size?: Size;
|
||||
hasSVGwithBitmap?: boolean;
|
||||
pdfPageViewProps?: PDFPageViewProps;
|
||||
};
|
||||
type ImageCacheMetadata = Partial<
|
||||
Pick<
|
||||
FileCacheData,
|
||||
"renderScale" | "size" | "hasSVGwithBitmap" | "pdfPageViewProps"
|
||||
>
|
||||
>;
|
||||
type BackupData = string;
|
||||
type BackupKey = string;
|
||||
|
||||
@@ -34,6 +45,16 @@ export type ImageKey = {
|
||||
type GetImageFromCacheOptions = {
|
||||
skipDependencyCheck?: boolean;
|
||||
minRenderScale?: number;
|
||||
expectedPayloadKind?: FileCacheData["payloadKind"];
|
||||
requireSvgInspectionMetadata?: boolean;
|
||||
svgFormat?: "element" | "data-url";
|
||||
onCacheHit?: (metadata: {
|
||||
mtime: number;
|
||||
renderScale?: number;
|
||||
size?: Size;
|
||||
hasSVGwithBitmap?: boolean;
|
||||
payloadKind: FileCacheData["payloadKind"];
|
||||
}) => void;
|
||||
};
|
||||
|
||||
const getKey = (key: ImageKey): string =>
|
||||
@@ -54,7 +75,9 @@ const getKey = (key: ImageKey): string =>
|
||||
class ImageCache {
|
||||
private dbName: string;
|
||||
private cacheStoreName: string;
|
||||
private cacheAccessStoreName: string;
|
||||
private backupStoreName: string;
|
||||
private legacyCacheStoreNames: readonly string[];
|
||||
private db: IDBDatabase | null;
|
||||
private isInitializing: boolean;
|
||||
private plugin: ExcalidrawPlugin;
|
||||
@@ -63,6 +86,18 @@ class ImageCache {
|
||||
private obsidanURLCache = new Map<string, string>();
|
||||
private purgeInvalidCacheTimer: number = null;
|
||||
private purgeInvalidBackupTimer: number = null;
|
||||
private touchedCacheKeys = new Set<string>();
|
||||
private cacheReadinessPromise: Promise<void> | null = null;
|
||||
private backupWrites = new BackupPersistenceQueue({
|
||||
ownerWindow: window,
|
||||
write: (filepath, data) => this.addBAKToCache(filepath, data),
|
||||
onError: (error, stage) =>
|
||||
errorlog({
|
||||
where: "ImageCache.backupWrites",
|
||||
fn: stage,
|
||||
error,
|
||||
}),
|
||||
});
|
||||
|
||||
private getCacheRetentionCutoff(): number {
|
||||
const retentionDays = Math.max(
|
||||
@@ -72,29 +107,28 @@ class ImageCache {
|
||||
return Date.now() - retentionDays * 24 * 60 * 60 * 1000;
|
||||
}
|
||||
|
||||
private touchCacheData(key: string, cacheData: FileCacheData): void {
|
||||
if (!this.db) {
|
||||
/**
|
||||
* Records cache use without rewriting the potentially very large image value.
|
||||
* The access store has a disjoint transaction scope, so these small writes do
|
||||
* not block image-cache reads. One write per key and plugin session is enough
|
||||
* for retention-based housekeeping.
|
||||
*/
|
||||
private touchCacheData(key: string): void {
|
||||
if (!this.db || this.touchedCacheKeys.has(key)) {
|
||||
return;
|
||||
}
|
||||
const nextLastAccessed = Date.now();
|
||||
// Avoid rewriting IndexedDB on every cache hit while still keeping actively used
|
||||
// entries alive for retention-based purging.
|
||||
if (
|
||||
cacheData.lastAccessed &&
|
||||
nextLastAccessed - cacheData.lastAccessed < 60 * 1000
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const transaction = this.db.transaction(this.cacheStoreName, "readwrite");
|
||||
const store = transaction.objectStore(this.cacheStoreName);
|
||||
store.put(
|
||||
{
|
||||
...cacheData,
|
||||
lastAccessed: nextLastAccessed,
|
||||
},
|
||||
key,
|
||||
this.touchedCacheKeys.add(key);
|
||||
const transaction = this.db.transaction(
|
||||
this.cacheAccessStoreName,
|
||||
"readwrite",
|
||||
);
|
||||
const request = transaction
|
||||
.objectStore(this.cacheAccessStoreName)
|
||||
.put(Date.now(), key);
|
||||
request.onerror = (event) => {
|
||||
event.preventDefault();
|
||||
this.touchedCacheKeys.delete(key);
|
||||
};
|
||||
}
|
||||
|
||||
public destroy(): void {
|
||||
@@ -105,23 +139,74 @@ class ImageCache {
|
||||
if (this.purgeInvalidBackupTimer) {
|
||||
window.clearTimeout(this.purgeInvalidBackupTimer);
|
||||
}
|
||||
this.backupWrites.destroy();
|
||||
this.db?.close();
|
||||
this.db = null;
|
||||
this.plugin = null;
|
||||
this.app = null;
|
||||
this.obsidanURLCache.forEach((url) => URL.revokeObjectURL(url));
|
||||
this.obsidanURLCache.clear();
|
||||
this.obsidanURLCache = null;
|
||||
this.touchedCacheKeys.clear();
|
||||
this.cacheReadinessPromise = null;
|
||||
}
|
||||
|
||||
constructor(dbName: string, cacheStoreName: string, backupStoreName: string) {
|
||||
constructor(
|
||||
dbName: string,
|
||||
cacheStoreName: string,
|
||||
cacheAccessStoreName: string,
|
||||
backupStoreName: string,
|
||||
legacyCacheStoreNames: readonly string[],
|
||||
) {
|
||||
this.dbName = dbName;
|
||||
this.cacheStoreName = cacheStoreName;
|
||||
this.cacheAccessStoreName = cacheAccessStoreName;
|
||||
this.backupStoreName = backupStoreName;
|
||||
this.legacyCacheStoreNames = legacyCacheStoreNames;
|
||||
this.db = null;
|
||||
this.isInitializing = false;
|
||||
this.plugin = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the current cache stores and removes disposable legacy image-cache
|
||||
* stores in the same IndexedDB version-change transaction.
|
||||
*
|
||||
* The drawing backup store is deliberately preserved. Legacy image payloads
|
||||
* are not converted because doing so would deserialize and rewrite the full
|
||||
* cache during startup; the v2 cache is rebuilt lazily as images are used.
|
||||
*/
|
||||
private applyStoreSchema(db: IDBDatabase): void {
|
||||
if (!db.objectStoreNames.contains(this.cacheStoreName)) {
|
||||
db.createObjectStore(this.cacheStoreName);
|
||||
}
|
||||
if (!db.objectStoreNames.contains(this.cacheAccessStoreName)) {
|
||||
db.createObjectStore(this.cacheAccessStoreName);
|
||||
}
|
||||
if (!db.objectStoreNames.contains(this.backupStoreName)) {
|
||||
db.createObjectStore(this.backupStoreName);
|
||||
}
|
||||
this.legacyCacheStoreNames.forEach((storeName) => {
|
||||
if (
|
||||
storeName !== this.backupStoreName &&
|
||||
db.objectStoreNames.contains(storeName)
|
||||
) {
|
||||
db.deleteObjectStore(storeName);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private requiresStoreUpgrade(db: IDBDatabase): boolean {
|
||||
return (
|
||||
!db.objectStoreNames.contains(this.cacheStoreName) ||
|
||||
!db.objectStoreNames.contains(this.cacheAccessStoreName) ||
|
||||
!db.objectStoreNames.contains(this.backupStoreName) ||
|
||||
this.legacyCacheStoreNames.some((storeName) =>
|
||||
db.objectStoreNames.contains(storeName),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public async initializeDB(plugin: ExcalidrawPlugin): Promise<void> {
|
||||
this.plugin = plugin;
|
||||
this.app = plugin.app;
|
||||
@@ -136,12 +221,7 @@ class ImageCache {
|
||||
|
||||
request.onupgradeneeded = (event: IDBVersionChangeEvent) => {
|
||||
const db = (event.target as IDBOpenDBRequest).result;
|
||||
if (!db.objectStoreNames.contains(this.cacheStoreName)) {
|
||||
db.createObjectStore(this.cacheStoreName);
|
||||
}
|
||||
if (!db.objectStoreNames.contains(this.backupStoreName)) {
|
||||
db.createObjectStore(this.backupStoreName);
|
||||
}
|
||||
this.applyStoreSchema(db);
|
||||
};
|
||||
|
||||
this.db = await new Promise<IDBDatabase>((resolve, reject) => {
|
||||
@@ -159,23 +239,16 @@ class ImageCache {
|
||||
};
|
||||
});
|
||||
|
||||
// Pre-create the object stores to reduce delay when accessing them later
|
||||
if (
|
||||
!this.db.objectStoreNames.contains(this.cacheStoreName) ||
|
||||
!this.db.objectStoreNames.contains(this.backupStoreName)
|
||||
) {
|
||||
// Existing databases are upgraded atomically: create v2 stores, remove
|
||||
// disposable v1 image stores, and leave drawingBAK untouched.
|
||||
if (this.requiresStoreUpgrade(this.db)) {
|
||||
const version = this.db.version + 1;
|
||||
this.db.close();
|
||||
|
||||
const upgradeRequest = indexedDB.open(this.dbName, version);
|
||||
upgradeRequest.onupgradeneeded = (event: IDBVersionChangeEvent) => {
|
||||
const db = (event.target as IDBOpenDBRequest).result;
|
||||
if (!db.objectStoreNames.contains(this.cacheStoreName)) {
|
||||
db.createObjectStore(this.cacheStoreName);
|
||||
}
|
||||
if (!db.objectStoreNames.contains(this.backupStoreName)) {
|
||||
db.createObjectStore(this.backupStoreName);
|
||||
}
|
||||
this.applyStoreSchema(db);
|
||||
};
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
@@ -206,6 +279,10 @@ class ImageCache {
|
||||
});
|
||||
}
|
||||
|
||||
// All initial cache consumers share this probe instead of racing separate
|
||||
// reads against a short timeout. Once it resolves, normal reads can proceed.
|
||||
await this.ensureCacheStoreReady();
|
||||
|
||||
this.purgeInvalidCacheTimer = window.setTimeout(() => {
|
||||
this.purgeInvalidCacheTimer = null;
|
||||
void this.purgeInvalidCacheFiles();
|
||||
@@ -215,69 +292,121 @@ class ImageCache {
|
||||
this.purgeInvalidBackupTimer = null;
|
||||
void this.purgeInvalidBackupFiles();
|
||||
}, 120000);
|
||||
} catch (error) {
|
||||
// An upgrade failure can leave `this.db` pointing at the closed legacy
|
||||
// connection. Do not advertise a broken cache as ready to consumers.
|
||||
this.db?.close();
|
||||
this.db = null;
|
||||
this.cacheReadinessPromise = null;
|
||||
throw error;
|
||||
} 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");
|
||||
}
|
||||
}
|
||||
|
||||
private ensureCacheStoreReady(): Promise<void> {
|
||||
if (this.cacheReadinessPromise !== null) {
|
||||
return this.cacheReadinessPromise;
|
||||
}
|
||||
this.cacheReadinessPromise = new Promise<void>((resolve, reject) => {
|
||||
const transaction = this.db.transaction(this.cacheStoreName, "readonly");
|
||||
const request = transaction
|
||||
.objectStore(this.cacheStoreName)
|
||||
.get("__excalidraw_cache_readiness_probe__");
|
||||
request.onsuccess = () => resolve();
|
||||
request.onerror = () =>
|
||||
reject(new Error("Failed to initialize image-cache reads."));
|
||||
});
|
||||
return this.cacheReadinessPromise;
|
||||
}
|
||||
|
||||
private async getCacheAccessTimes(): Promise<Map<string, number>> {
|
||||
const accessTimes = new Map<string, number>();
|
||||
const transaction = this.db.transaction(
|
||||
this.cacheAccessStoreName,
|
||||
"readonly",
|
||||
);
|
||||
const request = transaction
|
||||
.objectStore(this.cacheAccessStoreName)
|
||||
.openCursor();
|
||||
return new Promise<Map<string, number>>((resolve, reject) => {
|
||||
request.onsuccess = (event: Event) => {
|
||||
const cursor = (event.target as IDBRequest<IDBCursorWithValue | null>)
|
||||
.result;
|
||||
if (!cursor) {
|
||||
resolve(accessTimes);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
typeof cursor.key === "string" &&
|
||||
typeof cursor.value === "number"
|
||||
) {
|
||||
accessTimes.set(cursor.key, cursor.value);
|
||||
}
|
||||
cursor.continue();
|
||||
};
|
||||
request.onerror = () =>
|
||||
reject(new Error("Failed to retrieve image-cache access times."));
|
||||
});
|
||||
}
|
||||
|
||||
private isCurrentCacheData(cacheData: FileCacheData): boolean {
|
||||
return (
|
||||
cacheData?.schemaVersion === 2 &&
|
||||
(cacheData.payloadKind === "svg" || cacheData.payloadKind === "raster") &&
|
||||
cacheData.blob instanceof Blob
|
||||
);
|
||||
}
|
||||
|
||||
private async purgeInvalidCacheFiles(): Promise<void> {
|
||||
const accessTimes = await this.getCacheAccessTimes();
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const transaction = this.db.transaction(this.cacheStoreName, "readwrite");
|
||||
const transaction = this.db.transaction(
|
||||
[this.cacheStoreName, this.cacheAccessStoreName],
|
||||
"readwrite",
|
||||
);
|
||||
const store = transaction.objectStore(this.cacheStoreName);
|
||||
const files = this.app.vault.getFiles();
|
||||
const deletePromises: Promise<void>[] = [];
|
||||
const accessStore = transaction.objectStore(this.cacheAccessStoreName);
|
||||
const request = store.openCursor();
|
||||
transaction.oncomplete = () => resolve();
|
||||
transaction.onerror = () =>
|
||||
reject(
|
||||
transaction.error ??
|
||||
new Error("Failed to purge invalid image-cache entries."),
|
||||
);
|
||||
request.onsuccess = (event: Event) => {
|
||||
const cursor = (event.target as IDBRequest<IDBCursorWithValue | null>)
|
||||
.result;
|
||||
if (cursor) {
|
||||
const key = cursor.key as string;
|
||||
const isLegacyKey = key.split("#").length - 1 < 13; // introduced hasGroupref, etc. in 1.9.28 // introduced hasClippedFrameref in 2.2.10 //introduced inlineFonts 2.2.11 //introduced cacheId in 2.23.x
|
||||
const cacheData = cursor.value as FileCacheData;
|
||||
// Cache-key suffixes such as transparency and padding are optional, so
|
||||
// separator counts cannot identify an old schema reliably. Unreachable
|
||||
// legacy entries are harmless and age out through normal retention.
|
||||
const filepath = key.split("#")[0];
|
||||
const fileExists = files.some((f: TFile) => f.path === filepath);
|
||||
const file = fileExists
|
||||
? files.find((f: TFile) => f.path === filepath)
|
||||
: null;
|
||||
const lastAccessed = cursor.value.lastAccessed ?? cursor.value.mtime;
|
||||
const file = this.app.vault.getFileByPath(filepath);
|
||||
const lastAccessed = accessTimes.get(key) ?? cacheData.mtime;
|
||||
const isExpired = lastAccessed < this.getCacheRetentionCutoff();
|
||||
if (
|
||||
isLegacyKey ||
|
||||
!file ||
|
||||
(file && file.stat.mtime > cursor.value.mtime) ||
|
||||
(!cursor.value.blob && !cursor.value.svg) ||
|
||||
(file && file.stat.mtime > cacheData.mtime) ||
|
||||
!this.isCurrentCacheData(cacheData) ||
|
||||
isExpired
|
||||
) {
|
||||
if (this.obsidanURLCache.has(key)) {
|
||||
URL.revokeObjectURL(this.obsidanURLCache.get(key));
|
||||
this.obsidanURLCache.delete(key);
|
||||
}
|
||||
deletePromises.push(
|
||||
new Promise<void>((innerResolve, innerReject) => {
|
||||
const deleteRequest = store.delete(cursor.primaryKey);
|
||||
deleteRequest.onsuccess = () => innerResolve();
|
||||
deleteRequest.onerror = () => {
|
||||
const error = deleteRequest.error;
|
||||
const errorMsg = `Failed to delete file with key: ${key}. Error: ${error.message}`;
|
||||
innerReject(new Error(errorMsg));
|
||||
};
|
||||
}),
|
||||
);
|
||||
store.delete(cursor.primaryKey);
|
||||
accessStore.delete(cursor.primaryKey);
|
||||
this.touchedCacheKeys.delete(key);
|
||||
}
|
||||
cursor.continue();
|
||||
} else {
|
||||
Promise.all(deletePromises)
|
||||
.then(() => {
|
||||
transaction.commit();
|
||||
resolve();
|
||||
})
|
||||
.catch((error) => reject(error as Error));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -297,7 +426,6 @@ class ImageCache {
|
||||
private async purgeInvalidBackupFiles(): Promise<void> {
|
||||
const transaction = this.db.transaction(this.backupStoreName, "readwrite");
|
||||
const store = transaction.objectStore(this.backupStoreName);
|
||||
const files = this.app.vault.getFiles();
|
||||
const deletePromises: Promise<void>[] = [];
|
||||
const request = store.openCursor();
|
||||
return await new Promise<void>((resolve, reject) => {
|
||||
@@ -306,7 +434,7 @@ class ImageCache {
|
||||
.result;
|
||||
if (cursor) {
|
||||
const key = cursor.key as BackupKey;
|
||||
const fileExists = files.some((f: TFile) => f.path === key);
|
||||
const fileExists = Boolean(this.app.vault.getFileByPath(key));
|
||||
if (!fileExists) {
|
||||
deletePromises.push(
|
||||
new Promise<void>((resolve, reject) => {
|
||||
@@ -392,52 +520,49 @@ class ImageCache {
|
||||
);
|
||||
}
|
||||
|
||||
private fullyInitialized = false;
|
||||
|
||||
private async getResolvedCacheData(
|
||||
key_: ImageKey,
|
||||
options?: GetImageFromCacheOptions,
|
||||
): Promise<{ cacheData: FileCacheData; key: string } | undefined> {
|
||||
const key = getKey(key_);
|
||||
if (!this.isReady()) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const key = getKey(key_);
|
||||
|
||||
try {
|
||||
const cachedData = this.fullyInitialized
|
||||
? await this.getCacheData(key)
|
||||
: await Promise.race([
|
||||
this.getCacheData(key),
|
||||
new Promise<undefined>((_, reject) =>
|
||||
window.setTimeout(() => {
|
||||
reject(new Error("Timeout while retrieving cache data"));
|
||||
}, 200),
|
||||
),
|
||||
]);
|
||||
this.fullyInitialized = true;
|
||||
await this.ensureCacheStoreReady();
|
||||
|
||||
const cachedData = await this.getCacheData(key);
|
||||
if (!cachedData) {
|
||||
return undefined;
|
||||
}
|
||||
if (!this.isCurrentCacheData(cachedData)) {
|
||||
const transaction = this.db.transaction(
|
||||
[this.cacheStoreName, this.cacheAccessStoreName],
|
||||
"readwrite",
|
||||
);
|
||||
transaction.objectStore(this.cacheStoreName).delete(key);
|
||||
transaction.objectStore(this.cacheAccessStoreName).delete(key);
|
||||
this.touchedCacheKeys.delete(key);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const file = this.app.vault.getAbstractFileByPath(
|
||||
key_.filepath.split("#")[0],
|
||||
);
|
||||
if (!file || !(file instanceof TFile)) {
|
||||
const file = this.app.vault.getFileByPath(key_.filepath.split("#")[0]);
|
||||
if (!file) {
|
||||
return undefined;
|
||||
}
|
||||
if (cachedData.mtime < file.stat.mtime) {
|
||||
return undefined;
|
||||
}
|
||||
if (
|
||||
!options?.skipDependencyCheck &&
|
||||
hasExcalidrawEmbeddedImagesTreeChanged(
|
||||
if (!options?.skipDependencyCheck) {
|
||||
const dependencyChanged = hasExcalidrawEmbeddedImagesTreeChanged(
|
||||
file,
|
||||
cachedData.mtime,
|
||||
this.plugin,
|
||||
)
|
||||
) {
|
||||
return undefined;
|
||||
);
|
||||
if (dependencyChanged) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
// Validated reads can require a minimum render scale so lower-resolution PDF
|
||||
// snapshots are upgraded in the background without blocking the first paint.
|
||||
@@ -448,7 +573,27 @@ class ImageCache {
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
this.touchCacheData(key, cachedData);
|
||||
if (
|
||||
options?.expectedPayloadKind &&
|
||||
cachedData.payloadKind !== options.expectedPayloadKind
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
if (
|
||||
options?.requireSvgInspectionMetadata &&
|
||||
cachedData.payloadKind === "svg" &&
|
||||
typeof cachedData.hasSVGwithBitmap !== "boolean"
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
options?.onCacheHit?.({
|
||||
mtime: cachedData.mtime,
|
||||
renderScale: cachedData.renderScale,
|
||||
size: cachedData.size,
|
||||
hasSVGwithBitmap: cachedData.hasSVGwithBitmap,
|
||||
payloadKind: cachedData.payloadKind,
|
||||
});
|
||||
this.touchCacheData(key);
|
||||
return { cacheData: cachedData, key };
|
||||
} catch (error) {
|
||||
console.error(
|
||||
@@ -478,11 +623,12 @@ class ImageCache {
|
||||
}
|
||||
|
||||
const { cacheData, key } = resolved;
|
||||
if (cacheData.svg) {
|
||||
return convertSVGStringToElement(cacheData.svg);
|
||||
}
|
||||
if (!cacheData.blob) {
|
||||
return undefined;
|
||||
if (cacheData.payloadKind === "svg") {
|
||||
if (options?.svgFormat === "data-url") {
|
||||
return blobToDataURL(cacheData.blob);
|
||||
}
|
||||
const svgText = await cacheData.blob.text();
|
||||
return convertSVGStringToElement(svgText);
|
||||
}
|
||||
if (this.obsidanURLCache.has(key)) {
|
||||
return this.obsidanURLCache.get(key);
|
||||
@@ -492,6 +638,11 @@ class ImageCache {
|
||||
return obsidianURL;
|
||||
}
|
||||
|
||||
/** Returns the number of live raster blob URLs retained by the session cache. */
|
||||
public getObsidianURLCacheSize(): number {
|
||||
return this.obsidanURLCache?.size ?? 0;
|
||||
}
|
||||
|
||||
public releaseObsidianURL(url: string): void {
|
||||
if (!url || !this.obsidanURLCache) {
|
||||
return;
|
||||
@@ -521,39 +672,44 @@ class ImageCache {
|
||||
key_: ImageKey,
|
||||
obsidianURL: string,
|
||||
image: Blob | SVGSVGElement,
|
||||
metadata?: Partial<FileCacheData>,
|
||||
metadata?: ImageCacheMetadata,
|
||||
): void {
|
||||
if (!this.isReady()) {
|
||||
return; // Database not initialized yet
|
||||
}
|
||||
|
||||
const file = this.app.vault.getAbstractFileByPath(
|
||||
key_.filepath.split("#")[0],
|
||||
);
|
||||
if (!file || !(file instanceof TFile)) {
|
||||
const file = this.app.vault.getFileByPath(key_.filepath.split("#")[0]);
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
|
||||
let svg: string = null;
|
||||
let blob: Blob = null;
|
||||
if (image instanceof SVGSVGElement) {
|
||||
svg = image.outerHTML;
|
||||
} else {
|
||||
blob = image;
|
||||
}
|
||||
const isSVGElement = isInstanceOfSVGSVGElement(image);
|
||||
const payloadKind =
|
||||
isSVGElement || image.type === "image/svg+xml" ? "svg" : "raster";
|
||||
const blob = isSVGElement
|
||||
? new Blob([image.outerHTML.replaceAll(" ", " ")], {
|
||||
type: "image/svg+xml",
|
||||
})
|
||||
: image;
|
||||
const now = Date.now();
|
||||
const data: FileCacheData = {
|
||||
schemaVersion: 2,
|
||||
payloadKind,
|
||||
mtime: now,
|
||||
lastAccessed: now,
|
||||
blob,
|
||||
svg,
|
||||
...metadata,
|
||||
};
|
||||
const transaction = this.db.transaction(this.cacheStoreName, "readwrite");
|
||||
const transaction = this.db.transaction(
|
||||
[this.cacheStoreName, this.cacheAccessStoreName],
|
||||
"readwrite",
|
||||
);
|
||||
const store = transaction.objectStore(this.cacheStoreName);
|
||||
const accessStore = transaction.objectStore(this.cacheAccessStoreName);
|
||||
const key = getKey(key_);
|
||||
store.put(data, key);
|
||||
if (!svg && obsidianURL) {
|
||||
accessStore.put(now, key);
|
||||
this.touchedCacheKeys.add(key);
|
||||
if (payloadKind === "raster" && obsidianURL) {
|
||||
if (
|
||||
this.obsidanURLCache.has(key) &&
|
||||
this.obsidanURLCache.get(key) !== obsidianURL
|
||||
@@ -575,9 +731,40 @@ class ImageCache {
|
||||
const transaction = this.db.transaction(this.backupStoreName, "readwrite");
|
||||
const store = transaction.objectStore(this.backupStoreName);
|
||||
store.put(data, filepath);
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
transaction.oncomplete = () => resolve();
|
||||
transaction.onerror = () =>
|
||||
reject(
|
||||
transaction.error ??
|
||||
new Error(`Failed to update backup file with key: ${filepath}`),
|
||||
);
|
||||
transaction.onabort = () =>
|
||||
reject(
|
||||
transaction.error ??
|
||||
new Error(`Backup update aborted for key: ${filepath}`),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules the latest backup payload through the plugin-global queue.
|
||||
*/
|
||||
public scheduleBAKToCache(
|
||||
filepath: string,
|
||||
data: BackupData,
|
||||
delayMs: number,
|
||||
): boolean {
|
||||
return this.backupWrites.schedule(filepath, data, delayMs);
|
||||
}
|
||||
|
||||
/** Flushes any queued backup before a drawing path is renamed. */
|
||||
public async flushPendingBAK(filepath: string): Promise<void> {
|
||||
await this.backupWrites.flush(filepath);
|
||||
}
|
||||
|
||||
public async removeBAKFromCache(filepath: string): Promise<void> {
|
||||
await this.backupWrites.cancel(filepath);
|
||||
if (!this.isReady()) {
|
||||
return; // Database not initialized yet
|
||||
}
|
||||
@@ -604,10 +791,15 @@ class ImageCache {
|
||||
this.obsidanURLCache.forEach((url) => URL.revokeObjectURL(url));
|
||||
this.obsidanURLCache.clear();
|
||||
|
||||
return this.clear(this.cacheStoreName, "Image cache was cleared");
|
||||
this.touchedCacheKeys.clear();
|
||||
return this.clear(
|
||||
[this.cacheStoreName, this.cacheAccessStoreName],
|
||||
"Image cache was cleared",
|
||||
);
|
||||
}
|
||||
|
||||
public async clearBackupCache(): Promise<void> {
|
||||
await this.backupWrites.cancelAll();
|
||||
if (!this.isReady()) {
|
||||
return; // Database not initialized yet
|
||||
}
|
||||
@@ -615,22 +807,31 @@ class ImageCache {
|
||||
return this.clear(this.backupStoreName, "All backups were cleared");
|
||||
}
|
||||
|
||||
private async clear(storeName: string, message: string): Promise<void> {
|
||||
private async clear(
|
||||
storeNames: string | string[],
|
||||
message: string,
|
||||
): Promise<void> {
|
||||
if (!this.isReady()) {
|
||||
return; // Database not initialized yet
|
||||
}
|
||||
|
||||
const transaction = this.db.transaction([storeName], "readwrite");
|
||||
const store = transaction.objectStore(storeName);
|
||||
const names = Array.isArray(storeNames) ? storeNames : [storeNames];
|
||||
const transaction = this.db.transaction(names, "readwrite");
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const request = store.clear();
|
||||
request.onsuccess = () => {
|
||||
const requests = names.map((name) =>
|
||||
transaction.objectStore(name).clear(),
|
||||
);
|
||||
transaction.oncomplete = () => {
|
||||
new Notice(message);
|
||||
resolve();
|
||||
};
|
||||
request.onerror = () =>
|
||||
reject(new Error(`Failed to clear ${storeName}.`));
|
||||
transaction.onerror = () =>
|
||||
reject(new Error(`Failed to clear ${names.join(", ")}.`));
|
||||
requests.forEach((request) => {
|
||||
request.onerror = () =>
|
||||
reject(new Error(`Failed to clear ${names.join(", ")}.`));
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -640,9 +841,17 @@ let imageCache: ImageCache = null;
|
||||
export const getImageCache = (): ImageCache => {
|
||||
if (!imageCache) {
|
||||
const DB_NAME = `Excalidraw ${EXCALIDRAW_PLUGIN.app.appId}`;
|
||||
const CACHE_STORE = "imageCache";
|
||||
const CACHE_STORE = "imageCacheV2";
|
||||
const CACHE_ACCESS_STORE = "imageCacheAccessV2";
|
||||
const BACKUP_STORE = "drawingBAK";
|
||||
imageCache = new ImageCache(DB_NAME, CACHE_STORE, BACKUP_STORE);
|
||||
const LEGACY_CACHE_STORES = ["imageCache", "imageCacheAccess"] as const;
|
||||
imageCache = new ImageCache(
|
||||
DB_NAME,
|
||||
CACHE_STORE,
|
||||
CACHE_ACCESS_STORE,
|
||||
BACKUP_STORE,
|
||||
LEGACY_CACHE_STORES,
|
||||
);
|
||||
}
|
||||
return imageCache;
|
||||
};
|
||||
+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,
|
||||
) => {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+809
-130
File diff suppressed because it is too large.
Load diff
@@ -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,
|
||||
@@ -88,6 +88,7 @@ export class InlineLinkSuggester
|
||||
private paragraphItems: ParagraphSuggestion[] = [];
|
||||
private frameItems: FrameSuggestion[] = [];
|
||||
private tagItems: TagSuggestion[] = [];
|
||||
private linkItemsLoaded = false;
|
||||
|
||||
constructor(
|
||||
app: App,
|
||||
@@ -98,8 +99,7 @@ export class InlineLinkSuggester
|
||||
surpessPlaceholder: boolean = false,
|
||||
collisionBoundary?: HTMLElement,
|
||||
) {
|
||||
const items = getLinkSuggestionsFiltered(app);
|
||||
super(app, inputEl, items, collisionBoundary);
|
||||
super(app, inputEl, [], collisionBoundary);
|
||||
this.plugin = plugin;
|
||||
this.getSourcePath = getSourcePath;
|
||||
this.widthHost = widthWrapper ?? inputEl;
|
||||
@@ -152,7 +152,7 @@ export class InlineLinkSuggester
|
||||
}
|
||||
|
||||
getItems(): InlineSuggestion[] {
|
||||
return getLinkSuggestionsFiltered(this.app);
|
||||
return this.items;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -205,9 +205,23 @@ export class InlineLinkSuggester
|
||||
* Refreshes the suggestion data (e.g. when vault changes) without recreating the instance.
|
||||
*/
|
||||
public refreshItems() {
|
||||
if (!this.linkItemsLoaded) {
|
||||
return;
|
||||
}
|
||||
this.items = getLinkSuggestionsFiltered(this.app);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the vault-wide file-link candidates only after a wikilink is active.
|
||||
*/
|
||||
private ensureLinkItemsLoaded() {
|
||||
if (this.linkItemsLoaded) {
|
||||
return;
|
||||
}
|
||||
this.items = getLinkSuggestionsFiltered(this.app);
|
||||
this.linkItemsLoaded = true;
|
||||
}
|
||||
|
||||
modifyInput(input: string): string {
|
||||
return input;
|
||||
}
|
||||
@@ -248,6 +262,10 @@ export class InlineLinkSuggester
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.mode === "file") {
|
||||
this.ensureLinkItemsLoaded();
|
||||
}
|
||||
|
||||
void (async () => {
|
||||
if (this.mode === "heading") {
|
||||
await this.loadHeadings(this.activeFile);
|
||||
|
||||
@@ -5,26 +5,26 @@ import { setStyle } from "src/utils/styleUtils";
|
||||
import { isInstanceOfHTMLElement } from "src/utils/typechecks";
|
||||
|
||||
declare const mainDocument: Document;
|
||||
declare const deliberateCreateElement: (document: Document, tagName: string) => HTMLElement;
|
||||
declare const deliberateCreateElement: (
|
||||
document: Document,
|
||||
tagName: string,
|
||||
) => HTMLElement;
|
||||
|
||||
export class ContentSearcher {
|
||||
private contentDiv: HTMLElement;
|
||||
private searchBar: HTMLInputElement;
|
||||
private prevButton: HTMLButtonElement;
|
||||
private nextButton: HTMLButtonElement;
|
||||
private exportMarkdown: HTMLButtonElement;
|
||||
private showHideButton: HTMLButtonElement;
|
||||
private customElemenentContainer: HTMLDivElement;
|
||||
private inputContainer: HTMLDivElement;
|
||||
private customElement: HTMLElement;
|
||||
private hitCount: HTMLSpanElement;
|
||||
private searchBarWrapper: HTMLDivElement;
|
||||
|
||||
constructor(contentDiv: HTMLElement, customElement?: HTMLElement) {
|
||||
constructor(contentDiv: HTMLElement) {
|
||||
this.contentDiv = contentDiv;
|
||||
this.customElement = customElement;
|
||||
this.createSearchElements();
|
||||
this.setupEventListeners();
|
||||
contentDiv.prepend(this.getSearchBarWrapper());
|
||||
contentDiv.prepend(this.searchBarWrapper);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -68,16 +68,6 @@ export class ContentSearcher {
|
||||
});
|
||||
setIcon(this.nextButton, "arrow-down");
|
||||
|
||||
this.exportMarkdown = createEl("button", {
|
||||
cls: ["clickable-icon", "document-search-button"],
|
||||
attr: {
|
||||
"aria-label": t("SEARCH_COPY_TO_CLIPBOARD_ARIA"),
|
||||
"data-tooltip-position": "top",
|
||||
},
|
||||
type: "button",
|
||||
});
|
||||
setIcon(this.exportMarkdown, "clipboard-copy");
|
||||
|
||||
this.showHideButton = createEl("button", {
|
||||
cls: ["clickable-icon", "document-search-button", "search-visible"],
|
||||
attr: {
|
||||
@@ -90,19 +80,12 @@ export class ContentSearcher {
|
||||
|
||||
buttonContainer.appendChild(this.prevButton);
|
||||
buttonContainer.appendChild(this.nextButton);
|
||||
buttonContainer.appendChild(this.exportMarkdown);
|
||||
buttonContainer.appendChild(this.showHideButton);
|
||||
|
||||
documentSearch.appendChild(this.inputContainer);
|
||||
documentSearch.appendChild(buttonContainer);
|
||||
|
||||
this.searchBarWrapper.appendChild(documentSearch);
|
||||
|
||||
this.customElemenentContainer = createDiv();
|
||||
if (this.customElement) {
|
||||
this.customElemenentContainer.appendChild(this.customElement);
|
||||
this.searchBarWrapper.appendChild(this.customElemenentContainer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -111,56 +94,11 @@ export class ContentSearcher {
|
||||
private setupEventListeners(): void {
|
||||
this.nextButton.onclick = () => this.navigateSearchResults("next");
|
||||
this.prevButton.onclick = () => this.navigateSearchResults("previous");
|
||||
this.exportMarkdown.onclick = () => {
|
||||
const exportContent = this.contentDiv.cloneNode(true) as HTMLElement;
|
||||
exportContent.querySelector(".excalidraw-search")?.remove();
|
||||
|
||||
const childNodes = Array.from(exportContent.childNodes);
|
||||
const startIndex = childNodes.findIndex(
|
||||
(node) => isInstanceOfHTMLElement(node) && node.tagName === "HR",
|
||||
);
|
||||
const nodesToExport =
|
||||
startIndex > -1 ? childNodes.slice(startIndex) : childNodes;
|
||||
// div should never be attached to the DOM
|
||||
const htmlContainer = deliberateCreateElement(mainDocument, "div");
|
||||
|
||||
nodesToExport.forEach((node) => {
|
||||
htmlContainer.appendChild(node.cloneNode(true));
|
||||
});
|
||||
|
||||
const html = htmlContainer.innerHTML;
|
||||
|
||||
function replaceHeading(html: string, level: number): string {
|
||||
const re = new RegExp(
|
||||
`<summary class="excalidraw-setting-h${level}">([^<]+)</summary>`,
|
||||
"g",
|
||||
);
|
||||
return html.replaceAll(
|
||||
re,
|
||||
`<summary class="excalidraw-setting-h${level}"><h${level}>$1</h${level}></summary>`,
|
||||
);
|
||||
}
|
||||
|
||||
let x = replaceHeading(html, 1);
|
||||
x = replaceHeading(x, 2);
|
||||
x = replaceHeading(x, 3);
|
||||
x = replaceHeading(x, 4);
|
||||
x = x.replaceAll(
|
||||
/<div class="setting-item-name">([^<]+)<\/div>/g,
|
||||
"<h5>$1</h5>",
|
||||
);
|
||||
|
||||
const md = htmlToMarkdown(x);
|
||||
void window.navigator.clipboard.writeText(md);
|
||||
new Notice(t("SEARCH_COPIED_TO_CLIPBOARD"));
|
||||
};
|
||||
this.showHideButton.onclick = () => {
|
||||
const setOpacity = (value: string | null) => {
|
||||
setStyle(this.inputContainer, { opacity: value });
|
||||
setStyle(this.prevButton, { opacity: value });
|
||||
setStyle(this.nextButton, { opacity: value });
|
||||
setStyle(this.exportMarkdown, { opacity: value });
|
||||
setStyle(this.customElemenentContainer, { opacity: value });
|
||||
};
|
||||
if (this.showHideButton.hasClass("search-visible")) {
|
||||
this.showHideButton.removeClass("search-visible");
|
||||
@@ -207,11 +145,49 @@ export class ContentSearcher {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the search bar wrapper element to add to the DOM
|
||||
*/
|
||||
public getSearchBarWrapper(): HTMLElement {
|
||||
return this.searchBarWrapper;
|
||||
/** Copies the complete legacy settings DOM as Markdown. */
|
||||
public copyContentAsMarkdown(): void {
|
||||
const exportContent = this.contentDiv.cloneNode(true) as HTMLElement;
|
||||
exportContent.querySelector(".excalidraw-search")?.remove();
|
||||
exportContent
|
||||
.querySelectorAll(".excalidraw-declarative-settings-toolbar")
|
||||
.forEach((toolbar) => toolbar.remove());
|
||||
|
||||
const childNodes = Array.from(exportContent.childNodes);
|
||||
const startIndex = childNodes.findIndex(
|
||||
(node) => isInstanceOfHTMLElement(node) && node.tagName === "HR",
|
||||
);
|
||||
const nodesToExport =
|
||||
startIndex > -1 ? childNodes.slice(startIndex) : childNodes;
|
||||
const htmlContainer = deliberateCreateElement(mainDocument, "div");
|
||||
|
||||
nodesToExport.forEach((node) => {
|
||||
htmlContainer.appendChild(node.cloneNode(true));
|
||||
});
|
||||
|
||||
const replaceHeading = (html: string, level: number): string => {
|
||||
const expression = new RegExp(
|
||||
`<summary class="excalidraw-setting-h${level}">([^<]+)</summary>`,
|
||||
"g",
|
||||
);
|
||||
return html.replaceAll(
|
||||
expression,
|
||||
`<summary class="excalidraw-setting-h${level}"><h${level}>$1</h${level}></summary>`,
|
||||
);
|
||||
};
|
||||
|
||||
let html = htmlContainer.innerHTML;
|
||||
for (let level = 1; level <= 4; level++) {
|
||||
html = replaceHeading(html, level);
|
||||
}
|
||||
html = html.replaceAll(
|
||||
/<div class="setting-item-name">([^<]+)<\/div>/g,
|
||||
"<h5>$1</h5>",
|
||||
);
|
||||
|
||||
const markdown = htmlToMarkdown(html);
|
||||
void window.navigator.clipboard.writeText(markdown);
|
||||
new Notice(t("SEARCH_COPIED_TO_CLIPBOARD"));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -239,7 +215,7 @@ export class ContentSearcher {
|
||||
nodesToReplace.forEach((node) => {
|
||||
const nodeContent = node.nodeValue;
|
||||
const newNode = createFragment();
|
||||
|
||||
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
const regex = new RegExp(escapeRegExp(searchTerm), "gi");
|
||||
|
||||
@@ -3,6 +3,15 @@ import { DEVICE } from "src/constants/constants";
|
||||
import type { SelectableFontOption } from "src/types/fontTypes";
|
||||
import { removeStyle, setStyle } from "src/utils/styleUtils";
|
||||
|
||||
declare const deliberateCreateElement: (
|
||||
document: Document,
|
||||
tagName: "style",
|
||||
) => HTMLStyleElement;
|
||||
|
||||
type BuiltInFontCssProvider = (
|
||||
fontFamily: string,
|
||||
) => Promise<string | null>;
|
||||
|
||||
type LoadedPreviewFont = {
|
||||
document: Document;
|
||||
face: FontFace;
|
||||
@@ -21,7 +30,8 @@ const quoteFontFamily = (fontFamily: string): string =>
|
||||
* The option provider is invoked whenever the menu opens, allowing vault font
|
||||
* additions, removals, and renames to appear without maintaining a file cache.
|
||||
* Local font binaries are loaded only for the selected option and visible menu
|
||||
* rows, and are registered in the document that owns the control.
|
||||
* rows. Callers may also provide built-in font CSS when their owning document
|
||||
* does not already receive Excalidraw's window-scoped font registration.
|
||||
*/
|
||||
export class FontPickerComponent extends ValueComponent<string> {
|
||||
public readonly buttonEl: HTMLButtonElement;
|
||||
@@ -33,12 +43,15 @@ export class FontPickerComponent extends ValueComponent<string> {
|
||||
private menu: Menu | null = null;
|
||||
private optionObserver: IntersectionObserver | null = null;
|
||||
private readonly loadedPreviewFonts = new Map<string, LoadedPreviewFont>();
|
||||
private readonly builtInPreviewStyles = new Map<string, HTMLStyleElement>();
|
||||
private readonly builtInPreviewLoads = new Map<string, Promise<void>>();
|
||||
private readonly handleClick = (): void => this.openMenu();
|
||||
|
||||
public constructor(
|
||||
containerEl: HTMLElement,
|
||||
private readonly app: App,
|
||||
private readonly getOptions: () => SelectableFontOption[],
|
||||
private readonly getBuiltInFontCss?: BuiltInFontCssProvider,
|
||||
) {
|
||||
super();
|
||||
this.buttonEl = containerEl.createEl("button", {
|
||||
@@ -97,6 +110,11 @@ export class FontPickerComponent extends ValueComponent<string> {
|
||||
loaded.document.fonts.delete(loaded.face);
|
||||
}
|
||||
this.loadedPreviewFonts.clear();
|
||||
for (const styleElement of this.builtInPreviewStyles.values()) {
|
||||
styleElement.remove();
|
||||
}
|
||||
this.builtInPreviewStyles.clear();
|
||||
this.builtInPreviewLoads.clear();
|
||||
this.buttonEl.remove();
|
||||
}
|
||||
|
||||
@@ -232,6 +250,42 @@ export class FontPickerComponent extends ValueComponent<string> {
|
||||
return;
|
||||
}
|
||||
setStyle(element, { fontFamily: quoteFontFamily(family) });
|
||||
if (!option.fontFile) {
|
||||
void this.ensureBuiltInPreviewFont(family).catch((): void => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
private async ensureBuiltInPreviewFont(fontFamily: string): Promise<void> {
|
||||
if (
|
||||
!this.getBuiltInFontCss ||
|
||||
this.builtInPreviewStyles.has(fontFamily)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const pendingLoad = this.builtInPreviewLoads.get(fontFamily);
|
||||
if (pendingLoad !== undefined) {
|
||||
await pendingLoad;
|
||||
return;
|
||||
}
|
||||
|
||||
const load = this.loadBuiltInPreviewFont(fontFamily).finally(() => {
|
||||
this.builtInPreviewLoads.delete(fontFamily);
|
||||
});
|
||||
this.builtInPreviewLoads.set(fontFamily, load);
|
||||
await load;
|
||||
}
|
||||
|
||||
private async loadBuiltInPreviewFont(fontFamily: string): Promise<void> {
|
||||
const css = await this.getBuiltInFontCss?.(fontFamily);
|
||||
if (!css || !this.buttonEl.isConnected) {
|
||||
return;
|
||||
}
|
||||
const doc = this.buttonEl.ownerDocument;
|
||||
const styleElement = deliberateCreateElement(doc, "style");
|
||||
styleElement.textContent = css;
|
||||
doc.head.appendChild(styleElement);
|
||||
this.builtInPreviewStyles.set(fontFamily, styleElement);
|
||||
await doc.fonts.load(`20px ${quoteFontFamily(fontFamily)}`);
|
||||
}
|
||||
|
||||
private ensureLocalPreviewFont(file: TFile): string | null {
|
||||
|
||||
@@ -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);
|
||||
|
||||
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user