Compare commits

..
141 Commits
Author SHA1 Message Date
zsviczian 30b20ebaf0 2.24.0 2026-06-15 20:57:18 +02:00
zsviczian 841db04f75 renderComponent 2026-06-15 20:51:09 +02:00
zsviczian d61131e321 getLeaf(), Excalidraw Loading... 2026-06-15 20:20:50 +02:00
zsviczian f45a9ebd66 activeLeaf, isUnwantedLeaf 2026-06-15 19:00:28 +02:00
zsviczian 757147ad4b disabled wait for font, fixed few type issues 2026-06-15 11:15:29 +00:00
zsviczian a57db28e22 Merge pull request #2803 from zsviczian/260614
Mostly lint
2026-06-14 22:36:04 +02:00
zsviczian 64f105b11b 2.24.0-beta-4 2026-06-14 22:34:51 +02:00
zsviczian fccc325825 0.18.103 2026-06-14 20:48:25 +02:00
zsviczian 7843d9ce51 lint 2026-06-14 20:39:48 +02:00
zsviczian 894350739a eslint type error fixing 2026-06-14 20:39:15 +02:00
zsviczian 53eae64ed3 lint 2026-06-14 20:12:38 +02:00
zsviczian ec426ce5ea Mindmap Builder, lint errors, 2026-06-14 20:10:48 +02:00
zsviczian 97c4381f64 remove await for initializeFont, fix universalInsertFileModal capturing keyboard events 2026-06-14 16:58:50 +02:00
zsviczian 25220bb6fc Release notes for runtime pens 2026-06-14 07:42:50 +02:00
zsviczian c3c666e0c9 fixed main.ts type issues with MonkeyPatch implementation. 2026-06-14 06:49:10 +02:00
zsviczian ee479985f6 Merge remote-tracking branch 'origin/master' into 260614 2026-06-14 06:33:35 +02:00
zsviczian ab799ab836 Merge pull request #2801 from arias007/codex/custom-pens-independent-state
Keep custom pen runtime state independent
2026-06-14 06:32:00 +02:00
zsviczian 629763ed7a Move monkeypatch to MonkeyPatchManager 2026-06-14 06:25:05 +02:00
Murat e0f9326a8b Keep custom pen state independent 2026-06-14 01:55:00 +08:00
zsviczian 2fb2ffbc4c 2.24.0-beta-3 2026-06-13 14:31:15 +02:00
zsviczian 9fcabc2d94 fixed hasOwn(null) 2026-06-13 14:30:47 +02:00
zsviczian cc8af155c7 lint 2026-06-13 14:13:58 +02:00
zsviczian 33e8085161 Merge pull request #2797 from iwanhoogendoorn/update-color-scheme-manager-v3
Update Color Scheme Manager script
2026-06-13 13:36:27 +02:00
zsviczian 5af5844556 Merge pull request #2798 from zsviczian/260612
Type fixes
2026-06-13 13:35:26 +02:00
zsviczian d2ed7faefa 2.24.0-beta-2 2026-06-13 13:34:43 +02:00
zsviczian 44bb246572 mostly type fixes 2026-06-13 13:34:14 +02:00
zsviczian 0a7ec898d1 Object.hasOwn 2026-06-13 10:01:05 +02:00
zsviczian 84c77180e1 instanceOf typechecks, use fileManager.trashFile, unexpected lexical declaration 2026-06-13 09:26:04 +02:00
zsviczian 809c722855 activeLeaf to getMostRecentLeaf, Expected an assignment or function call and instead saw an expression. 2026-06-13 07:02:56 +02:00
iwanhoogendoorn e6c05292a7 Update Color Scheme Manager script
- Themable canvas background per scheme (defaults to white; CANVAS: import key)
- Stroke/fill/canvas palettes stratified like the default palette (strong / pastel / paper tints)
- Full colour editor on every pick: spectrum/sliders/eyedropper, HEX, RGB or native palette
- Top-pick rows: fixed anchors (black / transparent) + 4 editable slots, edits no longer dropped
- 'Expand theme -> picker': 55 swatches per picker, 5 lightness levels per accent, uniform neutrals row
- Multi-object selection: each object gets its own stroke+fill pair from the theme; re-click cycles the assignment
- Heals legacy auto-saved pickers that froze identical stroke/fill grids
2026-06-12 21:57:39 +02:00
zsviczian 4ad249db22 eslint configuration 2026-06-12 16:57:46 +02:00
zsviczian 46ac969f4e Merge pull request #2796 from zsviczian/fix-lint-issues
excalidraw extras fixes
2026-06-12 07:58:19 +02:00
zsviczian 573397868b verify min plugin version 2026-06-12 07:56:07 +02:00
zsviczian 278e6d9976 fixed mermaid load 2026-06-12 07:09:07 +02:00
zsviczian fb2b782bd4 Merge pull request #2794 from zsviczian/excalidraw-extras-initial
excalidraw extras 1.0 implementation
2026-06-10 21:48:38 +02:00
zsviczian 421f2ec21a remove update to toolspanel 2026-06-10 21:45:51 +02:00
zsviczian 9e358cac97 moved timer to extras 2026-06-10 20:21:26 +02:00
zsviczian 5cbb5f2ee5 initial full implementation 2026-06-10 19:40:35 +02:00
zsviczian c8470ffdc5 fs access step 1 2026-06-10 19:07:05 +02:00
zsviczian 57f8a781a6 move lzstring to project 2026-06-10 07:46:19 +02:00
zsviczian 4c764b5656 move to pako 1 2026-06-10 07:25:42 +02:00
zsviczian e655cfbccd added rollup visualizer 2026-06-10 06:27:01 +02:00
zsviczian 1208a509d6 mermaid implementation 2026-06-09 22:15:59 +02:00
zsviczian 1759cdffab mindmap builder update 2026-06-09 18:27:48 +02:00
zsviczian e7af4b62ac updated capture note 2026-06-09 08:26:07 +02:00
zsviczian bd5df81be7 carved out printToPDF 2026-06-08 23:47:01 +02:00
zsviczian db1ec02578 gateway update 2026-06-08 22:49:02 +02:00
zsviczian e92d95fc67 promise tracking 2026-06-08 22:36:26 +02:00
zsviczian 9d7e0828f9 excalidraw-extras initial commit, removed mathjax 2026-06-08 22:03:10 +02:00
zsviczian 1160e0ec1f 2.23.12 2026-06-07 23:16:22 +02:00
zsviczian efe7009040 fix innerHTML 2026-06-07 22:22:04 +02:00
zsviczian 96aa17d4d8 2.23.11, 0.18.100 2026-06-07 20:34:44 +02:00
zsviczian 52d6d905d3 addressed styling issues 2026-06-07 17:46:08 +02:00
zsviczian 329e739c69 address setStyle issues batch 1 2026-06-07 13:27:45 +02:00
zsviczian b8b51fcff2 lint 2026-06-07 10:57:27 +02:00
zsviczian 11f47ecd41 Add style helpers step 1
fixed regression introduced in d3232f3071
2026-06-07 08:54:16 +02:00
zsviczian 817854bbcd eslint --fix 2026-06-07 07:13:12 +02:00
zsviczian d3232f3071 Mindless cosmetics based on Obsidian codescanner results 2026-06-07 07:01:35 +02:00
zsviczian e4e290cdb6 removed "require" from code 2026-06-07 06:36:16 +02:00
zsviczian 3c3f4a54b1 fixing obsidian codescanner findings, mostly meaningless changes to please the machine :( 2026-06-06 23:50:16 +02:00
zsviczian 820e5b2324 add console log to all catch statements, replace _ with error, and print error to console.log 2026-06-06 23:28:34 +02:00
zsviczian ce332eab26 2.23.10 2026-06-06 19:34:50 +02:00
zsviczian 57a5149a91 2.23.9, 0.18.98 2026-06-06 15:53:09 +02:00
zsviczian cebe80ce0d getAllNestedExcalidrawFiles, ExcalidrawView now updates on deep nested changes 2026-06-06 14:40:32 +02:00
zsviczian cf9096adf8 added setting to hide tab bar buttons 2026-06-06 06:40:44 +02:00
zsviczian dc0038a116 cache fixes 2026-06-05 18:54:36 +02:00
zsviczian 09356cfcef Merge branch 'master' of https://github.com/zsviczian/obsidian-excalidraw-plugin 2026-06-05 13:54:14 +02:00
zsviczian f210b4b28e fixed cache race condition 2026-06-05 13:54:10 +02:00
zsviczian 6c7e9b0811 Merge pull request #2788 from iwanhoogendoorn/update-color-scheme-manager
Update Color Scheme Manager script
2026-06-05 11:17:54 +02:00
iwanhoogendoorn b3879f9550 Update Color Scheme Manager script
- MindMap mode now defaults OFF each load and never touches the map when off
- Mind map branches get maximally-distinct colours (evenly spaced hues)
- Bump directory-info timestamp so the plugin detects the update
2026-06-05 09:30:16 +02:00
zsviczian 4d2555532d Merge pull request #2787 from iwanhoogendoorn/add-color-scheme-manager
Add Color Scheme Manager script
2026-06-04 20:16:58 +02:00
iwanhoogendoorn 605222de78 Add Color Scheme Manager script
Swap Stroke and Background/Fill colour palettes between named, categorized
themes from a docked side panel; create/import/export schemes; optional
MindMap Builder branch recolouring.

- ea-scripts/Color Scheme Manager.md + .svg
- images/color-scheme-manager.gif
- index-new.md: TOC (Styling and Appearance) + details section
- directory-info.json: both files with current timestamp
2026-06-04 19:48:42 +02:00
zsviczian 209ae5e2b9 updated capture note 2026-06-04 10:07:46 +00:00
zsviczian 36b0cc0c97 race condition 2026-06-02 23:14:43 +02:00
zsviczian 79662d11b0 updated mindmap builder 2026-06-02 11:29:51 +02:00
zsviczian fc5147fcb6 Mindmap Builder, added new config API 2026-06-02 09:09:09 +00:00
zsviczian 7f08ea8e18 updated .nvmrc, package and package-lock, added overrides to package.json 2026-06-02 08:04:45 +00:00
zsviczian d4dc96c34a multiple minor fixes in capture note 2026-06-01 19:57:45 +02:00
zsviczian 6e1041a590 remove excalibrain excluded elements from Capture Note Ontology Suggester 2026-06-01 12:16:51 +00:00
zsviczian f6e4997534 Clicking Excalidraw links now correctly jumps to the targeted element 2026-06-01 10:47:43 +00:00
zsviczian b96eb43ac7 Mindmap builder supports embedding markdown as an image, if the ![[wiki-embed.md|width]] has width. 2026-06-01 06:19:16 +00:00
zsviczian 566d98b008 graceful fail if yaml includes malformed aliases 2026-05-31 22:40:00 +02:00
zsviczian 6fdaf710eb 2.23.8 2026-05-31 21:42:03 +02:00
zsviczian b06fa3fa7c Mindmap Builder Script extended with calendar feature 2026-05-29 22:13:22 +02:00
zsviczian e86c977495 updated zoomToElements in EA 2026-05-28 22:08:51 +02:00
zsviczian 1754797876 moved PaneTarget utilTypes so it gets in cluded the LLM training file. 2026-05-28 20:10:55 +02:00
zsviczian 78a33be754 removed unsupported fonts from dropdown 2026-05-28 10:58:48 +00:00
zsviczian b985993af7 support image embed of markdown section of Excalidraw file 2026-05-28 10:00:04 +00:00
zsviczian 9f815a5ed4 fix FRONTMATTER_KEYS regression 2026-05-28 08:04:22 +00:00
zsviczian 0ddf6bfbeb support ontology in embeddable links 2026-05-28 06:36:49 +00:00
zsviczian f08e5777fd updated llm training file 2026-05-27 05:39:18 +02:00
zsviczian 53a868ade5 updated package lock 2026-05-26 21:27:48 +02:00
zsviczian b9ec19fee3 2.23.7, 0.18.0-93 2026-05-26 21:25:02 +02:00
zsviczian 467a4b8a43 getColosFromExcalidrawFile 2026-05-26 06:08:57 +00:00
zsviczian b15204a1fd added CONTRIBUTING.md 2026-05-25 06:30:33 +02:00
zsviczian 571829081c fixed undeclared variable error 2026-05-24 19:17:44 +02:00
zsviczian ed888f7de2 2.23.6 2026-05-24 17:13:15 +02:00
zsviczian 13ce80bc41 update image in readme 2026-05-24 15:48:05 +02:00
zsviczian 2d2c52e042 updated image in readme 2026-05-24 15:44:29 +02:00
zsviczian 29bd2df589 updated AI training file 2026-05-24 10:54:52 +02:00
zsviczian cac0029afc 2.23.5 2026-05-23 22:59:16 +02:00
zsviczian 3ab78f8364 Merge pull request #2777 from playermiller109/2026-05-24
fix URL string issues and broken comments across locales
2026-05-23 22:27:07 +02:00
playermiller109 9b495bb05a fix(i18n): correct URL string errors in e80666f 2026-05-24 02:27:16 +08:00
playermiller109 937936521f fix(i18n): correct broken comments in f9529e3 2026-05-24 02:27:16 +08:00
zsviczian d8eff4c2f5 2.23.4 2026-05-23 19:45:56 +02:00
zsviczian bf791f4c8a iframe hardening 2026-05-22 17:19:12 +02:00
zsviczian 2bfb38197b fixed taskbone regression, removed taskbone fetch 2026-05-22 05:41:16 +00:00
zsviczian e639b1c1f4 fetch related changes 2026-05-22 06:11:56 +02:00
zsviczian 06ff20e844 patching image occlusion 2026-05-21 23:13:35 +02:00
zsviczian b2e96d369c hardend data:url embeddables 2026-05-21 23:01:07 +02:00
zsviczian 8cddc6ae60 replace iframely with secure alternative (oembed) 2026-05-21 22:56:25 +02:00
zsviczian 3c74deeb43 opt in for cmd://, fixed toolspanel drag, sanitize SVG 2026-05-21 22:38:58 +02:00
zsviczian 5240d1ffe2 aiMetering 2026-05-21 18:21:45 +02:00
zsviczian c22fde3215 introducing mainDocument, migrating to activeDocument and mainDocument 2026-05-21 12:02:52 +00:00
zsviczian 7021a24611 further eslint --fix -es 2026-05-21 08:03:46 +00:00
zsviczian e157074504 eslint --fix 2026-05-21 07:26:48 +00:00
zsviczian 46093d890a fix .instanceOf lint error 2026-05-21 06:26:21 +00:00
zsviczian de89b5d365 moving LocalGraphView type to types.d.ts 2026-05-21 05:19:06 +00:00
zsviczian f9529e3e6e removed unused language keys 2026-05-21 05:59:42 +02:00
zsviczian e800036b66 adding typings 2026-05-20 22:59:46 +02:00
zsviczian 6f9a53bf6d addressed any in excalidrawViewUtils 2026-05-20 19:52:19 +02:00
zsviczian e80666f46e replaced any with proper types in ExcalidrawAutomate 2026-05-20 19:36:10 +02:00
zsviczian ba86626560 added support for Gemini aspect ratios and resolution ranges 2026-05-20 18:56:59 +02:00
zsviczian 6929d19bd2 mindmap builder fixed: ALT+V: image element with external image, embeddable with data url, inline suggester "." issue 2026-05-20 15:50:59 +00:00
zsviczian b549b27024 lint and getPathForImageFileId 2026-05-20 09:52:01 +00:00
zsviczian 1503e34b72 addressed types in utils.ts 2026-05-20 06:09:52 +02:00
zsviczian 1417ec33f9 remove any types from Prompt.ts, AIUtils.ts 2026-05-19 22:54:55 +02:00
zsviczian a3b27e5501 replace any types in ExcalidrawAutomateUtils.ts 2026-05-19 21:17:20 +02:00
zsviczian 5591e048be remove "any" from ExcalidrawData.ts 2026-05-19 20:41:56 +02:00
zsviczian d8c2a2d56c replaced any with types: main.ts, settings.ts, ExcalidrawView.ts, centralized element.customData types. 2026-05-19 20:19:15 +02:00
zsviczian 4e58511fa1 remove any types from settings.ts 2026-05-19 19:27:27 +02:00
zsviczian 2529f44283 removed legacy localStorage cleanup to improve plugin score 2026-05-19 18:45:04 +02:00
zsviczian c34144876c agent.md v0.1 2026-05-19 13:26:42 +00:00
zsviczian 5a9f7fdeff added image to ReadMe 2026-05-19 07:30:07 +02:00
zsviczian e98f9dff4a rationalize URL_REGISTRY 2026-05-18 20:31:09 +02:00
zsviczian 4d39502c68 minor type fixes 2026-05-18 20:02:20 +02:00
zsviczian cde46e593d lint 2026-05-18 10:42:13 +00:00
zsviczian c58c28457b fix script icon install 2026-05-18 10:37:13 +00:00
zsviczian f01ff7fd29 fix remaining URLS 2026-05-17 17:41:15 +02:00
zsviczian 2cb9dbd7f8 something went wrong with the previous release... codescanner scanned the wrong commit 2026-05-17 16:48:46 +02:00
zsviczian 0b1a56f92d Merge pull request #2766 from zsviczian/safeURL
Safe url
2026-05-17 15:57:15 +02:00
163 changed files with 36737 additions and 42851 deletions

No files matched your search

-7
View File
@@ -1,7 +0,0 @@
{
"extends": ["@excalidraw/eslint-config"],
"rules": {
"import/no-anonymous-default-export": "off",
"no-restricted-globals": "off"
}
}
+2
View File
@@ -15,6 +15,8 @@ lib
dist
tmp
deploy.ps1
eslint_results.json
bundle-analysis.html
#VSCode
yarn.lock
+1 -1
View File
@@ -1 +1 @@
20
22
+4
View File
@@ -0,0 +1,4 @@
{
"tabWidth": 2,
"useTabs": false
}
+4 -1
View File
@@ -1,6 +1,6 @@
{
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"typescript.enablePromptUseWorkspaceTsdk": true,
"typescript.tsserver.log": "off",
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
@@ -13,6 +13,9 @@
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"editor.tabSize": 2,
"editor.insertSpaces": true,
"editor.formatOnSave": true,
"eslint.validate": [
"javascript",
"javascriptreact",
+15
View File
@@ -0,0 +1,15 @@
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "lint",
"problemMatcher": "$eslint-stylish",
"group": {
"kind": "build",
"isDefault": true
},
"label": "Run Project Linting"
}
]
}
+586
View File
@@ -0,0 +1,586 @@
# Obsidian Excalidraw Plugin Agent Guide
## Purpose
This repository contains the Obsidian Excalidraw plugin: an Obsidian.md plugin that integrates a heavily customized Excalidraw fork into Obsidian.
This is not a generic React canvas app. Many implementation choices are driven by:
- Obsidian plugin lifecycle constraints
- Electron desktop and mobile compatibility
- popout window support
- startup time and bundle size
- compatibility with a customized upstream Excalidraw fork
- advanced plugin-specific features such as scripts, automation, custom pens, custom fonts, markdown embeds, PDF export, OCR, AI features, and deep vault integration
When working in this repo, optimize for correctness inside Obsidian and for preserving existing behavior. Do not assume that a simpler-looking web-app pattern is safe here.
Use https://github.com/obsidian-typings/obsidian-typings as a reference when dealing with Obsidian APIs, especially undocumented or weakly documented ones.
## Product And Deployment Model
- The shipped plugin is effectively three files: `main.js`, `styles.css`, and `manifest.json`.
- The production build emits these into `dist/`.
- The bundle is intentionally assembled as a single CommonJS `main.js` with embedded runtime payloads.
- `package.json` is primarily the library/package manifest. Its version is not the canonical plugin release version.
- Plugin release versions live in `manifest.json` and `manifest-beta.json`.
- `package.json` `main` and `types` point to the library build in `lib/`, not the Obsidian runtime bundle.
## Core Mental Model
- `src/core/main.ts` owns plugin startup, lifecycle, settings loading, migration, and manager initialization.
- `src/view/ExcalidrawView.ts` is the main runtime surface for the editor/view experience.
- `src/core/managers/` contains most lifecycle-adjacent coordination logic.
- `src/shared/` contains major reusable subsystems such as Excalidraw Automate, dialogs, data handling, script engine support, LaTeX, workers, and SVG conversion.
- `src/utils/` contains lower-level helpers for Obsidian integration, export, files, PDF, AI, dynamic styling, and scene manipulation.
- `rollup.config.mjs` is a critical part of the runtime architecture, not just a packaging detail.
Treat build code and runtime code as one system.
## Repository Map
### Runtime Source
- `src/core/main.ts`: plugin class, lifecycle ordering, view registration, settings load/save/migration, startup instrumentation
- `src/core/index.ts`: library/public API entry used by consumers of the lib build
- `src/core/settings.ts`: settings interface, defaults, settings tab UI
- `src/core/managers/`: command, event, file, observer, package, style, and markdown post processor managers
- `src/core/editor/`: editor-specific helpers and mode handling
- `src/view/`: Excalidraw views, loading view, sidepanel, view managers
- `src/shared/`: Excalidraw Automate, script engine, dialogs, OCR, LaTeX, data model, workers, suggesters, SVG parser
- `src/utils/`: file/path/export/PDF/Obsidian/scene/UI/helper utilities
- `src/lang/`: localization helpers and locale files
- `src/constants/`: constants, icons, startup script, safe URLs
- `src/types/`: project TypeScript contracts
### Build, Docs, And Supporting Content
- `rollup.config.mjs`: main plugin build and runtime payload embedding
- `MathjaxToSVG/`: separate subproject built before the main plugin and embedded into the bundle
- `scripts/`: build helpers such as `build-mathjax.mjs`
- `styles.css`: plugin stylesheet merged with Excalidraw CSS during build
- `docs/`: user-facing documentation and API/docs content
- `ea-scripts/`: downloadable/example scripts for the script engine, not the main plugin runtime
- `test-data/`: fixtures and sample content, not a conventional automated test suite
## Startup And Lifecycle Rules
Lifecycle ordering matters.
- `onload()` in `src/core/main.ts` registers views, extensions, icons, the ribbon action, settings loading, Excalidraw Automate initialization, the markdown post processor, and the `onLayoutReady` callback.
- `onloadOnLayoutReady()` initializes the package manager, event manager, observer manager, command manager, compression worker, Excalidraw config, monkey patches, styles manager, script engine, fonts, image cache, and finally switches loading views to real Excalidraw views.
Important constraints:
- Keep markdown post processor registration in `onload()`. Obsidian expects post processors to be registered there.
- Monkey patches are intentionally registered after layout is ready.
- Startup order is performance-sensitive and behavior-sensitive.
- Do not move initialization steps across `onload()` and `onLayoutReady()` casually.
- `ExcalidrawView.onUnloadFile()` deliberately avoids calling `super.onUnloadFile()` to avoid duplicate autosave behavior.
If a task touches startup behavior, read the surrounding lifecycle code before editing.
## Build And Packaging Rules
This project uses a non-trivial Rollup build because startup time, popout-window behavior, and bundle size matter.
### Key Facts
- The main build entry is `src/core/main.ts`.
- Production output is `dist/main.js` plus `dist/styles.css` and `dist/manifest.json`.
- `inlineDynamicImports` is enabled for the main bundle.
- The build compresses and embeds selected runtime payloads into `main.js`.
- `styles.css` is merged with upstream Excalidraw CSS and minified.
### Embedded Runtime Payloads
The build embeds or injects runtime code for:
- React and ReactDOM
- a JSX runtime shim for compatibility
- the customized `@zsviczian/excalidraw` package
- `MathjaxToSVG`
- `lz-string`
- selected compressed locale payloads
These payloads are executed or unpacked at runtime. This is intentional.
### 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.
### MathJax Subproject
- `MathjaxToSVG/` is a standalone subproject with its own build.
- `scripts/build-mathjax.mjs` hashes the subproject, installs dependencies if needed, and rebuilds it when inputs change.
- The main plugin build expects `MathjaxToSVG/dist/index.js` to exist and embeds it.
### Localization Compression
- English is loaded directly.
- Some non-English locales are compressed and embedded at build time.
- `rollup.config.mjs` tokenizes runtime-dependent strings in locales.
- `src/lang/helpers.ts` resolves those tokens at runtime.
- If you add new runtime-dependent locale patterns, you must keep `rollup.config.mjs` and `src/lang/helpers.ts` in sync.
### Safe URL Tokenization
- Safe URLs are centralized in `src/constants/safeUrls.ts`.
- The build tokenizes URL constants and resolves them at runtime.
- If you change safe URL handling, rebuild and verify both token emission and token resolution.
### Versioning Nuance
- The release workflow publishes `dist/main.js`, `dist/styles.css`, and `dist/manifest.json`.
- Stable releases use `manifest.json`.
- Pre-releases swap in `manifest-beta.json` in the GitHub release workflow.
- `rollup.config.mjs` currently reads `manifest-beta.json` when injecting `PLUGIN_VERSION`, so version changes must be intentional and consistent.
## Architectural Conventions
- Prefer repository-local patterns over upstream Excalidraw assumptions.
- Many unusual solutions are workarounds for Obsidian or Electron limitations. Do not remove them just because they look unconventional.
- The codebase uses non-published Obsidian APIs and monkey patches where necessary.
- Performance and startup-time optimizations are first-class design constraints.
- Popout window support is a first-class design constraint.
- Backwards compatibility is a strong default requirement.
- Preserve existing abstractions unless the task clearly requires a redesign.
- Avoid broad refactors unless there is strong evidence they are necessary.
## 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.
### File And Symbol Naming
- Use PascalCase filenames when the file's main export is a class, React component, modal, manager, view, or similarly named object with clear identity. The filename should match the primary export. Examples already in the repo include `ExcalidrawView.ts`, `CommandManager.ts`, and `ReleaseNotes.ts`.
- Use lowerCamelCase filenames for helper and utility modules whose main exports are functions or small related helpers. Examples already in the repo include `fileUtils.ts`, `pathUtils.ts`, and `exportUtils.ts`.
- Use lowerCamelCase filenames for grouped type modules unless the file is intentionally mirroring an externally established name.
- Use PascalCase for classes, React components, dialogs, managers, views, interfaces, and domain-level type aliases.
- Use lowerCamelCase for functions, methods, variables, parameters, and object properties.
- Use UPPER_SNAKE_CASE for exported constants and locale keys.
- Keep persisted settings keys, serialized fields, and frontmatter keys stable and lowerCamelCase unless an explicit migration is added.
- For future rename work, fix typos and inconsistent acronym casing in a dedicated pass rather than mixing those renames with behavior changes. Existing examples worth normalizing later include files such as `YoutTubeUtils.ts`, `modifierkeyHelper.ts`, and `TTDDialogPersistanceAdater.ts`.
### Folder Placement Guide
- `src/core/`: plugin bootstrap, plugin-wide lifecycle, registration, settings, and orchestration. If a change affects the plugin globally rather than a single open view, start here.
- `src/core/managers/`: plugin-global coordinators that own subscriptions, registration, or lifecycle-managed behavior.
- `src/core/editor/`: markdown/editor bridge behavior and editor-specific UX.
- `src/view/`: the live Excalidraw pane and view-owned behavior.
- `src/view/components/`: React components rendered inside the main Excalidraw view or tightly coupled to `ExcalidrawView` state.
- `src/view/managers/`: view-scoped controllers that belong to a single view instance rather than the whole plugin.
- `src/view/sidepanel/`: sidepanel-only view code.
- `src/shared/`: reusable subsystems used by multiple areas such as `core`, `view`, scripting, import/export, or dialogs.
- `src/shared/Dialogs/`: Obsidian modals, prompts, release-note content, and user-facing dialog flows. `src/shared/Dialogs/Messages.ts` is the source for next-version change messages shown to users.
- `src/shared/components/`: reusable UI helpers that are not owned solely by the main Excalidraw view.
- `src/shared/Suggesters/`: suggestion modals and suggestion-specific helpers.
- `src/shared/Workers/`: worker entrypoints and worker-specific helper code.
- `src/shared/OCR/`: OCR integrations and OCR-specific logic.
- `src/shared/svgToExcalidraw/`: SVG parsing and import pipeline code.
- `src/utils/`: side-effect-light helpers. If a module owns long-lived state, subscriptions, or plugin/view lifecycle, it likely does not belong in `utils`.
- `src/constants/`: shared constants, icon definitions, startup content, and URL registries. Keep logic here minimal and obvious.
- `src/types/`: shared TypeScript contracts and ambient declarations, not implementation logic.
- `src/lang/locale/`: user-visible strings. `en.ts` is the source of truth for new keys.
- `MathjaxToSVG/`: a separate subproject with its own build and runtime role. Treat it as an independent package with the same documentation and compatibility expectations as the main plugin.
## Documentation Standard
Use TSDoc as the documentation standard. It is the modern TypeScript-friendly evolution of JSDoc and is the right fit for this repository; do not think in terms of JavaDoc for TS code.
- Require TSDoc for exported classes, exported functions, public methods, public library APIs, and non-obvious modules.
- Public APIs in `src/core/index.ts` and `src/shared/ExcalidrawAutomate.ts` should always have complete TSDoc.
- Settings migrations, compatibility shims, build-time tokenization code, and package-loading code should also carry clear high-signal documentation.
- Add short module-level documentation to files whose behavior is easy to misread, such as `rollup.config.mjs`, `src/core/managers/PackageManager.ts`, migration code in `src/core/main.ts`, and the `MathjaxToSVG/` subproject.
- Internal/private code should only be commented when the behavior is non-obvious. Avoid trivial comments.
## Backward Compatibility Requirements
Backwards compatibility is a strong requirement in this repository.
- Do not break persisted settings, serialized scene data, frontmatter keys, command IDs, or documented user workflows without an explicit migration or compatibility layer.
- Do not rename public API methods, script-engine entry points, or library exports casually. `src/core/index.ts` and `src/shared/ExcalidrawAutomate.ts` are especially sensitive.
- Naming-only refactors must preserve observable behavior.
- 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.
## User-Facing Change Workflow
- Every user-visible change intended for the next release should be documented in `src/shared/Dialogs/Messages.ts` under the next upcoming version key.
- Keep `Messages.ts` entries concise, user-facing, and focused on observable behavior, not implementation detail.
- If a change affects scripting, API behavior, settings, or migration, mention that explicitly in the release-note entry.
- Every new user-visible language string must be added first in `src/lang/locale/en.ts`.
- The same change must also update `src/lang/locale/ru.ts`, `src/lang/locale/es.ts`, `src/lang/locale/zh-cn.ts`, and `src/lang/locale/zh-tw.ts`.
- These maintained locales are part of the build-time localized bundle path, so they are not optional follow-up work.
- Preserve locale key names and the existing comment grouping by owning file or subsystem.
- If a string contains URLs or runtime-dependent tokens, follow the existing locale patterns so build-time tokenization and runtime resolution continue to work.
## 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.
- 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.
- 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.
- Before adding or refactoring a React file, inspect the nearest existing file in that area and match its import/runtime pattern.
## Where To Make Changes
Use this routing guide before editing.
- Startup, lifecycle, readiness, plugin-wide state: `src/core/main.ts`
- Public/library API surface: `src/core/index.ts`
- Settings schema/defaults/UI: `src/core/settings.ts`
- 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`
- 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/`
- Scripting and automation API: `src/shared/ExcalidrawAutomate.ts` and `src/shared/Scripts.ts`
- Dialogs and UI support components: `src/shared/Dialogs/`
- Release notes and next-version change messages: `src/shared/Dialogs/Messages.ts` and `src/shared/Dialogs/ReleaseNotes.ts`
- Export/PDF/image workflows: `src/utils/exportUtils.ts`, `src/utils/PDFUtils.ts`, `src/shared/ImageCache.ts`
- Localization: `src/lang/locale/en.ts`, then the maintained locales `ru.ts`, `es.ts`, `zh-cn.ts`, and `zh-tw.ts`, then build/runtime localization helpers if needed
- Build output, bundle shape, and injected payloads: `rollup.config.mjs` and `MathjaxToSVG/`
## Settings Change Checklist
If a task changes persisted settings, inspect all relevant pieces.
- `ExcalidrawSettings` in `src/core/settings.ts`
- `DEFAULT_SETTINGS` in `src/core/settings.ts`
- settings UI in `src/core/settings.ts`
- loading and migration logic in `src/core/main.ts`
- any encryption or decryption logic for persisted keys
Settings changes are often incomplete if only one of these surfaces is updated.
## Script Engine And Automation Notes
- Excalidraw Automate is a major public surface of this project.
- `src/shared/ExcalidrawAutomate.ts` is large and high-impact.
- `src/shared/Scripts.ts` loads and manages vault-based scripts.
- Example and user-facing docs live in `AutomateHowTo.md`, `docs/ExcalidrawScriptsEngine.md`, `docs/API/`, and `ea-scripts/`.
- If you change public automation behavior, consider whether docs or the library build need updates.
### ExcalidrawAutomate Change Checklist
Whenever a function is added to or changed in `src/shared/ExcalidrawAutomate.ts`, three additional files must be updated in the same change:
1. **`src/shared/Dialogs/SuggesterInfo.ts`** — Add or update the corresponding entry in `EXCALIDRAW_AUTOMATE_INFO`. The `field` must match the function or property name exactly. The `desc` should explain behavior clearly, including any important limitations or session-scoped constraints. The `code` should reflect the actual TypeScript signature.
2. **`src/shared/Dialogs/Messages.ts`** — Document the new or changed function under the upcoming release version key. Include a brief user-facing description and the TypeScript signature in a fenced code block.
3. **`src/lang/locale/en.ts`** (and maintained locales) — Only required if the change introduces new user-visible strings. Follow the existing locale workflow described in the User-Facing Change Workflow section.
## High-Risk Areas
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/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
If a task touches any of the above, read adjacent code first and validate more carefully than usual.
## Validation Expectations
There is no standard unit-test suite wired into `package.json`.
Repo-wide ESLint currently reports a large backlog of pre-existing issues, so it is not yet a blocking pass/fail gate for every task.
Primary validation commands:
```bash
npm run code
npm run build
```
Additional useful commands:
```bash
npm run lib
npm run build:mathjax
npm run build:all
npm run madge
npm run doc
```
Validation guidance:
- 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.
- Run `npm run build` for anything that can affect bundle integrity, runtime injection, or production output.
- 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.
- 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.
## Practical Agent Guidance
**All changes must consider the full codebase, not just the immediate file or local context.**
- Before making or validating any change, agents must proactively search for all dependencies, references, and affected code across the repository. This includes:
- Searching for all usages, imports, and related patterns (e.g., property access, type assertions, function calls, etc.)
- 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.
- 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.
- Assume undocumented behavior may still be intentional.
- For new code, follow the target naming conventions even if nearby legacy files do not yet.
- 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.
- When a type is used in more than one module, prefer a shared definition in `src/types/` and import it everywhere instead of repeating local aliases.
- For scope-local inline types (for example inside a processor or callback), quickly verify whether the shape already exists elsewhere before keeping or adding a local declaration.
- Example: if `RemoteDirectoryInfo` is used in both `src/utils/utils.ts` and `src/core/main.ts`, define it once in `src/types/githubTypes.ts`, update both imports, and delete both local aliases in the same change.
- After type-only consolidations, run targeted diagnostics on touched files plus `npm run build`, and confirm no runtime behavior was intentionally changed.
**Summary:**
> Agents must always consider the full codebase impact of any change, proactively search for dependencies and affected code, and validate correctness globally—not just locally—before considering a task complete.
## Type System And Type Refactoring
Replacing `any` types is a precision task requiring understanding of the codebase's type architecture and constraints.
### Core Principles
When replacing `any` types:
- **Functional equivalence is non-negotiable**: Code must remain 100% functionally identical. Type changes are *only* for TypeScript type checking, never for runtime behavior changes.
- **Never invent local types**: If a type can be inferred from existing usage, Excalidraw types, or Obsidian APIs, use it. Do not create ad-hoc interface definitions.
- **Do not replace with `unknown` by default**: `unknown` is stricter than `any` and often requires guards/assertions elsewhere, which can break functional equivalence.
- **Exception for bridge casts**: In rare generic conditional return scenarios where TypeScript cannot express a provably equivalent return value, a narrow `as unknown as ...` bridge cast is acceptable. Keep it local, document why, and do not use it to bypass real type mismatches.
- **Use existing infrastructure**: Extend `src/types/types.d.ts` for Obsidian unpublished APIs, create new files in `src/types/` that build on existing conventions, and reference Excalidraw types directly.
### CRITICAL: Behavioral Change Detection When Replacing `any`
**Type replacements that appear to be "type-only" can introduce subtle runtime behavior changes. You must proactively detect and flag these before finalizing any change.**
#### Behavior-Altering Patterns
When scanning code that uses a value currently typed as `any`, watch for these patterns that can be affected by a type change:
1. **Falsy/Truthy checks**: `if (!value)`, `if (value)`, `value ? ... : ...`
- **Risk**: If the original code treats `0`, `""`, `false`, `null`, `undefined`, or `[]` as falsy, and you infer a type that allows these values, behavior changes.
- **Example**: Old code `if (!offset)` rejects `offset === 0`. New type `offset: number` allows `0`, fundamentally changing behavior for edge cases.
- **Action**: If the code has falsy checks, document that behavior explicitly in your change notes to the user.
2. **Existence checks**: `if (value === undefined)`, `if (value === null)`, `if (value)`
- **Risk**: Changing from accepting `any` (including undefined) to a narrower type may exclude valid edge cases.
- **Action**: Verify all call sites provide values matching the new type constraint.
3. **Optional chaining with falsy fallbacks**: `value?.prop ?? default`, `value?.prop ?? fallback`
- **Risk**: The fallback behavior may change if the inferred type rules out falsy intermediate values.
- **Action**: Test that fallback behavior is identical.
4. **Conditional logic on properties**: `if (obj.prop)`, `switch (obj.type)`, loops over `obj`
- **Risk**: Narrowing from `any` to a specific object shape might exclude properties the runtime code depends on.
- **Action**: Verify the inferred type shape includes all properties actually accessed.
#### Mandatory Pre-Change Verification
Before replacing an `any` type:
1. **Scan all usages** of the value (especially the entire function or component containing it).
2. **Identify falsy/truthy checks** or conditional logic that depends on the value.
3. **Compare semantics**: Does the old behavior permit `0`, `""`, `false`, `null`, or `undefined` in a way the new type might not?
4. **If a behavior change is introduced**: Explicitly document it in a comment in the code AND flag it to the user BEFORE considering the task complete.
5. **Document edge cases** that the type change affects.
#### Examples of Correct vs. Incorrect Replacements
**INCORRECT** (behavioral change, not flagged):
```typescript
// Old: const value: any = ...; if (!value) return null;
// New: const value: number = ...; if (typeof value !== "number") return null;
// Problem: Old code rejects 0, new code accepts 0. Behavior changed silently.
```
**CORRECT** (behavioral change, explicitly flagged):
```typescript
// Old: const offset: any = ...; if (!offset) return null;
// New: const offset: number = ...; if (typeof offset !== "number") return null;
// Flagged: "Note: This change now allows offset=0 (previously rejected as falsy).
// This is intentional and fixes a bug where block IDs could not be inserted at file start."
```
**CORRECT** (no behavioral change):
```typescript
// Old: const frame: any = ...; if (frame.type === "frame" && !frame.isDeleted) ...
// New: const frame: { type: string; isDeleted?: boolean } = ...; if (frame.type === "frame" && !frame.isDeleted) ...
// OK: Inferred type supports all operations, no falsy checks introduced, behavior identical.
```
### 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.
- **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.
### Excalidraw Type Integration
- Do not invent wrapper types for Excalidraw entities. Reference the customized `@zsviczian/excalidraw` types directly.
- 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`.
### Inference And Scanning Workflow
To identify the correct type for an `any` reference:
1. **Scan usage**: Identify all sites where the value is used. Determine what properties, methods, or operations are performed on it.
2. **Check existing types**: Search `src/types/`, the Excalidraw type definitions (via node_modules), and Obsidian API typings for matching types.
3. **Check upstream patterns**: Look at similar usage patterns elsewhere in the codebase. How are comparable values typed?
4. **Intersect constraints**: The correct type must support all observed operations. If multiple possible types exist, choose the one that is most specific without inventing new constraints.
5. **Test narrowing**: If the type was `any`, code may not have type guards. Ensure that replacing `any` with a more specific type does not require adding guards or assertions that change behavior.
### Common Patterns
- **DOM elements and jQuery-like objects**: Often `any` when they should be `HTMLElement`, `HTMLDivElement`, `Element`, etc. Check `src/utils/` and view components for examples.
- **Obsidian unpublished APIs**: Frequently `any` because the official typings are incomplete. Add to `src/types/types.d.ts` to model the actual shape based on Obsidian source or runtime inspection.
- **Excalidraw component state and config objects**: Usually `any` but should reference `ExcalidrawProps`, `AppState`, or similar exported by `@zsviczian/excalidraw`.
- **Event handler parameters and callbacks**: Often `any` but should be typed based on what the callback receives. Check invocation sites.
- **Imported worker or third-party runtime objects**: May be `any` if the package lacks types. Create a minimal type stub in `src/types/` if needed, or use `as const` to infer from a known shape.
- **Scene boundary typing (`getScene()` vs persistence sync)**: Scene producers may return readonly/non-deleted element arrays while persistence code mutates scene internals. Prefer broader input types at boundary methods (e.g., sync/update entry points), then narrow/cast internally where mutation is required.
- **AppState strict vs partial contracts**: Many helpers accept `AppState` while repository data paths often carry `Partial<AppState>`. Prefer widening helper signatures only when behavior is unchanged and call sites are truly partial; otherwise use narrow local assertions at call sites instead of reshaping runtime objects.
- **Legacy appState compatibility keys**: Preserve compatibility for legacy keys used during migrations or cross-version loads (e.g., `currentItemLinearStrokeSharpness`, `currentItemStrokeSharpness`) when tightening types.
### Adding Obsidian Unpublished API Types
When documenting an unpublished Obsidian API in `src/types/types.d.ts`:
- Use module declaration patterns already in the file (`declare module "obsidian" { interface App { ... } }`).
- Include a brief comment explaining the API or linking to the Obsidian source, if known.
- Only add properties and methods that are actually used in the codebase. Avoid speculative extensions.
- Be conservative: unpublished APIs can change; document the version or observation date if possible.
- Do not duplicate types; if Obsidian's types already define something, extend or refine, not redefine.
### Validation Approach
When replacing `any`:
1. **No new runtime errors**: Run the plugin in Obsidian after the change. Verify that all observed functionality works identically.
2. **TypeScript checking**: The change should reduce or eliminate TypeScript errors, not introduce new ones.
3. **No new guards or assertions**: If code previously worked with `any`, replacing it with a specific type should not require new `if` checks, `as` casts, or optional chaining that wasn't there before. If it does, the type choice is too strict.
4. **Side-effect parity check**: When replacing index-based mutation code with object transforms (e.g., sanitize/copy patterns), explicitly verify whether the original code intentionally mutated shared objects. Preserve side effects unless a behavior change is explicitly approved.
5. **Build passes**: `npm run build` must succeed. Type changes can affect bundle outcome if they affect build-time inference.
6. **Lint cleanliness**: The changed file should not gain new lint violations. Use `npm run code -- src/path/to/file.ts` to check the specific file.
### Justified ESLint Suppressions
In some cases, `@typescript-eslint/no-explicit-any` or `@typescript-eslint/no-unnecessary-type-assertion` warnings are justified and reflect legitimate constraints rather than type-safety failures. When suppressing these rules, follow strict guidelines:
#### When Suppressions Are Justified
- **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.
- **Legacy or compatibility code**: When bridging serialized data, migrations, or undocumented Obsidian APIs where the runtime shape is known but the type system cannot express it without inventing local stubs.
#### How To Document Suppressions
Always use `eslint-disable-next-line` (not file-wide disables) and include a comment explaining:
1. **Which rule** is being suppressed and why
2. **What constraint** makes the suppression necessary (provider variability, mutation path, etc.)
3. **Why a stricter type is not feasible** without breaking functional equivalence
**Format**:
```typescript
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- <rule name>: <1-2 sentence explanation of the constraint>
```
**Examples**:
```typescript
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- image provider payload schemas vary and are normalized in this function.
const normalizedData = rawItems.flatMap((item: Record<string, any>) => {
// ... normalize item.url, item.b64_json, item.image.url, etc.
});
```
```typescript
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- scene lookup returns union; mutation path requires mutable element.
const containerEl = sceneElements.find(
(el) => el.id === textElement.containerId,
) as unknown as Mutable<ExcalidrawElement>;
```
#### Suppressions To Avoid
- **Lazy typing**: Do not suppress `no-explicit-any` to avoid refactoring a complex function. Fix the type instead.
- **Overly broad assertions**: Do not use `as any` or `as unknown as any` to bypass unrelated type mismatches.
- **Undocumented suppressions**: Every suppression must include a clear comment. Suppressions without explanation are a code review red flag.
### When To Create A New Type File
- If a set of related types will be used across multiple modules and are not Obsidian or Excalidraw types, create a new file in `src/types/`.
- Name it to reflect its domain (e.g., `canvasTypes.ts`, `aiProviderTypes.ts`).
- Document the file's purpose and scope at the top with a brief module-level comment.
- Export types, not implementation. Do not put logic in type files.
- If the file re-exports types from Excalidraw or elsewhere, document the origin.
## Default Stance For Future Prompts
When you are asked to modify this repository:
- assume the current behavior exists for a reason
- favor root-cause fixes over superficial patches
- keep scope tight
- maintain backwards compatibility unless the task explicitly authorizes a breaking change
- validate with build plus lint-aware checks before declaring success
- do not introduce new lint violations in touched code, even if the full repo lint command still fails
- document user-visible changes in `src/shared/Dialogs/Messages.ts`
- add new language keys in `src/lang/locale/en.ts` and update `ru.ts`, `es.ts`, `zh-cn.ts`, and `zh-tw.ts` in the same change
- be especially careful around startup, build plumbing, localization tokenization, settings migration, and popout-window behavior
#### Custom Element Metadata (`customData`)
- All types and helpers for Excalidraw element `customData` (extensible metadata on elements, e.g., for LaTeX, PDF, image, or plugin-specific keys) are centralized in `src/utils/elementCustomDataUtils.ts`.
- If you need to add a new `customData` key, type, or helper, always add it to this file and import from here in all consumers. This avoids type duplication and ensures discoverability for future maintainers and agents.
- See `ExcalidrawCustomData`, `ExcalidrawCustomDataPatch`, `ExcalidrawPDFCustomData`, `ExcalidrawLatexCustomData`, and `addAppendUpdateCustomData` in that file for canonical patterns.
+96
View File
@@ -0,0 +1,96 @@
# 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.
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.
## 💬 Discuss First
Before spending your valuable time writing code for a new feature or significant refactor, please **open an issue** to discuss it first. This ensures your idea aligns with the project's roadmap and architecture, and helps prevent wasted effort or complex merge conflicts later.
## 🚀 Getting Started
1. Fork the repository and clone it locally.
2. 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).
## 🛠️ 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).*
- **Run ESLint:** Run `npm run code`
- **Fix ESLint Warnings:** Run `node ./scripts/fix-eslint-warnings.mjs`
## 🧪 Testing
At this time, the project **has no automated tests**. 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)
## 🏗️ 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.
- 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.
### 2. MathjaxToSVG
LaTeX support is provided by the `MathjaxToSVG` library, which is packaged as a separate sub-component (located in the `MathjaxToSVG/` folder).
- It is compressed using `LZString` during build time.
- 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/).
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.
- **Resist the temptation:** Do not implement features in the fork if they can be achieved using plugin wrappers, monkey patches, or API integrations within the main Obsidian plugin repo.
- **Use ringfenced areas:** Place changes in files clearly marked for the fork whenever possible:
- `packages/excalidraw/obsidianUtils.ts`
- `packages/common/src/commonObsidianUtils.ts`
- `packages/excalidraw/css/obsidianStylingOverrides.css`
- **Mark your changes explicitly:** Add a comment with your initials and the Issue or PR ID to easily identify custom additions during merge conflicts.
```ts
private shouldRenderAllEmbeddables: boolean = false; //zsviczian
```
- **Use dedicated functions:** If your code extension doesn't fit neatly into the ringfenced files, extract it into a dedicated new function rather than putting huge chunks of logic inline.
```ts
//mfuria #329. Right-click pan support when enabled via host plugin setting
if (
isPanWithRightMouseEnabled() &&
event.pointerType === "mouse" &&
event.button === POINTER_BUTTON.SECONDARY &&
!this.state.editingTextElement
) {
// prevent native context menu
const onContextMenu = (e: MouseEvent) => {
e.preventDefault();
};
window.addEventListener('contextmenu', onContextMenu, { once: true });
// Start right-click panning
this.startRightClickPanning(event);
return;
}
//mfuria #329. start right-click panning
private startRightClickPanning(event) { ... }
```
## 🌍 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.
## 📦 Pull Requests & Versioning
- **Do NOT bump versions:** Please do not bump the version numbers in `manifest.json`, `manifest-beta.json`, or `package.json` in your Pull Requests. Version bumping and release coordination are handled exclusively by the maintainer during the final GitHub Release workflow.
- **Release Notes:** If you are adding a feature or fixing a bug that users need to know about, please document it in `src/shared/Dialogs/Messages.ts` under the upcoming version key.
Once again, thank you for contributing to the plugin!
-121
View File
@@ -1,121 +0,0 @@
import { mathjax } from "mathjax-full/js/mathjax";
import { TeX } from 'mathjax-full/js/input/tex.js';
import { SVG } from 'mathjax-full/js/output/svg.js';
import { LiteAdaptor,liteAdaptor } from 'mathjax-full/js/adaptors/liteAdaptor.js';
import { RegisterHTMLHandler } from 'mathjax-full/js/handlers/html.js';
import { AllPackages } from 'mathjax-full/js/input/tex/AllPackages.js';
import { customAlphabet } from "nanoid";
import type { TAbstractFile, TFile } from "obsidian";
type DataURL = string & { _brand: "DataURL" };
type FileId = string & { _brand: "FileId" };
const fileid = customAlphabet("1234567890abcdef", 40);
type LatexPluginLike = {
app: {
vault: {
getFileByPath: (path: string) => TFile | null;
getAbstractFileByPath: (path: string) => TAbstractFile | null;
read: (file: TAbstractFile) => Promise<string>;
};
};
settings: {
latexPreambleLocation?: string;
};
};
let adaptor: LiteAdaptor;
let html: ReturnType<typeof mathjax.document>;
let preamble: string;
function svgToBase64(svg: string): string {
const cleanSvg = svg.replaceAll("&nbsp;", " ");
// Convert the string to UTF-8 and handle non-Latin1 characters
const encodedData = encodeURIComponent(cleanSvg)
.replace(/%([0-9A-F]{2})/g,
(match, p1) => String.fromCharCode(parseInt(p1, 16))
);
return `data:image/svg+xml;base64,${btoa(encodedData)}`;
}
async function getImageSize(src: string): Promise<{ height: number; width: number }> {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve({ height: img.naturalHeight, width: img.naturalWidth });
img.onerror = reject;
img.src = src;
});
}
export async function tex2dataURL(
tex: string,
scale: number = 4,
plugin?: LatexPluginLike
): Promise<{
mimeType: string;
fileId: FileId;
dataURL: DataURL;
created: number;
size: { height: number; width: number };
}> {
let input: TeX<Record<string, never>, Record<string, never>, Record<string, never>>;
let output: SVG<Record<string, never>, Record<string, never>, Record<string, never>>;
if(!adaptor) {
if (plugin) {
const file = plugin.app.vault.getFileByPath(plugin.settings.latexPreambleLocation || "preamble.sty");
preamble = file ? await plugin.app.vault.read(file) : null;
}
adaptor = liteAdaptor();
RegisterHTMLHandler(adaptor);
input = new TeX({
packages: AllPackages,
...(preamble ? {
inlineMath: [['$', '$']],
displayMath: [['$$', '$$']]
} : {}),
});
output = new SVG({ fontCache: "local" });
html = mathjax.document("", { InputJax: input, OutputJax: output });
}
try {
const node = html.convert(
preamble ? `${preamble}\n${tex}` : tex,
{ display: true, scale }
);
const svg = new DOMParser().parseFromString(adaptor.innerHTML(node), "image/svg+xml").firstChild as SVGSVGElement;
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2195
//https://stackoverflow.com/a/77181931
svg.insertAdjacentHTML("beforeend", "<style>.mjx-solid { stroke-width: 80px; }</style>");
if (svg) {
if(svg.width.baseVal.valueInSpecifiedUnits < 2) {
svg.width.baseVal.valueAsString = `${(svg.width.baseVal.valueInSpecifiedUnits+1).toFixed(3)}ex`;
}
const img = svgToBase64(svg.outerHTML);
svg.width.baseVal.valueAsString = (svg.width.baseVal.valueInSpecifiedUnits * 10).toFixed(3);
svg.height.baseVal.valueAsString = (svg.height.baseVal.valueInSpecifiedUnits * 10).toFixed(3);
const dataURL = svgToBase64(svg.outerHTML);
return {
mimeType: "image/svg+xml",
fileId: fileid() as FileId,
dataURL: dataURL as DataURL,
created: Date.now(),
size: await getImageSize(img),
};
}
} catch (e) {
console.error(e);
}
return null;
}
export function clearMathJaxVariables(): void {
adaptor = null;
html = null;
preamble = null;
}
-1655
View File
File diff suppressed because it is too large. Load diff
-28
View File
@@ -1,28 +0,0 @@
{
"name": "@zsviczian/mathjax-to-svg",
"version": "1.0.0",
"main": "dist/index.js",
"scripts": {
"build": "cross-env NODE_ENV=production rollup --config rollup.config.mjs",
"dev": "cross-env NODE_ENV=development rollup --config rollup.config.mjs"
},
"dependencies": {
"mathjax-full": "^3.2.2",
"nanoid": "^5.0.9"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^26.0.1",
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^12.1.2",
"cross-env": "^7.0.3",
"obsidian": "1.5.7-1",
"rollup": "^4.14.0",
"tslib": "^2.8.1",
"typescript": "5.9.3"
},
"engines": {
"node": ">=22.0.0",
"npm": ">=10.0.0"
}
}
-36
View File
@@ -1,36 +0,0 @@
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import typescript from '@rollup/plugin-typescript';
import terser from '@rollup/plugin-terser'; // <-- Updated import
const isProd = (process.env.NODE_ENV === 'production');
export default {
input: './index.ts',
output: {
dir: 'dist',
format: 'iife',
name: 'MathjaxToSVG', // Global variable name
exports: 'named',
sourcemap: !isProd,
},
plugins: [
typescript({
tsconfig: 'tsconfig.json',
sourceMap: !isProd, // <-- Explicitly tell TS compiler to output maps in dev
}),
commonjs(),
nodeResolve({
browser: true,
preferBuiltins: false
}),
isProd && terser({
format: {
comments: false,
},
compress: {
passes: 2,
}
})
].filter(Boolean)
};
-27
View File
@@ -1,27 +0,0 @@
{
"compilerOptions": {
"baseUrl": ".",
"sourceMap": true,
"module": "es2022",
"target": "es2022",
"allowJs": false,
"noImplicitAny": true,
"moduleResolution": "bundler",
"esModuleInterop": true,
"importHelpers": true,
"resolveJsonModule": true,
"lib": [
"dom",
"scripthost",
"es2022",
"DOM.Iterable"
],
"jsx": "react"
},
"include": [
"**/*.ts",
"**/*.tsx",
"src/shared/Dialogs/OpenDrawing.ts",
"src/types/types.d.ts"
]
}
+3 -1
View File
@@ -6,6 +6,8 @@
The Obsidian-Excalidraw plugin integrates [Excalidraw](https://excalidraw.com/), a feature rich sketching tool, into Obsidian. You can store and edit Excalidraw files in your vault, you can embed drawings into your documents, and you can link to documents and other drawings to/and from Excalidraw. For a showcase of Excalidraw features watch the videos below.
![Excalidraw Screenshot](https://github.com/user-attachments/assets/dde1df97-c6ae-491c-b546-65ec2d625326)
Excalidraw for Obsidian keeps evolving; it is extremely feature‑rich and can feel intimidating at first. The Video Walkthrough below should ease that initial overwhelm. For a comprehensive, searchable knowledge base covering features, settings, scripting, workflows, and visual thinking methods, explore the public [NotebookLM workbook](https://notebooklm.google.com/notebook/42d76a2f-c11d-4002-9286-1683c43d0ab0) (a must‑have learning resource).
<a href="https://community.sketch-your-mind.com/ee"><img src="https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/images/logo-EE.png?raw=true" width="150"></a>
@@ -378,4 +380,4 @@ You can find me on Twitter [@zsviczian](https://twitter.com/zsviczian), and on m
## Friends of Excalidraw
If you enjoy Excalidraw, consider giving [ExcaliBrain](https://github.com/zsviczian/excalibrain) a try (also available via Obsidian Community Plugins).
<a href="https://youtu.be/gOkniMkDPyM" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/169708346-9e41289d-9536-43ec-8f70-2d2ad2d369d6.png" width="300"/></a>
<a href="https://youtu.be/gOkniMkDPyM" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/169708346-9e41289d-9536-43ec-8f70-2d2ad2d369d6.png" width="300"/></a>
@@ -5,11 +5,16 @@
/* ************************************** */
/* lib/shared/ExcalidrawAutomate.d.ts */
/* ************************************** */
type ExcalidrawCustomDataValue = string | number | boolean | null | ExcalidrawCustomDataValue[] | {
[key: string]: ExcalidrawCustomDataValue;
};
type ExcalidrawCustomDataPatch = Partial<Record<string, ExcalidrawCustomDataValue | undefined>>;
type ExcalidrawAutomateHelpTarget = ((...args: any[]) => any) | string;
type MutableElementMapEntry = Mutable<ExcalidrawElement> & Record<string, unknown>;
import { PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFPageProperties, ExportSettings } from "src/types/exportUtilTypes";
import { FrameRenderingOptions, PaneTarget } from "src/types/utilTypes";
import { AutoexportConfig } from "src/types/excalidrawViewTypes";
import { FloatingModal } from "./Dialogs/FloatingModal";
import { ExcalidrawSidepanelTab } from "src/view/sidepanel/SidepanelTab";
import { ObsidianCanvasNode } from "src/view/managers/CanvasNodeFactory";
import { AIRequest, ExcalidrawAISettings } from "src/types/AIUtilTypes";
import { CaptureUpdateActionType } from "@zsviczian/excalidraw/types/element/src";
type ExcalidrawAutomateHelpTarget = ((...args: unknown[]) => unknown) | string;
/**
* 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.
@@ -91,6 +96,12 @@ export declare class ExcalidrawAutomate {
* Prints a detailed breakdown of the startup time.
*/
printStartupBreakdown(): void;
/**
* Prints all URLs grouped by their respective justifications.
* Useful for auditing and generating scanner exception reports.
* @returns {void}
*/
printURLsInCodebase(): void;
/**
* Add or modify keys in an element's customData while preserving existing keys.
* Creates customData={} if it does not exist.
@@ -129,7 +140,7 @@ export declare class ExcalidrawAutomate {
*/
generateAIText(request: AIRequest): Promise<{
response: RequestUrlResponse;
json: any;
json: Record<string, unknown>;
content: string;
rateLimit: number | null;
rateLimitRemaining: number | null;
@@ -139,7 +150,7 @@ export declare class ExcalidrawAutomate {
*/
analyzeAIImage(request: AIRequest): Promise<{
response: RequestUrlResponse;
json: any;
json: Record<string, unknown>;
content: string;
rateLimit: number | null;
rateLimitRemaining: number | null;
@@ -160,6 +171,24 @@ export declare class ExcalidrawAutomate {
* Creates a lightweight chat session wrapper that preserves prior messages between calls.
*/
createAIChatSession(initialRequest?: Omit<AIRequest, "messages">): import("../utils/AIUtils").AIChatSession;
/**
* Returns the accumulated AI token usage for the current Obsidian session.
* Usage is keyed by model identifier and tracks input/output tokens for text
* models and generation counts for image models.
* Data is not persisted and resets when Obsidian is restarted.
*/
getAIUsage(): import("src/types/AIUtilTypes").AIUsageData;
/**
* Opens a modal dialog showing per-model AI token usage for the current session.
* The dialog includes a "Copy as Markdown" button so the table can be pasted elsewhere.
*/
showAIUsageModal(): void;
/**
* Returns a compact label string summarising total session token usage.
* Format: "AI Usage: 355k/23k" (input tokens / output tokens).
* Appends image generation count when present, e.g. "+ 3 imgs".
*/
formatAIUsageLabel(): string;
/**
* Extracts code blocks from markdown text.
* @param {string} markdown - The markdown string to parse.
@@ -275,7 +304,7 @@ export declare class ExcalidrawAutomate {
isExcalidrawMaskFile(file?: TFile): boolean;
plugin: ExcalidrawPlugin;
elementsDict: {
[key: string]: any;
[key: string]: MutableElementMapEntry;
};
imagesDict: {
[key: FileId]: ImageInfo;
@@ -302,6 +331,7 @@ export declare class ExcalidrawAutomate {
startArrowHead: string;
endArrowHead: string;
};
setStyle(style: Partial<ExcalidrawAutomate["style"]>): void;
canvas: {
theme: string;
viewBackgroundColor: string;
@@ -444,23 +474,23 @@ export declare class ExcalidrawAutomate {
/**
* Extracts the Excalidraw Scene from an Excalidraw File.
* @param {TFile} file - The Excalidraw file to extract the scene from.
* @returns {Promise<{elements: ExcalidrawElement[]; appState: AppState;}>} Promise resolving to the Excalidraw scene.
* @returns {Promise<{elements: ExcalidrawElement[]; appState: Partial<AppState>;}>} Promise resolving to the Excalidraw scene.
*/
getSceneFromFile(file: TFile): Promise<{
elements: ExcalidrawElement[];
appState: AppState;
appState: Partial<AppState>;
}>;
/**
* Gets all elements from ExcalidrawAutomate elementsDict.
* @returns {Mutable<ExcalidrawElement>[]} Array of elements from elementsDict.
*/
getElements(): Mutable<ExcalidrawElement>[];
getElements(): MutableElementMapEntry[];
/**
* Gets a single element from ExcalidrawAutomate elementsDict.
* @param {string} id - The element ID to retrieve.
* @returns {Mutable<ExcalidrawElement>} The element with the specified ID.
*/
getElement(id: string): Mutable<ExcalidrawElement>;
getElement(id: string): MutableElementMapEntry;
/**
* Returns an object describing the bound text element.
*
@@ -492,14 +522,8 @@ export declare class ExcalidrawAutomate {
sceneElement?: ExcalidrawTextElement;
};
/**
* Creates a drawing and saves it to the specified filename.
* @param {Object} [params] - Parameters for creating the drawing.
* @param {string} [params.filename] - The filename for the drawing. If null, default filename as defined in Excalidraw settings.
* @param {string} [params.foldername] - The folder name for the drawing. If null, default folder as defined in Excalidraw settings.
* @param {string} [params.templatePath] - The template path to use for the drawing.
* @param {boolean} [params.onNewPane] - Whether to open the drawing in a new pane.
* @param {boolean} [params.silent] - Whether to create the drawing silently.
* @param {Object} [params.frontmatterKeys] - Frontmatter keys to include in the drawing.
* Creates a new Excalidraw drawing file from current EA state and optional template.
* @param params - Optional creation parameters.
* @param {string} [params.plaintext] - Text to insert above the `# Text Elements` section.
* @returns {Promise<string>} Promise resolving to the path of the created drawing.
*/
@@ -620,7 +644,7 @@ export declare class ExcalidrawAutomate {
* @param {number} [padding] - The padding to use for the PNG.
* @returns {Promise<any>} Promise resolving to the created PNG image.
*/
createPNG(templatePath?: string, scale?: number, exportSettings?: ExportSettings, loader?: EmbeddedFilesLoader, theme?: string, padding?: number): Promise<any>;
createPNG(templatePath?: string, scale?: number, exportSettings?: ExportSettings, loader?: EmbeddedFilesLoader, theme?: string, padding?: number): Promise<Blob>;
/**
* Wrapper for createPNG() that returns a base64 encoded string designed to support LLM workflows.
* @param {string} [templatePath] - The template path to use for the PNG.
@@ -806,7 +830,7 @@ export declare class ExcalidrawAutomate {
* @param {string} [id] - The ID of the line element.
* @returns {string} The ID of the added line element.
*/
addLine(points: [[x: number, y: number]], id?: string): string;
addLine(points: [x: number, y: number][], id?: string): string;
/**
* Adds an arrow element to the ExcalidrawAutomate instance.
* @param {[x: number, y: number][]} points - Array of points defining the arrow.
@@ -982,21 +1006,34 @@ export declare class ExcalidrawAutomate {
addBackOfTheCardNoteToView(sectionTitle: string, activate?: boolean, sectionBody?: string, embeddableCustomData?: EmbeddableMDCustomProps): Promise<string>;
/**
* Gets the selected element in the view. If more are selected, gets the first.
* @returns {any} The selected element or null if none selected.
* @returns {ExcalidrawElement | null} The selected element or null if none selected.
*/
getViewSelectedElement(): any;
getViewSelectedElement(): ExcalidrawElement | null;
/**
* Gets the selected elements in the view.
* @param {boolean} [includeFrameChildren=true] - Whether to include frame children in the selection.
* @returns {any[]} Array of selected elements.
* @returns {ExcalidrawElement[]} Array of selected elements.
*/
getViewSelectedElements(includeFrameChildren?: boolean): any[];
getViewSelectedElements(includeFrameChildren?: boolean): ExcalidrawElement[];
/**
* Gets the file associated with an image element in the view.
* @param {ExcalidrawElement} el - The image element.
* @returns {TFile | null} The file associated with the image element or null if not found.
*/
getViewFileForImageElement(el: ExcalidrawElement): TFile | null;
/**
* Returns the vault or external URI path for an image file identified by its Excalidraw fileId.
*
* Note: Excalidraw does not maintain a persistent index of fileIds to paths.
* The `filesMaster` cache is populated at runtime as images appear in open drawings,
* and is used to support copy/paste of image references between drawings without
* duplicating files. This function will only return a path for images that have
* been seen in a drawing during the current Obsidian session.
*
* @param {FileId} fileId - The Excalidraw fileId of the image.
* @returns {string | null} The vault path of the image file, or null if not cached.
*/
getPathForImageFileId(fileId: FileId): string | null;
/**
* Gets the color map associated with an image element in the view.
* @param {ExcalidrawElement} el - The image element.
@@ -1051,8 +1088,8 @@ export declare class ExcalidrawAutomate {
* @param {ExcalidrawElement[]} [scene.elements] - Array of elements in the scene.
* @param {AppState} [scene.appState] - The app state of the scene.
* @param {BinaryFiles} [scene.files] - The files in the scene.
* @param {boolean} [scene.commitToHistory] - Whether to commit the scene to history. @deprecated Use scene.storageOption instead
* @param {"capture" | "none" | "update"} [scene.storeAction] - The store action for the scene. @deprecated Use scene.storageOption instead
* @param {boolean} [scene.commitToHistory] - Deprecated: Use scene.storageOption instead.
* @param {"capture" | "none" | "update"} [scene.storeAction] - Deprecated: Use scene.storageOption instead
* @param {"IMMEDIATELY" | "NEVER" | "EVENTUALLY"} [scene.captureUpdate] - The capture update action for the scene.
* @param {boolean} [restore=false] - Whether to restore legacy elements in the scene.
*/
@@ -1086,8 +1123,9 @@ export declare class ExcalidrawAutomate {
* Zooms the target view to fit the specified elements.
* @param {boolean} selectElements - Whether to select the elements after zooming.
* @param {ExcalidrawElement[]} elements - Array of elements to zoom to.
* @param {number} [margin=0.05] - The margin around the elements when zooming.
*/
viewZoomToElements(selectElements: boolean, elements: ExcalidrawElement[]): void;
viewZoomToElements(selectElements: boolean, elements: ExcalidrawElement[], margin?: number): void;
/**
* Adds elements from elementsDict to the current view.
* @param {boolean} [repositionToCursor=false] - Whether to reposition the elements to the cursor.
@@ -1141,7 +1179,7 @@ export declare class ExcalidrawAutomate {
onDropHook: (data: {
ea: ExcalidrawAutomate;
event: React.DragEvent<HTMLDivElement>;
draggable: any;
draggable: ObsidianDraggable;
type: "file" | "text" | "unknown";
payload: {
files: TFile[];
@@ -1420,7 +1458,7 @@ export declare class ExcalidrawAutomate {
* @param {Object} settings - The script settings to set.
* @returns {Promise<void>} Promise resolving when the settings are saved.
*/
setScriptSettings(settings: any): Promise<void>;
setScriptSettings(settings: Record<string, unknown>): Promise<void>;
setScriptSettingValue(key: string, value: ScriptSettingValue): void;
getScriptSettingValue(key: string, defaultValue: ScriptSettingValue): ScriptSettingValue;
saveScriptSettings(): Promise<void>;
@@ -1488,13 +1526,22 @@ export declare class ExcalidrawAutomate {
* @returns {ExcalidrawElement} The cloned element with a new ID.
*/
cloneElement(element: ExcalidrawElement): ExcalidrawElement;
/**
* Clones an array of Excalidraw elements or a clipboard string.
* Ensures that relationships (containers, bound elements, groups, bindings)
* are correctly remapped to the newly generated IDs.
*
* @param {ExcalidrawElement[] | string} elementsOrClipboard - The elements array or Excalidraw clipboard string.
* @returns {ExcalidrawElement[]} An array of cloned elements with new IDs and updated relationships.
*/
cloneElements(elementsOrClipboard: ExcalidrawElement[] | string): ExcalidrawElement[];
/**
* Moves the specified element to a specific position in the z-index.
* * Operates directly on the Excalidraw Scene in targetView, not through ExcalidrawAutomate elements.
* @param {number} elementId - The ID of the element to move.
* @param {string} elementId - The ID of the element to move.
* @param {number} newZIndex - The new z-index position for the element.
*/
moveViewElementToZIndex(elementId: number, newZIndex: number): void;
moveViewElementToZIndex(elementId: string, newZIndex: number): void;
/**
* Converts a hex color string to an RGB array.
* @deprecated Use getCM / ColorMaster instead.
@@ -1761,6 +1808,27 @@ export interface FrameRenderingOptions {
outline: boolean;
clip: boolean;
}
export type PaneTarget = "active-pane" | "new-pane" | "popout-window" | "new-tab" | "md-properties";
export interface NestedFileNode {
file: TFile;
/**
* All distinct dependency paths from the root file down to this embedded file.
* Each path is an ordered array of TFile objects starting with the `rootFile` at index 0.
*
* @example
* If Root -> A -> B2.2 and Root -> B -> B2 -> B2.2
* The paths for B2.2 will be:
* [
* [Root, A, B2.2],
* [Root, B, B2, B2.2]
* ]
*
* Usage: To find which top-level embeds to reload if this file changes,
* you can map over `paths` and collect `path[1]`.
*/
paths: TFile[][];
}
export type NestedFileMap = Map<TFile, NestedFileNode>;
/* ************************************ */
/* lib/types/exportUtilTypes.d.ts */
@@ -1853,6 +1921,71 @@ export interface ExportSettings {
frameRendering?: FrameRenderingOptions;
skipInliningFonts?: boolean;
}
export interface PrintToPDFOptions {
includeName: boolean;
pageSize: string | {
width: number;
height: number;
};
landscape: boolean;
margins: {
top: number;
left: number;
right: number;
bottom: number;
};
scaleFactor: number;
scale: number;
open: boolean;
filepath: string;
preferCSSPageSize?: boolean;
pageRanges?: string | {
from: number;
to: number;
}[];
}
export interface SaveDialogOptions {
defaultPath: string;
filters: {
name: string;
extensions: string[];
}[];
properties: string[];
}
export interface SaveDialogReturnValue {
canceled: boolean;
filePath?: string;
}
type CaptureRect = {
x: number;
y: number;
width: number;
height: number;
};
type NativeImageLike = {
toPNG(): Uint8Array | Buffer;
};
interface ElectronWebContentsLike {
capturePage(rect: CaptureRect): Promise<NativeImageLike>;
getZoomFactor(): number;
setZoomFactor(factor: number): void;
}
interface ElectronWebUtilsLike {
getPathForFile(file: File): string;
}
export interface ElectronAPI {
ipcRenderer: {
send(channel: string, ...args: unknown[]): void;
once(channel: string, func: (...args: unknown[]) => void): void;
};
remote: {
dialog: {
showSaveDialog(options: SaveDialogOptions): Promise<SaveDialogReturnValue>;
};
getCurrentWebContents(): ElectronWebContentsLike;
};
webUtils: ElectronWebUtilsLike;
}
/* ************************************** */
/* lib/types/embeddedFileLoaderTypes.d.ts */
@@ -2022,6 +2155,20 @@ export type AIRequestMessage = {
role: "system" | "user" | "assistant";
content: string | AIRequestMessagePart[];
};
export type AITextUsageEntry = {
inputTokens: number;
outputTokens: number;
};
export type AIImageUsageEntry = {
generations: number;
};
export type AIUsageData = {
textModels: Record<string, AITextUsageEntry>;
imageModels: Record<string, AIImageUsageEntry>;
totalInputTokens: number;
totalOutputTokens: number;
totalImageGenerations: number;
};
export type AIRequest = {
provider?: AIProvider;
baseURL?: string;
@@ -2845,6 +2992,7 @@ export type OnExportProgress = {
};
export interface ExcalidrawProps {
onChange?: (elements: readonly OrderedExcalidrawElement[], appState: AppState, files: BinaryFiles) => void;
onThemeChange?: (theme: Theme | "system") => void;
/**
* note: only subscribes if the props.onIncrement is defined on initial render
*/
@@ -2906,6 +3054,10 @@ export interface ExcalidrawProps {
name?: string;
renderCustomStats?: (elements: readonly NonDeletedExcalidrawElement[], appState: UIAppState) => JSX.Element;
UIOptions?: Partial<UIOptions>;
/**
* dimensions and size constraints for inserted images
*/
imageOptions?: ImageOptions;
detectScroll?: boolean;
handleKeyboardGlobally?: boolean;
onLibraryChange?: (libraryItems: LibraryItems) => void | Promise<any>;
@@ -2917,7 +3069,6 @@ export interface ExcalidrawProps {
nextLink: string;
};
generateIdForFile?: (file: File) => string | Promise<string>;
onThemeChange?: (newTheme: string) => void;
onViewModeChange?: (isViewModeEnabled: boolean) => void;
generateLinkForSelection?: (id: string, type: "element" | "group") => string;
onLinkOpen?: (element: NonDeletedExcalidrawElement, event: CustomEvent<{
@@ -2974,12 +3125,21 @@ export type ExportOpts = {
onExportToBackend?: (exportedElements: readonly NonDeletedExcalidrawElement[], appState: UIAppState, files: BinaryFiles) => void;
renderCustomUI?: (exportedElements: readonly NonDeletedExcalidrawElement[], appState: UIAppState, files: BinaryFiles, canvas: HTMLCanvasElement) => JSX.Element;
};
export type ImageOptions = Partial<{
maxWidthOrHeight: number;
maxFileSizeBytes: number;
}>;
export type CanvasActions = Partial<{
changeViewBackgroundColor: boolean;
clearCanvas: boolean;
export: false | ExportOpts;
loadScene: boolean;
saveToActiveFile: boolean;
/**
* defaults to true if `props.theme` is omitted or `props.onThemeChange`
* is supplied (at which point the theme is considered as host-app controlled),
* else default to false
* */
toggleTheme: boolean | null;
saveAsImage: boolean;
}>;
@@ -3003,6 +3163,7 @@ export type AppProps = Merge<ExcalidrawProps, {
export: ExportOpts;
};
}>;
imageOptions: Required<ImageOptions>;
detectScroll: boolean;
handleKeyboardGlobally: boolean;
isCollaborating: boolean;
@@ -3313,6 +3474,23 @@ export declare const pointInsideBounds: <P extends GlobalPoint | LocalPoint>(p:
export declare const pointInsideBoundsInclusive: <P extends GlobalPoint | LocalPoint>(p: P, bounds: Bounds) => boolean;
export declare const doBoundsIntersect: (bounds1: Bounds | null, bounds2: Bounds | null) => boolean;
export declare const boundsContainBounds: (outerBounds: Bounds, innerBounds: Bounds) => boolean;
/**
* High level helper to get elements overlapping a bounding box.
* It can be used to get elements overlapping a selection box, for example.
*
*/
export declare const elementsOverlappingBBox: ({ elements, elementsMap, bounds, type, excludeElementsInFrames, shouldIgnoreElementFromSelection, }: {
elements: readonly NonDeletedExcalidrawElement[];
elementsMap?: ElementsMap;
bounds: Bounds | ExcalidrawElement;
/**
* - overlap: elements overlapping or inside bounds
* - contain: elements inside bounds
**/
type: "contain" | "overlap";
excludeElementsInFrames?: boolean;
shouldIgnoreElementFromSelection?: (element: NonDeletedExcalidrawElement) => boolean;
}) => NonDeletedExcalidrawElement[];
export declare const elementCenterPoint: (element: ExcalidrawElement, elementsMap: ElementsMap, xOffset?: number, yOffset?: number) => GlobalPoint;
/* ************************************** */
@@ -3432,7 +3610,6 @@ declare class App extends React.Component<AppProps, AppState> {
y: number;
};
allowMobileMode: boolean;
animationFrameHandler: AnimationFrameHandler;
laserTrails: LaserTrails;
eraserTrail: EraserTrail;
lassoTrail: LassoTrail;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+66 -1
View File
@@ -139,7 +139,7 @@ Imports markdown bullet hierarchy into the map.
#### `exportMarkdown({ nodeId?, cut? }): Promise<MMResult<{ markdown: string }>>`
Copies selected branch as markdown to clipboard and returns the markdown text.
### Submaps and config
### Map and Global config
#### `toggleSubmapRoot({ nodeId?, enabled? }): Promise<MMResult<{ nodeId; enabled }>>`
Toggles additional-root status (or forces it when `enabled` is provided).
@@ -161,6 +161,15 @@ Returns all project element IDs under a root.
#### `getElementIdsByRole(rootId: string): MMResult<{ nodes; branchArrows; crossLinks; boundaries; decorations; boundTexts }>`
Returns categorized element IDs for selective styling or export workflows.
#### `getConfigSchema(): MMResult<{ schema: object }>`
Returns the schema, allowed values, data types, and definitions for all map configurations. Useful for external agents to validate payloads before passing them to `setGlobalConfig` or `setMapConfig`.
#### `getGlobalConfig(): MMResult<{ config: object }>`
Returns the current active global settings, including layout configurations, growth strategy, and the custom color palette.
#### `setGlobalConfig({ patch }): Promise<MMResult<{ success: boolean }>>`
Updates the global map and layout configurations using a partial JSON patch. It automatically validates against allowed parameters, updates the in-memory state so the Sidepanel UI refreshes immediately, and persists the settings.
---
## Actions enum
@@ -464,6 +473,62 @@ if (!roles.ok) return;
})();
```
### 11) Update global configuration and custom color palette
```js
const mmb = window.MindMapBuilderAPI;
if (!mmb?.ready()) throw new Error("MindMapBuilderAPI not ready");
// 1. (Optional) Check the schema to understand allowed values
const schemaRes = mmb.getConfigSchema();
if (schemaRes.ok) {
// e.g., ["Radial", "Right-facing", "Left-facing", "Right-Left", "Up-facing", "Down-facing", "Up-Down"]
console.log("Allowed Growth Modes:", schemaRes.data.schema.growthMode.valueset);
}
// 2. Fetch the current global configuration
const configRes = mmb.getGlobalConfig();
if (configRes.ok) {
console.log("Current Base Stroke Width:", configRes.data.config.baseStrokeWidth);
}
// 3. Apply a patch to the global configuration
// This example sets the growth mode, adjusts stroke width, modifies layout spacing,
// and configures a custom sequential color palette.
const patch = {
growthMode: "Right-facing",
multicolor: true,
baseStrokeWidth: 8,
customPalette: {
enabled: true,
random: false, // Set to true to pick random colors from the array instead of sequentially
colors: [
"#ff595e", // red
"#ff922b", // orange
"#fcc419", // yellow
"#51cf66", // green
"#339af0", // blue
"#845ef7" // purple
]
},
layoutSettings: {
GAP_X: 150,
GAP_Y: 35
}
};
const updateRes = await mmb.setGlobalConfig({ patch });
if (updateRes.ok) {
console.log("Global settings and custom color palette updated successfully!");
// Subsequent calls to mmb.addNode() or mmb.refreshMapLayout()
// will now utilize these newly established global settings.
} else {
console.error("Failed to update global config:", updateRes.error.message);
}
```
---
## ExcalidrawAutomate integration note
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-book-heart-icon lucide-book-heart"><path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20"/><path d="M8.62 9.8A2.25 2.25 0 1 1 12 6.836a2.25 2.25 0 1 1 3.38 2.966l-2.626 2.856a.998.998 0 0 1-1.507 0z"/></svg>

After

Width:  |  Height:  |  Size: 451 B

File diff suppressed because it is too large. Load diff
+10
View File
@@ -0,0 +1,10 @@
<svg class="svg-icon lucide-swatch-book" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<!-- bottom swatch card (peeking out) -->
<path d="M8 13H19a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H6V13Z" fill="#FFD23F"/>
<!-- back / cover card with binder ring -->
<path d="M11 17a4 4 0 0 1-8 0V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2Z" fill="#FF6B6B"/>
<!-- flipped-open top card -->
<path d="m11 8 2.3-2.3a2.4 2.4 0 0 1 3.404.004L18.6 7.6a2.4 2.4 0 0 1 .026 3.434L9.9 19.8Z" fill="#4ECDC4"/>
<!-- binder ring hole -->
<path d="M7 17h.01"/>
</svg>

After

Width:  |  Height:  |  Size: 668 B

File diff suppressed because it is too large. Load diff
+132 -3
View File
@@ -786,6 +786,122 @@ const getValidSizesForModel = (model) => {
return ["1024x1024"];
};
const parseImageSizeDimensions = (size) => {
const match = String(size ?? "").trim().match(/^(\d+)x(\d+)$/i);
if(!match) {
return null;
}
const width = parseInt(match[1], 10);
const height = parseInt(match[2], 10);
if(Number.isNaN(width) || Number.isNaN(height) || width <= 0 || height <= 0) {
return null;
}
return {width, height};
};
const greatestCommonDivisor = (a, b) => {
let x = Math.abs(a);
let y = Math.abs(b);
while(y !== 0) {
const remainder = x % y;
x = y;
y = remainder;
}
return x || 1;
};
const CANONICAL_ASPECT_RATIOS = [
"1:8",
"1:4",
"2:3",
"3:4",
"4:5",
"9:16",
"1:1",
"16:9",
"5:4",
"4:3",
"3:2",
"4:1",
"8:1",
"21:9",
].map((label) => {
const [width, height] = label.split(":").map((value) => parseInt(value, 10));
return {
label,
ratio: width/height,
};
});
const ASPECT_RATIO_LABEL_RELATIVE_EPSILON = 0.02;
const getCanonicalAspectRatioLabel = (width, height) => {
const ratio = width/height;
const nearest = CANONICAL_ASPECT_RATIOS
.map((candidate) => ({
...candidate,
delta: Math.abs(candidate.ratio - ratio),
}))
.sort((left, right) => left.delta - right.delta)[0];
if(
nearest &&
nearest.delta/Math.max(nearest.ratio, Number.EPSILON)
<= ASPECT_RATIO_LABEL_RELATIVE_EPSILON
) {
return nearest.label;
}
const divisor = greatestCommonDivisor(width, height);
return `${Math.round(width/divisor)}:${Math.round(height/divisor)}`;
};
const getAspectRatioLabelFromDimensions = (width, height) => {
return getCanonicalAspectRatioLabel(width, height);
};
const getImageSizeDropdownOptions = (sizes = []) => {
return sizes
.map((size) => {
const dimensions = parseImageSizeDimensions(size);
if(!dimensions) {
return {
value: size,
label: String(size ?? ""),
ratioOrder: Number.POSITIVE_INFINITY,
pixels: Number.POSITIVE_INFINITY,
width: Number.POSITIVE_INFINITY,
height: Number.POSITIVE_INFINITY,
};
}
const ratioLabel = getAspectRatioLabelFromDimensions(dimensions.width, dimensions.height);
return {
value: size,
label: `(${ratioLabel}) ${dimensions.width}x${dimensions.height}`,
ratioOrder: dimensions.width/dimensions.height,
pixels: dimensions.width * dimensions.height,
width: dimensions.width,
height: dimensions.height,
};
})
.sort((left, right) => {
if(left.ratioOrder !== right.ratioOrder) {
return left.ratioOrder - right.ratioOrder;
}
if(left.pixels !== right.pixels) {
return left.pixels - right.pixels;
}
if(left.width !== right.width) {
return left.width - right.width;
}
if(left.height !== right.height) {
return left.height - right.height;
}
return String(left.value).localeCompare(String(right.value));
});
};
const getResolvedTextModelSelection = (requestedModelId = selectedTextModel) => {
const availableModels = getAvailableTextModels();
const requestedConfigId = getTextModelConfigId(requestedModelId);
@@ -2484,7 +2600,9 @@ const openConfigModal = () => {
while(imageSizeSettingDropdown.selectEl.options.length > 0) {
imageSizeSettingDropdown.selectEl.remove(0);
}
validSizes.forEach(size => imageSizeSettingDropdown.addOption(size, size));
getImageSizeDropdownOptions(validSizes).forEach(({value, label}) =>
imageSizeSettingDropdown.addOption(value, label),
);
imageSizeSettingDropdown.setDisabled(!hasAvailableImageModels());
if(hasAvailableImageModels() && validSizes.length > 0) {
imageSizeSettingDropdown.setValue(imageSize);
@@ -2776,8 +2894,19 @@ const openConfigModal = () => {
updateTaskSpecificControls();
const runContainer = leftCol.createDiv({ cls: "excali-ai-run-container" });
new ea.obsidian.Setting(runContainer)
.addButton(button => button.setButtonText(" Run").setIcon("play").setCta().onClick(() => {
const runSetting = new ea.obsidian.Setting(runContainer);
if(ea.verifyMinimumPluginVersion && ea.verifyMinimumPluginVersion("2.23.4")) {
runSetting.addButton(button => {
button
.setButtonText(ea.formatAIUsageLabel())
.setIcon("bar-chart-2")
.setTooltip("View AI token usage for this session")
.onClick(() => {
ea.showAIUsageModal();
});
});
}
runSetting.addButton(button => button.setButtonText(" Run").setIcon("play").setCta().onClick(() => {
const taskConfig = getActiveTaskConfig();
if(!taskConfig) {
new Notice("No runnable AI task is selected.", 8000);
-674
View File
@@ -1,674 +0,0 @@
/*
<a href="https://www.youtube.com/watch?v=A1vrSGBbWgo" target="_blank"><img src ="https://i.ytimg.com/vi/A1vrSGBbWgo/maxresdefault.jpg" style="width:560px;"></a>
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg)
```js*/
let dirty=false;
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.0.12")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
const outputTypes = {
"html": {
instruction: "Turn this into a single html file using tailwind. Return a single message containing only the html file in a codeblock.",
blocktype: "html"
},
"mermaid": {
instruction: "Return a single message containing only the mermaid diagram in a codeblock.",
blocktype: "mermaid"
},
"svg": {
instruction: "Return a single message containing only the SVG code in an html codeblock.",
blocktype: "svg"
},
"image-gen": {
instruction: "Return a single message with the generated image prompt in a codeblock",
blocktype: "image"
},
"image-edit": {
instruction: "",
blocktype: "image"
}
}
const systemPrompts = {
"Challenge my thinking": {
prompt: `Your task is to interpret a screenshot of a whiteboard, translating its ideas into a Mermaid graph. The whiteboard will encompass thoughts on a subject. Within the mind map, distinguish ideas that challenge, dispute, or contradict the whiteboard content. Additionally, include concepts that expand, complement, or advance the user's thinking. Utilize the Mermaid graph diagram type and present the resulting Mermaid diagram within a code block. Ensure the Mermaid script excludes the use of parentheses ().`,
type: "mermaid",
help: "Translate your image and optional text prompt into a Mermaid mindmap. If there are conversion errors, edit the Mermaid script under 'More Tools'."
},
"Convert sketch to shapes": {
prompt: `Given an image featuring various geometric shapes drawn by the user, your objective is to analyze the input and generate SVG code that accurately represents these shapes. Your output will be the SVG code enclosed in an HTML code block.`,
type: "svg",
help: "Convert selected scribbles into shapes; works better with fewer shapes. Experimental and may not produce good drawings."
},
"Create a simple Excalidraw icon": {
prompt: `Given a description of an SVG image from the user, your objective is to generate the corresponding SVG code. Avoid incorporating textual elements within the generated SVG. Your output should be the resulting SVG code enclosed in an HTML code block.`,
type: "svg",
help: "Convert text prompts into simple icons inserted as Excalidraw elements. Expect only a text prompt. Experimental and may not produce good drawings."
},
"Edit an image": {
prompt: null,
type: "image-edit",
help: "Image elements will be used as the Image. Shapes on top of the image will be the Mask. Use the prompt to instruct Dall-e about the changes. Dall-e-2 model will be used."
},
"Generate an image from image and prompt": {
prompt: "Your task involves receiving an image and a textual prompt from the user. Your goal is to craft a detailed, accurate, and descriptive narrative of the image, tailored for effective image generation. Utilize the user-provided text prompt to inform and guide your depiction of the image. Ensure the resulting image remains text-free.",
type: "image-gen",
help: "Generate an image based on the drawing and prompt using ChatGPT-Vision and Dall-e. Provide a contextual text-prompt for accurate interpretation."
},
"Generate an image from prompt": {
prompt: null,
type: "image-gen",
help: "Send only the text prompt to OpenAI. Provide a detailed description; OpenAI will enrich your prompt automatically. To avoid it, start your prompt like this 'DO NOT add any detail, just use it AS-IS:'"
},
"Generate an image to illustrate a quote": {
prompt: "Your task involves transforming a user-provided quote into a detailed and imaginative illustration. Craft a visual representation that captures the essence of the quote and resonates well with a broad audience. If the Author's name is provided, aim to establish a connection between the illustration and the Author. This can be achieved by referencing a well-known story from the Author, situating the image in the Author's era or setting, or employing other creative methods of association. Additionally, provide preferences for styling, such as the chosen medium and artistic direction, to guide the image creation process. Ensure the resulting image remains text-free. Your task output should comprise a descriptive and detailed narrative aimed at facilitating the creation of a captivating illustration from the quote.",
type: "image-gen",
help: "ExcaliAI will create an image prompt to illustrate your text input - a quote - with GPT, then generate an image using Dall-e. In case you include the Author's name, GPT will try to generate an image that in some way references the Author."
},
"Visual brainstorm": {
prompt: "Your objective is to interpret a screenshot of a whiteboard, creating an image aimed at sparking further thoughts on the subject. The whiteboard will present diverse ideas about a specific topic. Your generated image should achieve one of two purposes: highlighting concepts that challenge, dispute, or contradict the whiteboard content, or introducing ideas that expand, complement, or enrich the user's thinking. You have the option to include multiple tiles in the resulting image, resembling a sequence akin to a comic strip. Ensure that the image remains devoid of text.",
type: "image-gen",
help: "Use ChatGPT Visions and Dall-e to create an image based on your text prompt and image to spark new ideas."
},
"Wireframe to code": {
prompt: `You are an expert tailwind developer. A user will provide you with a low-fidelity wireframe of an application and you will return a single html file that uses tailwind to create the website. Use creative license to make the application more fleshed out. Write the necessary javascript code. If you need to insert an image, use placehold.co to create a placeholder image.`,
type: "html",
help: "Use GPT Visions to interpret the wireframe and generate a web application. You may copy the resulting code from the active embeddable's top left menu."
},
}
const IMAGE_WARNING = "The generated image is linked through a temporary OpenAI URL and will be removed in approximately 30 minutes. To save it permanently, choose 'Save image from URL to local file' from the Obsidian Command Palette."
// --------------------------------------
// Initialize values and settings
// --------------------------------------
let settings = ea.getScriptSettings();
if(!settings["Agent's Task"]) {
settings = {
"Agent's Task": "Wireframe to code",
"User Prompt": "",
};
await ea.setScriptSettings(settings);
}
const OPENAI_API_KEY = ea.plugin.settings.openAIAPIToken;
if(!OPENAI_API_KEY || OPENAI_API_KEY === "") {
new Notice("You must first configure your API key in Excalidraw Plugin Settings");
return;
}
let userPrompt = settings["User Prompt"] ?? "";
let agentTask = settings["Agent's Task"];
let imageSize = settings["Image Size"]??"1024x1024";
if(!systemPrompts.hasOwnProperty(agentTask)) {
agentTask = Object.keys(systemPrompts)[0];
}
let imageModel, valideSizes;
const setImageModelAndSizes = () => {
imageModel = systemPrompts[agentTask].type === "image-edit"
? "dall-e-2"
: ea.plugin.settings.openAIDefaultImageGenerationModel;
validSizes = imageModel === "dall-e-2"
? [`256x256`, `512x512`, `1024x1024`]
: (imageModel === "dall-e-3"
? [`1024x1024`, `1792x1024`, `1024x1792`]
: [`1024x1024`])
if(!validSizes.includes(imageSize)) {
imageSize = "1024x1024";
dirty = true;
}
}
setImageModelAndSizes();
// --------------------------------------
// Generate Image Blob From Selected Excalidraw Elements
// --------------------------------------
const calculateImageScale = (elements) => {
const bb = ea.getBoundingBox(elements);
const size = (bb.width*bb.height);
const minRatio = Math.sqrt(360000/size);
const maxRatio = Math.sqrt(size/16000000);
return minRatio > 1
? minRatio
: (
maxRatio > 1
? 1/maxRatio
: 1
);
}
const createMask = async (dataURL) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;
for (let i = 0; i < data.length; i += 4) {
// If opaque (alpha > 0), make it transparent
if (data[i + 3] > 0) {
data[i + 3] = 0; // Set alpha to 0 (transparent)
} else if (data[i + 3] === 0) {
// If fully transparent, make it red
data[i] = 255; // Red
data[i + 1] = 0; // Green
data[i + 2] = 0; // Blue
data[i + 3] = 255; // make it opaque
}
}
ctx.putImageData(imageData, 0, 0);
const maskDataURL = canvas.toDataURL();
resolve(maskDataURL);
};
img.onerror = error => {
reject(error);
};
img.src = dataURL;
});
}
//https://platform.openai.com/docs/api-reference/images/createEdit
//dall-e-2 image edit only works on square images
//if targetDalleImageEdit === true then the image and the mask will be returned in two separate dataURLs
let squareBB;
const generateCanvasDataURL = async (view, targetDalleImageEdit=false) => {
let PADDING = 5;
await view.forceSave(true); //to ensure recently embedded PNG and other images are saved to file
const viewElements = ea.getViewSelectedElements();
if(viewElements.length === 0) {
return {imageDataURL: null, maskDataURL: null} ;
}
ea.copyViewElementsToEAforEditing(viewElements, true); //copying the images objects over to EA for PNG generation
let maskDataURL;
const loader = ea.getEmbeddedFilesLoader(false);
let scale = calculateImageScale(ea.getElements());
const bb = ea.getBoundingBox(viewElements);
if(ea.getElements()
.filter(el=>el.type==="image")
.some(el=>Math.round(el.width) === Math.round(bb.width) && Math.round(el.height) === Math.round(bb.height))
) { PADDING = 0; }
let exportSettings = {withBackground: true, withTheme: true};
if(targetDalleImageEdit) {
PADDING = 0;
const strokeColor = ea.style.strokeColor;
const backgroundColor = ea.style.backgroundColor;
ea.style.backgroundColor = "transparent";
ea.style.strokeColor = "transparent";
let rectID;
if(bb.height > bb.width) {
rectID = ea.addRect(bb.topX-(bb.height-bb.width)/2, bb.topY,bb.height, bb.height);
}
if(bb.width > bb.height) {
rectID = ea.addRect(bb.topX, bb.topY-(bb.width-bb.height)/2,bb.width, bb.width);
}
if(bb.height === bb.width) {
rectID = ea.addRect(bb.topX, bb.topY, bb.width, bb.height);
}
const rect = ea.getElement(rectID);
squareBB = {topX: rect.x-PADDING, topY: rect.y-PADDING, width: rect.width + 2*PADDING, height: rect.height + 2*PADDING};
ea.style.strokeColor = strokeColor;
ea.style.backgroundColor = backgroundColor;
ea.getElements().filter(el=>el.type === "image").forEach(el=>{el.isDeleted = true});
dalleWidth = parseInt(imageSize.split("x")[0]);
scale = dalleWidth/squareBB.width;
exportSettings = {withBackground: false, withTheme: true};
maskDataURL= await ea.createPNGBase64(
null, scale, exportSettings, loader, "light", PADDING
);
maskDataURL = await createMask(maskDataURL)
ea.getElements().filter(el=>el.type === "image").forEach(el=>{el.isDeleted = false});
ea.getElements().filter(el=>el.type !== "image" && el.id !== rectID).forEach(el=>{el.isDeleted = true});
}
const imageDataURL = await ea.createPNGBase64(
null, scale, exportSettings, loader, "light", PADDING
);
ea.clear();
return {imageDataURL, maskDataURL};
}
let {imageDataURL, maskDataURL} = await generateCanvasDataURL(ea.targetView, systemPrompts[agentTask].type === "image-edit");
// --------------------------------------
// Support functions - embeddable spinner and error
// --------------------------------------
const spinner = await ea.convertStringToDataURL(`
<html><head><style>
html, body {width: 100%; height: 100%; color: ${ea.getExcalidrawAPI().getAppState().theme === "dark" ? "white" : "black"};}
body {display: flex; align-items: center; justify-content: center; flex-direction: column; gap: 1rem; overflow: hidden;}
.Spinner {display: flex; align-items: center; justify-content: center; margin-left: auto; margin-right: auto;}
.Spinner svg {animation: rotate 1.6s linear infinite; transform-origin: center center; width: 40px; height: 40px;}
.Spinner circle {stroke: currentColor; animation: dash 1.6s linear 0s infinite; stroke-linecap: round;}
@keyframes rotate {100% {transform: rotate(360deg);}}
@keyframes dash {
0% {stroke-dasharray: 1, 300; stroke-dashoffset: 0;}
50% {stroke-dasharray: 150, 300; stroke-dashoffset: -200;}
100% {stroke-dasharray: 1, 300; stroke-dashoffset: -280;}
}
</style></head><body>
<div class="Spinner">
<svg viewBox="0 0 100 100">
<circle cx="50" cy="50" r="46" stroke-width="8" fill="none" stroke-miter-limit="10"/>
</svg>
</div>
<div>Generating...</div>
</body></html>`);
const errorMessage = async (spinnerID, message) => {
const error = "Something went wrong! Check developer console for more.";
const details = message ? `<p>${message}</p>` : "";
const errorDataURL = await ea.convertStringToDataURL(`
<html><head><style>
html, body {height: 100%;}
body {display: flex; flex-direction: column; align-items: center; justify-content: center; color: red;}
h1, h3 {margin-top: 0;margin-bottom: 0.5rem;}
</style></head><body>
<h1>Error!</h1>
<h3>${error}</h3>${details}
</body></html>`);
new Notice (error);
ea.getElement(spinnerID).link = errorDataURL;
ea.addElementsToView(false,true);
}
// --------------------------------------
// Utility to write Mermaid to dialog
// --------------------------------------
const EDITOR_LS_KEYS = {
OAI_API_KEY: "excalidraw-oai-api-key",
MERMAID_TO_EXCALIDRAW: "mermaid-to-excalidraw",
PUBLISH_LIBRARY: "publish-library-data",
};
const setMermaidDataToStorage = (mermaidDefinition) => {
try {
window.localStorage.setItem(
EDITOR_LS_KEYS.MERMAID_TO_EXCALIDRAW,
JSON.stringify(mermaidDefinition)
);
return true;
} catch (error) {
console.warn(`localStorage.setItem error: ${error.message}`);
return false;
}
};
// --------------------------------------
// Submit Prompt
// --------------------------------------
const generateImage = async(text, spinnerID, bb) => {
const requestObject = {
text,
imageGenerationProperties: {
size: imageSize,
//quality: "standard", //not supported by dall-e-2
n:1,
},
};
const result = await ea.postOpenAI(requestObject);
console.log({result, json:result?.json});
if(!result?.json?.data?.[0]?.url) {
await errorMessage(spinnerID, result?.json?.error?.message);
return;
}
const spinner = ea.getElement(spinnerID)
spinner.isDeleted = true;
const imageID = await ea.addImage(spinner.x, spinner.y, result.json.data[0].url);
const imageEl = ea.getElement(imageID);
const revisedPrompt = result.json.data[0].revised_prompt;
if(revisedPrompt) {
ea.style.fontSize = 16;
const rectID = ea.addText(imageEl.x+15, imageEl.y + imageEl.height + 50, revisedPrompt, {
width: imageEl.width-30,
textAlign: "center",
textVerticalAlign: "top",
box: true,
})
ea.getElement(rectID).strokeColor = "transparent";
ea.getElement(rectID).backgroundColor = "transparent";
ea.addToGroup(ea.getElements().filter(el=>el.id !== spinnerID).map(el=>el.id));
}
await ea.addElementsToView(false, true, true);
ea.getExcalidrawAPI().setToast({
message: IMAGE_WARNING,
duration: 15000,
closable: true
});
}
const run = async (text) => {
if(!text && !imageDataURL) {
new Notice("No prompt, aborting");
return;
}
const systemPrompt = systemPrompts[agentTask];
const outputType = outputTypes[systemPrompt.type];
const isImageGenRequest = outputType.blocktype === "image";
const isImageEditRequest = systemPrompt.type === "image-edit";
if(isImageEditRequest) {
if(!text) {
new Notice("You must provide a text prompt with instructions for how the image should be modified");
return;
}
if(!imageDataURL || !maskDataURL) {
new Notice("You must provide an image and a mask");
return;
}
}
//place spinner next to selected elements
const bb = ea.getBoundingBox(ea.getViewSelectedElements());
const spinnerID = ea.addEmbeddable(bb.topX+bb.width+100,bb.topY-(720-bb.height)/2,550,720,spinner);
//this block is in an async call using the isEACompleted flag because otherwise during debug Obsidian
//goes black (not freezes, but does not get a new frame for some reason)
//palcing this in an async call solves this issue
//If you know why this is happening and can offer a better solution, please reach out to @zsviczian
let isEACompleted = false;
setTimeout(async()=>{
await ea.addElementsToView(false,true);
ea.clear();
const embeddable = ea.getViewElements().filter(el=>el.id===spinnerID);
ea.copyViewElementsToEAforEditing(embeddable);
const els = ea.getViewSelectedElements();
ea.viewZoomToElements(false, els.concat(embeddable));
isEACompleted = true;
});
if(isImageGenRequest && !systemPrompt.prompt && !isImageEditRequest) {
generateImage(text,spinnerID,bb);
return;
}
const requestObject = isImageEditRequest
? {
...imageDataURL ? {image: imageDataURL} : {},
...(text && text.trim() !== "") ? {text} : {},
imageGenerationProperties: {
size: imageSize,
//quality: "standard", //not supported by dall-e-2
n:1,
mask: maskDataURL,
},
}
: {
...imageDataURL ? {image: imageDataURL} : {},
...(text && text.trim() !== "") ? {text} : {},
systemPrompt: systemPrompt.prompt,
instruction: outputType.instruction,
}
//Get result from GPT
const result = await ea.postOpenAI(requestObject);
console.log({result, json:result?.json});
//checking that EA has completed. Because the postOpenAI call is an async await
//I don't expect EA not to be completed by now. However the devil never sleeps.
//This (the insomnia of the Devil) is why I have a watchdog here as well
let counter = 0
while(!isEACompleted && counter++<10) sleep(50);
if(!isEACompleted) {
await errorMessage(spinnerID, "Unexpected issue with ExcalidrawAutomate");
return;
}
if(isImageEditRequest) {
if(!result?.json?.data?.[0]?.url) {
await errorMessage(spinnerID, result?.json?.error?.message);
return;
}
const spinner = ea.getElement(spinnerID)
spinner.isDeleted = true;
const imageID = await ea.addImage(spinner.x, spinner.y, result.json.data[0].url);
await ea.addElementsToView(false, true, true);
ea.getExcalidrawAPI().setToast({
message: IMAGE_WARNING,
duration: 15000,
closable: true
});
return;
}
if(!result?.json?.hasOwnProperty("choices")) {
await errorMessage(spinnerID, result?.json?.error?.message);
return;
}
//extract codeblock and display result
let content = ea.extractCodeBlocks(result.json.choices[0]?.message?.content)[0]?.data;
if(!content) {
await errorMessage(spinnerID);
return;
}
if(isImageGenRequest) {
generateImage(content,spinnerID,bb);
return;
}
switch(outputType.blocktype) {
case "html":
ea.getElement(spinnerID).link = await ea.convertStringToDataURL(content);
ea.addElementsToView(false,true);
break;
case "svg":
ea.getElement(spinnerID).isDeleted = true;
ea.importSVG(content);
ea.addToGroup(ea.getElements().map(el=>el.id));
if(ea.getViewSelectedElements().length>0) {
ea.targetView.currentPosition = {x: bb.topX+bb.width+100, y: bb.topY};
}
ea.addElementsToView(true, false);
break;
case "mermaid":
if(content.startsWith("mermaid")) {
content = content.replace(/^mermaid/,"").trim();
}
try {
result = await ea.addMermaid(content);
if(typeof result === "string") {
await errorMessage(spinnerID, "Open [More Tools / Mermaid to Excalidraw] to manually fix the received mermaid script<br><br>" + result);
return;
}
} catch (e) {
ea.addText(0,0,content);
}
ea.getElement(spinnerID).isDeleted = true;
ea.targetView.currentPosition = {x: bb.topX+bb.width+100, y: bb.topY-bb.height};
await ea.addElementsToView(true, false);
setMermaidDataToStorage(content);
new Notice("Open More Tools/Mermaid to Excalidraw in the top tools menu to edit the generated diagram",8000);
break;
}
}
// --------------------------------------
// User Interface
// --------------------------------------
let previewDiv;
const fragWithHTML = (html) => createFragment((frag) => (frag.createDiv().innerHTML = html));
const isImageGenerationTask = () => systemPrompts[agentTask].type === "image-gen" || systemPrompts[agentTask].type === "image-edit";
const addPreviewImage = () => {
if(!previewDiv) return;
previewDiv.empty();
previewDiv.createEl("img",{
attr: {
style: `max-width: 100%;max-height: 30vh;`,
src: imageDataURL,
}
});
if(maskDataURL) {
previewDiv.createEl("img",{
attr: {
style: `max-width: 100%;max-height: 30vh;`,
src: maskDataURL,
}
});
}
}
const configModal = new ea.obsidian.Modal(app);
configModal.modalEl.style.width="100%";
configModal.modalEl.style.maxWidth="1000px";
configModal.onOpen = async () => {
const contentEl = configModal.contentEl;
contentEl.createEl("h1", {text: "ExcaliAI"});
let systemPromptTextArea, systemPromptDiv, imageSizeSetting, imageSizeSettingDropdown, helpEl;
new ea.obsidian.Setting(contentEl)
.setName("What would you like to do?")
.addDropdown(dropdown=>{
Object.keys(systemPrompts).forEach(key=>dropdown.addOption(key,key));
dropdown
.setValue(agentTask)
.onChange(async (value) => {
dirty = true;
const prevTask = agentTask;
agentTask = value;
if(
(systemPrompts[prevTask].type === "image-edit" && systemPrompts[value].type !== "image-edit") ||
(systemPrompts[prevTask].type !== "image-edit" && systemPrompts[value].type === "image-edit")
) {
({imageDataURL, maskDataURL} = await generateCanvasDataURL(ea.targetView, systemPrompts[value].type === "image-edit"));
addPreviewImage();
setImageModelAndSizes();
while (imageSizeSettingDropdown.selectEl.options.length > 0) { imageSizeSettingDropdown.selectEl.remove(0); }
validSizes.forEach(size=>imageSizeSettingDropdown.addOption(size,size));
imageSizeSettingDropdown.setValue(imageSize);
}
imageSizeSetting.settingEl.style.display = isImageGenerationTask() ? "" : "none";
const prompt = systemPrompts[value].prompt;
helpEl.innerHTML = `<b>Help: </b>` + systemPrompts[value].help;
if(prompt) {
systemPromptDiv.style.display = "";
systemPromptTextArea.setValue(systemPrompts[value].prompt);
} else {
systemPromptDiv.style.display = "none";
}
});
})
helpEl = contentEl.createEl("p");
helpEl.innerHTML = `<b>Help: </b>` + systemPrompts[agentTask].help;
systemPromptDiv = contentEl.createDiv();
systemPromptDiv.createEl("h4", {text: "Customize System Prompt"});
systemPromptDiv.createEl("span", {text: "Unless you know what you are doing I do not recommend changing the system prompt"})
const systemPromptSetting = new ea.obsidian.Setting(systemPromptDiv)
.addTextArea(text => {
systemPromptTextArea = text;
const prompt = systemPrompts[agentTask].prompt;
text.inputEl.style.minHeight = "10em";
text.inputEl.style.width = "100%";
text.setValue(prompt);
text.onChange(value => {
systemPrompts[value].prompt = value;
});
if(!prompt) systemPromptDiv.style.display = "none";
})
systemPromptSetting.nameEl.style.display = "none";
systemPromptSetting.descEl.style.display = "none";
systemPromptSetting.infoEl.style.display = "none";
contentEl.createEl("h4", {text: "User Prompt"});
const userPromptSetting = new ea.obsidian.Setting(contentEl)
.addTextArea(text => {
text.inputEl.style.minHeight = "10em";
text.inputEl.style.width = "100%";
text.setValue(userPrompt);
text.onChange(value => {
userPrompt = value;
dirty = true;
})
})
userPromptSetting.nameEl.style.display = "none";
userPromptSetting.descEl.style.display = "none";
userPromptSetting.infoEl.style.display = "none";
imageSizeSetting = new ea.obsidian.Setting(contentEl)
.setName("Select image size")
.setDesc(fragWithHTML("<mark>⚠️ Important ⚠️</mark>: " + IMAGE_WARNING))
.addDropdown(dropdown=>{
validSizes.forEach(size=>dropdown.addOption(size,size));
imageSizeSettingDropdown = dropdown;
dropdown
.setValue(imageSize)
.onChange(async (value) => {
dirty = true;
imageSize = value;
if(systemPrompts[agentTask].type === "image-edit") {
({imageDataURL, maskDataURL} = await generateCanvasDataURL(ea.targetView, true));
addPreviewImage();
}
});
})
imageSizeSetting.settingEl.style.display = isImageGenerationTask() ? "" : "none";
if(imageDataURL) {
previewDiv = contentEl.createDiv({
attr: {
style: "text-align: center;",
}
});
addPreviewImage();
} else {
contentEl.createEl("h4", {text: "No elements are selected from your canvas"});
contentEl.createEl("span", {text: "Because there are no Excalidraw elements selected on the canvas, only the text prompt will be sent to OpenAI."});
}
new ea.obsidian.Setting(contentEl)
.addButton(button =>
button
.setButtonText("Run")
.onClick((event)=>{
run(userPrompt); //Obsidian crashes otherwise, likely has to do with requesting an new frame for react
configModal.close();
})
);
}
configModal.onClose = () => {
if(dirty) {
settings["User Prompt"] = userPrompt;
settings["Agent's Task"] = agentTask;
settings["Image Size"] = imageSize;
ea.setScriptSettings(settings);
}
}
configModal.open();
-1
View File
@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><path d="M320 0c17.7 0 32 14.3 32 32V96H472c39.8 0 72 32.2 72 72V440c0 39.8-32.2 72-72 72H168c-39.8 0-72-32.2-72-72V168c0-39.8 32.2-72 72-72H288V32c0-17.7 14.3-32 32-32zM208 384c-8.8 0-16 7.2-16 16s7.2 16 16 16h32c8.8 0 16-7.2 16-16s-7.2-16-16-16H208zm96 0c-8.8 0-16 7.2-16 16s7.2 16 16 16h32c8.8 0 16-7.2 16-16s-7.2-16-16-16H304zm96 0c-8.8 0-16 7.2-16 16s7.2 16 16 16h32c8.8 0 16-7.2 16-16s-7.2-16-16-16H400zM264 256a40 40 0 1 0 -80 0 40 40 0 1 0 80 0zm152 40a40 40 0 1 0 0-80 40 40 0 1 0 0 80zM48 224H64V416H48c-26.5 0-48-21.5-48-48V272c0-26.5 21.5-48 48-48zm544 0c26.5 0 48 21.5 48 48v96c0 26.5-21.5 48-48 48H576V224h16z"/></svg>

Before

Width:  |  Height:  |  Size: 694 B

+53 -10
View File
@@ -94,6 +94,7 @@ const mode = await utils.suggester(
// Exit if user cancels the operation
if(!mode) return;
// Function to permanently delete related files and images
// Function to permanently delete related files and images
const deleteRelatedFilesAndImages = async (sourcePath) => {
// Add delay function for async operations
@@ -101,7 +102,7 @@ const deleteRelatedFilesAndImages = async (sourcePath) => {
// Initialize collections and counters
const cardFiles = new Set();
const batchMarkers = new Set();
const batchMarkers = new Map(); // Map<folderPath, Set<markerFile>>
const sourceFile = app.vault.getAbstractFileByPath(sourcePath);
let deletedCardsCount = 0;
let deletedFoldersCount = 0;
@@ -120,21 +121,25 @@ const deleteRelatedFilesAndImages = async (sourcePath) => {
if (filePath.endsWith('batch-marker.md')) {
const markerFile = app.vault.getAbstractFileByPath(filePath);
if (markerFile) {
batchMarkers.add(markerFile);
// console.log(`Found batch marker: ${filePath}`);
const folderPath = markerFile.path.substring(0, markerFile.path.lastIndexOf('/'));
if (!batchMarkers.has(folderPath)) {
batchMarkers.set(folderPath, new Set());
}
batchMarkers.get(folderPath).add(markerFile);
}
}
}
}
if (batchMarkers.size === 0) {
// console.log('No batch markers found. Please check if the source file path is correct:', sourcePath);
console.log('No batch markers found. Please check if the source file path is correct:', sourcePath);
new Notice("No batch markers found. Please check if the source file path is correct.");
return;
}
// Process each batch marker file to find cards
for (const marker of batchMarkers) {
// console.log(`Processing batch marker: ${marker.path}`);
console.log(`Processing batch marker: ${marker.path}`);
const content = await app.vault.read(marker);
// console.log("Batch marker content:", content);
const lines = content.split('\n');
@@ -156,14 +161,52 @@ const deleteRelatedFilesAndImages = async (sourcePath) => {
cardFiles.add(cardFile);
// console.log(`Found card file through wiki link: ${cardFile.path}`);
} else {
// console.log(`Card file not found for wiki link: ${cardPath}`);
console.log(`Card file not found for wiki link: ${cardPath}`);
}
}
}
}
}
// First delete all card files
if (cardFiles.size === 0) {
new Notice("No cards found for deletion.");
return;
}
// --- Confirmation Dialog ---
const confirmDeletion = await new Promise(resolve => {
const modal = new ea.Modal(app);
modal.onOpen = () => {
const contentEl = modal.contentEl;
contentEl.createEl('h2', { text: 'Confirm Deletion' });
contentEl.createEl('p', { text: `You are about to permanently delete ${cardFiles.size} card file(s).` });
if (batchMarkers.size > 0) {
contentEl.createEl('p', { text: `This action will also attempt to delete ${batchMarkers.size} related folder(s).` });
}
const confirmContainer = contentEl.createDiv({ cls: "excalidraw-dialog-buttons", style: "margin-top: 20px; display: flex; gap: 12px; justify-content: flex-end;" });
// Cancel Button
const cancelButton = new ea.obsidian.ButtonComponent(confirmContainer);
cancelButton.setButtonText("Cancel");
cancelButton.onClick(() => resolve(false));
// Confirm Button
const confirmButton = new ea.obsidian.ButtonComponent(confirmContainer);
confirmButton.setButtonText("Delete Permanently");
confirmButton.setCta();
confirmButton.onClick(() => resolve(true));
};
modal.open();
});
if (!confirmDeletion) {
new Notice("Deletion cancelled.");
return;
}
// Proceed with deletion if confirmed
for (const file of cardFiles) {
try {
if (await app.vault.adapter.exists(file.path)) {
@@ -173,7 +216,7 @@ const deleteRelatedFilesAndImages = async (sourcePath) => {
// Add short delay to allow plugins to respond
await delay(50);
deletedCardsCount++;
// console.log(`Deleted card file: ${file.path}`);
console.log(`Deleted card file: ${file.path}`);
}
} catch (error) {
console.error(`Failed to delete card file: ${file.path}`, error);
@@ -195,14 +238,14 @@ const deleteRelatedFilesAndImages = async (sourcePath) => {
await app.vault.delete(parentFolder, true);
await delay(50);
deletedFoldersCount++;
// console.log(`Deleted folder: ${parentFolder.path}`);
console.log(`Deleted folder: ${parentFolder.path}`);
} catch (error) {
console.error(`Failed to delete folder: ${parentFolder.path}`, error);
}
}
}
new Notice(`Summary:
new Notice(`Deletion Summary:
- Card files deleted: ${deletedCardsCount}
- Image folders deleted: ${deletedFoldersCount}`);
};
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+682 -1
View File
@@ -1 +1,682 @@
[{"fname":"Mindmap connector.md","mtime":1658686599427},{"fname":"Mindmap connector.svg","mtime":1658686599427},{"fname":"Add Connector Point.md","mtime":1735420748564},{"fname":"Add Connector Point.svg","mtime":1645944722000},{"fname":"Add Link to Existing File and Open.md","mtime":1647807918345},{"fname":"Add Link to Existing File and Open.svg","mtime":1645964261000},{"fname":"Add Link to New Page and Open.md","mtime":1654168862138},{"fname":"Add Link to New Page and Open.svg","mtime":1645960639000},{"fname":"Add Next Step in Process.md","mtime":1688304760357},{"fname":"Add Next Step in Process.svg","mtime":1645960639000},{"fname":"Box Each Selected Groups.md","mtime":1645305706000},{"fname":"Box Each Selected Groups.svg","mtime":1645967510000},{"fname":"Box Selected Elements.md","mtime":1645305706000},{"fname":"Box Selected Elements.svg","mtime":1645960639000},{"fname":"Change shape of selected elements.md","mtime":1652701169236},{"fname":"Change shape of selected elements.svg","mtime":1645960775000},{"fname":"Connect elements.md","mtime":1645305706000},{"fname":"Connect elements.svg","mtime":1645960639000},{"fname":"Convert freedraw to line.md","mtime":1645305706000},{"fname":"Convert freedraw to line.svg","mtime":1645960639000},{"fname":"Convert selected text elements to sticky notes.md","mtime":1670169501383},{"fname":"Convert selected text elements to sticky notes.svg","mtime":1645960639000},{"fname":"Convert text to link with folder and alias.md","mtime":1641639819000},{"fname":"Convert text to link with folder and alias.svg","mtime":1645960639000},{"fname":"Copy Selected Element Styles to Global.md","mtime":1642232088000},{"fname":"Copy Selected Element Styles to Global.svg","mtime":1645960639000},{"fname":"Create new markdown file and embed into active drawing.md","mtime":1640866935000},{"fname":"Create new markdown file and embed into active drawing.svg","mtime":1645960639000},{"fname":"Darken background color.md","mtime":1663059051059},{"fname":"Darken background color.svg","mtime":1645960639000},{"fname":"Elbow connectors.md","mtime":1671126911490},{"fname":"Elbow connectors.svg","mtime":1645960639000},{"fname":"Expand rectangles horizontally keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles horizontally keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles horizontally.md","mtime":1644950235000},{"fname":"Expand rectangles horizontally.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles vertically keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically.md","mtime":1658686599427},{"fname":"Expand rectangles vertically.svg","mtime":1645967510000},{"fname":"Fixed horizontal distance between centers.md","mtime":1646743234000},{"fname":"Fixed horizontal distance between centers.svg","mtime":1645960639000},{"fname":"Fixed inner distance.md","mtime":1646743234000},{"fname":"Fixed inner distance.svg","mtime":1645960639000},{"fname":"Fixed spacing.md","mtime":1646743234000},{"fname":"Fixed spacing.svg","mtime":1645967510000},{"fname":"Fixed vertical distance between centers.md","mtime":1646743234000},{"fname":"Fixed vertical distance between centers.svg","mtime":1645967510000},{"fname":"Fixed vertical distance.md","mtime":1646743234000},{"fname":"Fixed vertical distance.svg","mtime":1645967510000},{"fname":"Lighten background color.md","mtime":1663059051059},{"fname":"Lighten background color.svg","mtime":1645959546000},{"fname":"Modify background color opacity.md","mtime":1644924415000},{"fname":"Modify background color opacity.svg","mtime":1645944722000},{"fname":"Normalize Selected Arrows.md","mtime":1670403743278},{"fname":"Normalize Selected Arrows.svg","mtime":1645960639000},{"fname":"Organic Line.md","mtime":1672920172531},{"fname":"Organic Line.svg","mtime":1645964261000},{"fname":"Organic Line Legacy.md","mtime":1690607372668},{"fname":"Organic Line Legacy.svg","mtime":1690607372668},{"fname":"README.md","mtime":1645175700000},{"fname":"Repeat Elements.md","mtime":1663059051059},{"fname":"Repeat Elements.svg","mtime":1645960639000},{"fname":"Reverse arrows.md","mtime":1645305706000},{"fname":"Reverse arrows.svg","mtime":1645960639000},{"fname":"Scribble Helper.md","mtime":1767536720161},{"fname":"Scribble Helper.svg","mtime":1645944722000},{"fname":"Select Elements of Type.md","mtime":1643464321000},{"fname":"Select Elements of Type.svg","mtime":1645960639000},{"fname":"Set Dimensions.md","mtime":1645305706000},{"fname":"Set Dimensions.svg","mtime":1645944722000},{"fname":"Set Font Family.md","mtime":1645305706000},{"fname":"Set Font Family.svg","mtime":1645944722000},{"fname":"Set Grid.md","mtime":1693725826368},{"fname":"Set Grid.svg","mtime":1645960639000},{"fname":"Set Link Alias.md","mtime":1645305706000},{"fname":"Set Link Alias.svg","mtime":1645960639000},{"fname":"Set Stroke Width of Selected Elements.md","mtime":1748189277Line truncated
[
{
"fname": "Mindmap connector.md",
"mtime": 1658686599427
},
{
"fname": "Mindmap connector.svg",
"mtime": 1658686599427
},
{
"fname": "Add Connector Point.md",
"mtime": 1735420748564
},
{
"fname": "Add Connector Point.svg",
"mtime": 1645944722000
},
{
"fname": "Add Link to Existing File and Open.md",
"mtime": 1647807918345
},
{
"fname": "Add Link to Existing File and Open.svg",
"mtime": 1645964261000
},
{
"fname": "Add Link to New Page and Open.md",
"mtime": 1654168862138
},
{
"fname": "Add Link to New Page and Open.svg",
"mtime": 1645960639000
},
{
"fname": "Add Next Step in Process.md",
"mtime": 1688304760357
},
{
"fname": "Add Next Step in Process.svg",
"mtime": 1645960639000
},
{
"fname": "Box Each Selected Groups.md",
"mtime": 1645305706000
},
{
"fname": "Box Each Selected Groups.svg",
"mtime": 1645967510000
},
{
"fname": "Box Selected Elements.md",
"mtime": 1645305706000
},
{
"fname": "Box Selected Elements.svg",
"mtime": 1645960639000
},
{
"fname": "Change shape of selected elements.md",
"mtime": 1652701169236
},
{
"fname": "Change shape of selected elements.svg",
"mtime": 1645960775000
},
{
"fname": "Connect elements.md",
"mtime": 1645305706000
},
{
"fname": "Connect elements.svg",
"mtime": 1645960639000
},
{
"fname": "Convert freedraw to line.md",
"mtime": 1645305706000
},
{
"fname": "Convert freedraw to line.svg",
"mtime": 1645960639000
},
{
"fname": "Convert selected text elements to sticky notes.md",
"mtime": 1670169501383
},
{
"fname": "Convert selected text elements to sticky notes.svg",
"mtime": 1645960639000
},
{
"fname": "Convert text to link with folder and alias.md",
"mtime": 1641639819000
},
{
"fname": "Convert text to link with folder and alias.svg",
"mtime": 1645960639000
},
{
"fname": "Copy Selected Element Styles to Global.md",
"mtime": 1642232088000
},
{
"fname": "Copy Selected Element Styles to Global.svg",
"mtime": 1645960639000
},
{
"fname": "Create new markdown file and embed into active drawing.md",
"mtime": 1640866935000
},
{
"fname": "Create new markdown file and embed into active drawing.svg",
"mtime": 1645960639000
},
{
"fname": "Darken background color.md",
"mtime": 1663059051059
},
{
"fname": "Darken background color.svg",
"mtime": 1645960639000
},
{
"fname": "Elbow connectors.md",
"mtime": 1671126911490
},
{
"fname": "Elbow connectors.svg",
"mtime": 1645960639000
},
{
"fname": "Expand rectangles horizontally keep text centered.md",
"mtime": 1646563692000
},
{
"fname": "Expand rectangles horizontally keep text centered.svg",
"mtime": 1645967510000
},
{
"fname": "Expand rectangles horizontally.md",
"mtime": 1644950235000
},
{
"fname": "Expand rectangles horizontally.svg",
"mtime": 1645967510000
},
{
"fname": "Expand rectangles vertically keep text centered.md",
"mtime": 1646563692000
},
{
"fname": "Expand rectangles vertically keep text centered.svg",
"mtime": 1645967510000
},
{
"fname": "Expand rectangles vertically.md",
"mtime": 1658686599427
},
{
"fname": "Expand rectangles vertically.svg",
"mtime": 1645967510000
},
{
"fname": "Fixed horizontal distance between centers.md",
"mtime": 1646743234000
},
{
"fname": "Fixed horizontal distance between centers.svg",
"mtime": 1645960639000
},
{
"fname": "Fixed inner distance.md",
"mtime": 1646743234000
},
{
"fname": "Fixed inner distance.svg",
"mtime": 1645960639000
},
{
"fname": "Fixed spacing.md",
"mtime": 1646743234000
},
{
"fname": "Fixed spacing.svg",
"mtime": 1645967510000
},
{
"fname": "Fixed vertical distance between centers.md",
"mtime": 1646743234000
},
{
"fname": "Fixed vertical distance between centers.svg",
"mtime": 1645967510000
},
{
"fname": "Fixed vertical distance.md",
"mtime": 1646743234000
},
{
"fname": "Fixed vertical distance.svg",
"mtime": 1645967510000
},
{
"fname": "Lighten background color.md",
"mtime": 1663059051059
},
{
"fname": "Lighten background color.svg",
"mtime": 1645959546000
},
{
"fname": "Modify background color opacity.md",
"mtime": 1644924415000
},
{
"fname": "Modify background color opacity.svg",
"mtime": 1645944722000
},
{
"fname": "Normalize Selected Arrows.md",
"mtime": 1670403743278
},
{
"fname": "Normalize Selected Arrows.svg",
"mtime": 1645960639000
},
{
"fname": "Organic Line.md",
"mtime": 1672920172531
},
{
"fname": "Organic Line.svg",
"mtime": 1645964261000
},
{
"fname": "Organic Line Legacy.md",
"mtime": 1690607372668
},
{
"fname": "Organic Line Legacy.svg",
"mtime": 1690607372668
},
{
"fname": "README.md",
"mtime": 1645175700000
},
{
"fname": "Repeat Elements.md",
"mtime": 1663059051059
},
{
"fname": "Repeat Elements.svg",
"mtime": 1645960639000
},
{
"fname": "Reverse arrows.md",
"mtime": 1645305706000
},
{
"fname": "Reverse arrows.svg",
"mtime": 1645960639000
},
{
"fname": "Scribble Helper.md",
"mtime": 1767536720161
},
{
"fname": "Scribble Helper.svg",
"mtime": 1645944722000
},
{
"fname": "Select Elements of Type.md",
"mtime": 1643464321000
},
{
"fname": "Select Elements of Type.svg",
"mtime": 1645960639000
},
{
"fname": "Set Dimensions.md",
"mtime": 1645305706000
},
{
"fname": "Set Dimensions.svg",
"mtime": 1645944722000
},
{
"fname": "Set Font Family.md",
"mtime": 1645305706000
},
{
"fname": "Set Font Family.svg",
"mtime": 1645944722000
},
{
"fname": "Set Grid.md",
"mtime": 1693725826368
},
{
"fname": "Set Grid.svg",
"mtime": 1645960639000
},
{
"fname": "Set Link Alias.md",
"mtime": 1645305706000
},
{
"fname": "Set Link Alias.svg",
"mtime": 1645960639000
},
{
"fname": "Set Stroke Width of Selected Elements.md",
"mtime": 1748189277103
},
{
"fname": "Set Stroke Width of Selected Elements.svg",
"mtime": 1645960639000
},
{
"fname": "Set Text Alignment.md",
"mtime": 1645305706000
},
{
"fname": "Set Text Alignment.svg",
"mtime": 1645960639000
},
{
"fname": "Set background color of unclosed line object by adding a shadow clone.md",
"mtime": 1681665030892
},
{
"fname": "Set background color of unclosed line object by adding a shadow clone.svg",
"mtime": 1645960639000
},
{
"fname": "Split text by lines.md",
"mtime": 1773076990493
},
{
"fname": "Split text by lines.svg",
"mtime": 1645944722000
},
{
"fname": "Zoom to Fit Selected Elements.md",
"mtime": 1640770602000
},
{
"fname": "Zoom to Fit Selected Elements.svg",
"mtime": 1645960639000
},
{
"fname": "directory-info.json",
"mtime": 1646583437000
},
{
"fname": "index-new.md",
"mtime": 1645986149000
},
{
"fname": "index.md",
"mtime": 1645175700000
},
{
"fname": "Grid Selected Images.md",
"mtime": 1701630797839
},
{
"fname": "Grid Selected Images.svg",
"mtime": 1649614401982
},
{
"fname": "Palette loader.md",
"mtime": 1686511890942
},
{
"fname": "Palette loader.svg",
"mtime": 1649614401982
},
{
"fname": "Rename Image.md",
"mtime": 1663678478785
},
{
"fname": "Rename Image.svg",
"mtime": 1663678478785
},
{
"fname": "Text to Path.md",
"mtime": 1775680971589
},
{
"fname": "Text to Path.svg",
"mtime": 1748193397572
},
{
"fname": "Deconstruct selected elements into new drawing.md",
"mtime": 1771009405621
},
{
"fname": "Deconstruct selected elements into new drawing.svg",
"mtime": 1668541145255
},
{
"fname": "Slideshow.md",
"mtime": 1764868375422
},
{
"fname": "Slideshow.svg",
"mtime": 1670017348333
},
{
"fname": "Auto Layout.md",
"mtime": 1670403743278
},
{
"fname": "Auto Layout.svg",
"mtime": 1670175947081
},
{
"fname": "Uniform size.md",
"mtime": 1670175947081
},
{
"fname": "Uniform size.svg",
"mtime": 1670175947081
},
{
"fname": "Mindmap format.md",
"mtime": 1684484694228
},
{
"fname": "Mindmap format.svg",
"mtime": 1674944958059
},
{
"fname": "Text to Sticky Notes.md",
"mtime": 1678537561724
},
{
"fname": "Text to Sticky Notes.svg",
"mtime": 1678537561724
},
{
"fname": "Folder Note Core - Make Current Drawing a Folder.md",
"mtime": 1678973697470
},
{
"fname": "Folder Note Core - Make Current Drawing a Folder.svg",
"mtime": 1678973697470
},
{
"fname": "Invert colors.md",
"mtime": 1761230648413
},
{
"fname": "Invert colors.svg",
"mtime": 1678973697470
},
{
"fname": "PDF Page Text to Clipboard.md",
"mtime": 1683984041712
},
{
"fname": "PDF Page Text to Clipboard.svg",
"mtime": 1680418321236
},
{
"fname": "Excalidraw Collaboration Frame.md",
"mtime": 1767536720161
},
{
"fname": "Excalidraw Collaboration Frame.svg",
"mtime": 1687881495985
},
{
"fname": "Create DrawIO file.md",
"mtime": 1688243858267
},
{
"fname": "Create DrawIO file.svg",
"mtime": 1688243858267
},
{
"fname": "Ellipse Selected Elements.md",
"mtime": 1690131476331
},
{
"fname": "Ellipse Selected Elements.svg",
"mtime": 1690131476331
},
{
"fname": "Select Similar Elements.md",
"mtime": 1736077716908
},
{
"fname": "Select Similar Elements.svg",
"mtime": 1691270949338
},
{
"fname": "Toggle Grid.md",
"mtime": 1692125382945
},
{
"fname": "Toggle Grid.svg",
"mtime": 1692124753386
},
{
"fname": "Split Ellipse.md",
"mtime": 1747585400113
},
{
"fname": "Split Ellipse.svg",
"mtime": 1693134104356
},
{
"fname": "Text Aura.md",
"mtime": 1693731979540
},
{
"fname": "Text Aura.svg",
"mtime": 1693731979540
},
{
"fname": "Boolean Operations.md",
"mtime": 1748278607255
},
{
"fname": "Boolean Operations.svg",
"mtime": 1695746839537
},
{
"fname": "Concatenate lines.md",
"mtime": 1736073478644
},
{
"fname": "Concatenate lines.svg",
"mtime": 1696175301525
},
{
"fname": "GPT-Draw-a-UI.md",
"mtime": 1703324727900
},
{
"fname": "GPT-Draw-a-UI.svg",
"mtime": 1700511998048
},
{
"fname": "ExcaliAI.md",
"mtime": 1779295681335
},
{
"fname": "ExcaliAI.svg",
"mtime": 1701011028767
},
{
"fname": "Repeat Texts.md",
"mtime": 1701969627758
},
{
"fname": "Repeat Texts.svg",
"mtime": 1701969627758
},
{
"fname": "Relative Font Size Cycle.md",
"mtime": 1701969627758
},
{
"fname": "Relative Font Size Cycle.svg",
"mtime": 1701969627758
},
{
"fname": "Golden Ratio.md",
"mtime": 1725174200469
},
{
"fname": "Golden Ratio.svg",
"mtime": 1702812404286
},
{
"fname": "Crop Vintage Mask.md",
"mtime": 1706565166174
},
{
"fname": "Crop Vintage Mask.svg",
"mtime": 1705836797730
},
{
"fname": "Custom Zoom.md",
"mtime": 1710424027192
},
{
"fname": "Custom Zoom.svg",
"mtime": 1710424027192
},
{
"fname": "Excalidraw Writing Machine.md",
"mtime": 1769960863134
},
{
"fname": "Excalidraw Writing Machine.svg",
"mtime": 1724356709706
},
{
"fname": "Reset LaTeX Size.md",
"mtime": 1725296010813
},
{
"fname": "Reset LaTeX Size.svg",
"mtime": 1725296010813
},
{
"fname": "Shade Master.md",
"mtime": 1779643017184
},
{
"fname": "Shade Master.svg",
"mtime": 1735252821829
},
{
"fname": "Image Occlusion.md",
"mtime": 1779555635845
},
{
"fname": "Image Occlusion.svg",
"mtime": 1735465948353
},
{
"fname": "Full-Year Calendar Generator.md",
"mtime": 1735465948353
},
{
"fname": "Full-Year Calendar Generator.svg",
"mtime": 1735465948353
},
{
"fname": "Printable Layout Wizard.md",
"mtime": 1755349206019
},
{
"fname": "Printable Layout Wizard.svg",
"mtime": 1753293096307
},
{
"fname": "Palm Guard.md",
"mtime": 1773670411373
},
{
"fname": "Palm Guard.svg",
"mtime": 1754718656757
},
{
"fname": "Mindmap Builder.md",
"mtime": 1781460603530
},
{
"fname": "Mindmap Builder.svg",
"mtime": 1766352440627
},
{
"fname": "Linear Calendar Generator.md",
"mtime": 1766386098306
},
{
"fname": "Linear Calendar Generator.svg",
"mtime": 1766386098306
},
{
"fname": "Capture Note.md",
"mtime": 1780986335837
},
{
"fname": "Capture Note.svg",
"mtime": 1780256122182
},
{
"fname": "Color Scheme Manager.md",
"mtime": 1781294249453
},
{
"fname": "Color Scheme Manager.svg",
"mtime": 1780595297314
}
]
+16 -7
View File
@@ -73,6 +73,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/Convert%20freedraw%20to%20line.svg"/></div>|[[#Convert freedraw to line]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Crop%20Vintage%20Mask.svg"/></div>|[[#Crop Vintage Mask]]|
|<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/Capture%20Note.svg"/></div>|[[#Capture Note]]|
## Layout and Organization
**Keywords**: Design, Placement, Arrangement, Structure, Formatting, Alignment
@@ -133,6 +134,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/Change%20shape%20of%20selected%20elements.svg"/></div>|[[#Change shape of selected elements]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Color%20Scheme%20Manager.svg"/></div>|[[#Color Scheme Manager]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Darken%20background%20color.svg"/></div>|[[#Darken background color]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Invert%20colors.svg"/></div>|[[#Invert colors]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Lighten%20background%20color.svg"/></div>|[[#Lighten background color]]|
@@ -153,6 +155,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/Capture%20Note.svg"/></div>|[[#Capture Note]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20Existing%20File%20and%20Open.svg"/></div>|[[#Add Link to Existing File and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20New%20Page%20and%20Open.svg"/></div>|[[#Add Link to New Page and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.svg"/></div>|[[#Convert text to link with folder and alias]]|
@@ -171,7 +174,6 @@ These are the scripts I use most often. I tried to order them by importance, but
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Copy%20Selected%20Element%20Styles%20to%20Global.svg"/></div>|[[#Copy Selected Element Styles to Global]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/ExcaliAI.svg"/></div>|[[#ExcaliAI]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Excalidraw%20Writing%20Machine.svg"/></div>|[[#Excalidraw Writing Machine]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/GPT-Draw-a-UI.svg"/></div>|[[#GPT Draw-a-UI]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Palette%20loader.svg"/></div>|[[#Palette Loader]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Palm%20Guard.svg"/></div>|[[#Palm Guard]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/PDF%20Page%20Text%20to%20Clipboard.svg"/></div>|[[#PDF Page Text to Clipboard]]|
@@ -263,12 +265,25 @@ 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/Box%20Selected%20Elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will add an encapsulating box around the currently selected elements in Excalidraw.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-box-elements.jpg'></td></tr></table>
## Capture Note
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Capture%20Note.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Capture%20Note.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script implements the unified "Capture Note" workflow, allowing users to select or search for note titles, automatically resolve their template and folder rules, and contextually back-embed visual frames or markdown sections.<br><a href="https://www.youtube.com/watch?v=y3sDfH30ApU" target="_blank"><img src ="https://i.ytimg.com/vi/y3sDfH30ApU/maxresdefault.jpg" style="width:560px;"></a></td></tr></table>
## Change shape of selected elements
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Change%20shape%20of%20selected%20elements.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Change%20shape%20of%20selected%20elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script allows you to change the shape and fill style of selected Rectangles, Diamonds, Ellipses, Lines, Arrows and Freedraw.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-change-shape.jpg'></td></tr></table>
## Color Scheme Manager
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Color%20Scheme%20Manager.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/iwanhoogendoorn'>@iwanhoogendoorn</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/Color%20Scheme%20Manager.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Swap the entire Stroke and Background/Fill colour palettes between named, categorized themes (Cloud Providers, Code Editors, Tech Brands, Design Systems, Nature, and more) from a docked side panel. Applying a theme recolours your selection (or sets the active colour) and repaints the native picker — both the quick-pick rows and the extended 3×5 grid with shades. Create your own schemes, import from a flat hex list, a labelled STROKE/FILL text format, or a raw appState colorPalette JSON (paste or .txt/.json file), hand-pick a custom picker, and export the current palette. When the MindMap Builder script is installed, an optional toggle recolours mind maps branch-by-branch. The canvas background is always left white.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/color-scheme-manager.gif' style="width:560px;"></td></tr></table>
## Concatenate lines
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Concatenate%20lines.md
@@ -453,12 +468,6 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/simonperet'>@simonperet</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/Full-Year%20Calendar%20Generator.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Generates a complete calendar for a specified year.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-full-year-calendar-exemple.excalidraw.png'></td></tr></table>
## GPT Draw-a-UI
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/GPT-Draw-a-UI.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/GPT-Draw-a-UI.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script was discontinued in favor of ExcaliAI. Draw a UI and let GPT create the code for you.<br><a href="https://www.youtube.com/watch?v=y3kHl_6Ll4w" target="_blank"><img src ="https://i.ytimg.com/vi/y3kHl_6Ll4w/maxresdefault.jpg" style="width:400px;"></a><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg'></td></tr></table>
## Image Occlusion
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Image%20Occlusion.md
+2 -1
View File
@@ -330,6 +330,7 @@ function slider(contentEl, action, min, max, step, invert) {
}
let debounceColorPicker = true;
let dirty = false;
function renderSidepanel(contentEl) {
contentEl.empty();
@@ -354,7 +355,7 @@ function renderSidepanel(contentEl) {
}
const { width, height } = ea.getExcalidrawAPI().getAppState();
if(allElements.length === 0) {
contentEl.createEl("p", {
text: "Select at least one rectangle, ellipse, diamond, line, arrow, freedraw, text or SVG image element",
-4214
View File
File diff suppressed because it is too large. Load diff
-119
View File
@@ -1,119 +0,0 @@
const { FlatCompat } = require("@eslint/eslintrc");
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const legacyConfig = require("./.eslintrc.json");
module.exports = (async () => {
const { default: obsidianmd } = await import("eslint-plugin-obsidianmd");
const tsRulesOffForJs = Object.fromEntries(
[
"@typescript-eslint/await-thenable",
"@typescript-eslint/ban-ts-comment",
"@typescript-eslint/no-array-constructor",
"@typescript-eslint/no-array-delete",
"@typescript-eslint/no-base-to-string",
"@typescript-eslint/no-deprecated",
"@typescript-eslint/no-duplicate-enum-values",
"@typescript-eslint/no-duplicate-type-constituents",
"@typescript-eslint/no-empty-object-type",
"@typescript-eslint/no-explicit-any",
"@typescript-eslint/no-extra-non-null-assertion",
"@typescript-eslint/no-floating-promises",
"@typescript-eslint/no-for-in-array",
"@typescript-eslint/no-implied-eval",
"@typescript-eslint/no-misused-new",
"@typescript-eslint/no-misused-promises",
"@typescript-eslint/no-namespace",
"@typescript-eslint/no-non-null-asserted-optional-chain",
"@typescript-eslint/no-redundant-type-constituents",
"@typescript-eslint/no-require-imports",
"@typescript-eslint/no-this-alias",
"@typescript-eslint/no-unnecessary-type-assertion",
"@typescript-eslint/no-unnecessary-type-constraint",
"@typescript-eslint/no-unsafe-argument",
"@typescript-eslint/no-unsafe-assignment",
"@typescript-eslint/no-unsafe-call",
"@typescript-eslint/no-unsafe-declaration-merging",
"@typescript-eslint/no-unsafe-enum-comparison",
"@typescript-eslint/no-unsafe-function-type",
"@typescript-eslint/no-unsafe-member-access",
"@typescript-eslint/no-unsafe-return",
"@typescript-eslint/no-unsafe-unary-minus",
"@typescript-eslint/no-unused-expressions",
"@typescript-eslint/no-unused-vars",
"@typescript-eslint/no-wrapper-object-types",
"@typescript-eslint/only-throw-error",
"@typescript-eslint/prefer-as-const",
"@typescript-eslint/prefer-namespace-keyword",
"@typescript-eslint/prefer-promise-reject-errors",
"@typescript-eslint/require-await",
"@typescript-eslint/restrict-plus-operands",
"@typescript-eslint/restrict-template-expressions",
"@typescript-eslint/triple-slash-reference",
"@typescript-eslint/unbound-method",
].map((rule) => [rule, "off"]),
);
const obsidianTypedRulesOffForJs = {
"obsidianmd/no-plugin-as-component": "off",
"obsidianmd/no-view-references-in-plugin": "off",
"obsidianmd/no-unsupported-api": "off",
"obsidianmd/prefer-file-manager-trash-file": "off",
"obsidianmd/prefer-instanceof": "off",
};
return [
{
ignores: [
"lib/**",
"dist/**",
"node_modules/**",
".github/**",
"MathjaxToSVG/**",
"docs/**",
"ea-scripts/**",
"images/**",
"test-data/**",
],
},
...compat.config(legacyConfig),
...obsidianmd.configs.recommended,
{
files: ["**/*.{js,jsx}"],
rules: {
...tsRulesOffForJs,
...obsidianTypedRulesOffForJs,
},
},
{
files: ["**/*.{ts,tsx}"],
languageOptions: {
parser: require("@typescript-eslint/parser"),
parserOptions: {
project: "./tsconfig.json",
tsconfigRootDir: __dirname,
},
},
},
{
files: ["**/*.{ts,tsx,js,jsx}"],
rules: {
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{
args: "after-used",
argsIgnorePattern: "^_",
varsIgnorePattern: "^_",
ignoreRestSiblings: true,
caughtErrors: "all",
caughtErrorsIgnorePattern: "^_",
},
],
"no-useless-escape": "error",
},
},
];
})();
+43
View File
@@ -0,0 +1,43 @@
import tseslint from 'typescript-eslint';
import obsidianmd from 'eslint-plugin-obsidianmd';
import globals from 'globals';
import { globalIgnores } from 'eslint/config';
export default tseslint.config(
globalIgnores([
'node_modules',
'dist',
'esbuild.config.mjs',
'rollup.config.mjs',
'version-bump.mjs',
'versions.json',
'main.js',
'package.json',
'package-lock.json',
'tsconfig.json',
'tsconfig.api.json',
'api',
"scripts",
"ea-scripts",
"docs",
"lib",
"images",
"assets",
]),
{
languageOptions: {
globals: {
...globals.browser,
},
parserOptions: {
projectService: {
allowDefaultProject: ['eslint.config.mts', 'manifest.json'],
},
tsconfigRootDir: import.meta.dirname,
extraFileExtensions: ['.json'],
},
},
},
...obsidianmd.configs.recommended,
);
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 MiB

+11 -9
View File
@@ -1,10 +1,12 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.23.1",
"minAppVersion": "1.5.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
"authorUrl": "https://excalidraw-obsidian.online",
"isDesktopOnly": false
}
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.24.0",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
"authorUrl": "https://excalidraw-obsidian.online",
"fundingUrl": "https://ko-fi.com/zsolt",
"helpUrl": "https://github.com/zsviczian/obsidian-excalidraw-plugin#readme",
"isDesktopOnly": false
}
+3 -3
View File
@@ -1,12 +1,12 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.23.1",
"minAppVersion": "1.5.7",
"version": "2.24.0",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
"authorUrl": "https://excalidraw-obsidian.online",
"fundingUrl": "https://ko-fi.com/zsolt",
"helpUrl": "https://github.com/zsviczian/obsidian-excalidraw-plugin#readme",
"isDesktopOnly": false
}
}
+1471 -935
View File
File diff suppressed because it is too large. Load diff
+22 -17
View File
@@ -8,39 +8,38 @@
"lib/**/*"
],
"scripts": {
"predev": "node scripts/build-mathjax.mjs",
"dev": "cross-env NODE_ENV=development rollup --config rollup.config.mjs",
"prebuild": "node scripts/build-mathjax.mjs",
"build": "cross-env NODE_ENV=production rollup --config rollup.config.mjs",
"prelib": "node scripts/build-mathjax.mjs",
"lib": "cross-env NODE_ENV=lib rollup --config rollup.config.mjs",
"code": "eslint --max-warnings=0 --ext .ts,.tsx ./src",
"code:fix": "eslint --max-warnings=0 --ext .ts,.tsx ./src --fix",
"code:unused": "eslint --max-warnings=0 --ext .ts,.tsx ./src --quiet --format json | node -e \"let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{const r=JSON.parse(d);for(const f of r){for(const m of f.messages||[]){if(m.ruleId==='@typescript-eslint/no-unused-vars'||m.ruleId==='no-unused-vars'){console.log(f.filePath+':'+m.line+':'+m.column+' '+m.ruleId+' '+m.message);}}}})\"",
"code:escape": "eslint --max-warnings=0 --ext .ts,.tsx ./src --quiet --format json | node -e \"let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{const r=JSON.parse(d);for(const f of r){for(const m of f.messages||[]){if(m.ruleId==='no-useless-escape'){console.log(f.filePath+':'+m.line+':'+m.column+' '+m.ruleId+' '+m.message);}}}})\"",
"madge": "madge --circular .",
"build:mathjax": "cd MathjaxToSVG && npm run build",
"build:all": "npm run build:mathjax && npm run build",
"dev:mathjax": "cd MathjaxToSVG && npm run dev",
"dev:all": "npm run dev:mathjax && npm run dev",
"doc": "npm run lib && node scripts/generate-script-library.js",
"mindmap": "node scripts/deploy-mindmap-builder.js"
"mindmap": "node scripts/deploy-mindmap-builder.js",
"lint": "eslint .",
"lint:fix": "npx prettier --write \"src/**/*.{ts,tsx}\" && eslint --max-warnings=0 --ext .ts,.tsx ./src --fix"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"@lezer/lr": "^1.4.10",
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.0-92",
"@zsviczian/excalidraw": "0.18.103",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
"gl-matrix": "^3.4.3",
"mathjax-full": "^3.2.2",
"lz-string": "^1.5.0",
"monkey-around": "^2.3.0",
"nanoid": "^4.0.2",
"nanoid": "^5.1.11",
"opentype.js": "^1.3.4",
"pako": "^2.1.0",
"points-on-path": "^0.2.1",
"polybooljs": "^1.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
@@ -57,8 +56,6 @@
"@codemirror/search": "6.5.11",
"@codemirror/state": "6.5.0",
"@codemirror/view": "6.38.6",
"@eslint/eslintrc": "^3.1.0",
"@excalidraw/eslint-config": "^1.0.3",
"@excalidraw/prettier-config": "^1.0.2",
"@rollup/plugin-babel": "^6.0.3",
"@rollup/plugin-commonjs": "^26.0.1",
@@ -73,26 +70,34 @@
"@types/opentype.js": "^1.3.8",
"@types/react": "^18.2.45",
"@types/react-dom": "^18.2.18",
"@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.27.0",
"eslint": "^9.39.4",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-obsidianmd": "^0.3.0",
"eslint-plugin-prettier": "^5.0.0",
"jiti": "^2.6.1",
"jsesc": "^3.0.2",
"lz-string": "^1.5.0",
"obsidian": "1.12.3",
"obsidian": "1.8.7",
"postcss": "^8.4.31",
"prettier": "^3.0.1",
"rollup": "^4.14.0",
"rollup-plugin-copy": "^3.5.0",
"rollup-plugin-visualizer": "^7.0.1",
"tslib": "^2.8.1",
"typescript": "5.9.3",
"uglify-js": "^3.19.3"
},
"overrides": {
"lodash": "^4.18.1",
"lodash-es": "^4.18.1",
"serialize-javascript": "^7.0.5",
"nanoid": "^5.1.11"
},
"resolutions": {
"@typescript-eslint/typescript-estree": "5.3.0"
"strip-ansi": "^7.0.1"
},
"prettier": "@excalidraw/prettier-config",
"engines": {
+9
View File
@@ -8,3 +8,12 @@ Uses .github/workflows/release.yml
3) Tag and trigger release
git tag 2.23.0-beta-x
git push origin 2.23.0-beta-x
---
When I need to rerun the release:
# 1. Delete the tag from your local repository
git tag -d 2.23.0
# 2. Delete the tag from GitHub
git push origin --delete 2.23.0
+36 -155
View File
@@ -1,4 +1,6 @@
import { nodeResolve } from '@rollup/plugin-node-resolve';
import zlib from 'node:zlib';
import visualizer from 'rollup-plugin-visualizer';
import commonjs from '@rollup/plugin-commonjs';
import replace from "@rollup/plugin-replace";
import terser from "@rollup/plugin-terser";
@@ -6,7 +8,6 @@ import copy from "rollup-plugin-copy";
import typescript from "@rollup/plugin-typescript";
import fs from 'fs';
import path from 'path';
import LZString from 'lz-string';
import postprocess from '@zsviczian/rollup-plugin-postprocess';
import cssnano from 'cssnano';
import jsesc from 'jsesc';
@@ -14,6 +15,12 @@ import { minify } from 'uglify-js';
import json from '@rollup/plugin-json';
import { parseEnv } from 'node:util';
function compressDeflateBase64(code) {
// Compress using Node's native zlib at maximum compression
const compressed = zlib.deflateSync(Buffer.from(code, "utf-8"), { level: 9 });
return compressed.toString("base64");
}
try {
const envContent = fs.readFileSync(path.resolve('.env'), 'utf8');
Object.assign(process.env, parseEnv(envContent));
@@ -48,45 +55,10 @@ const jsxRuntimeShim = `
window['react/jsx-dev-runtime'] = { jsx, jsxs, Fragment, jsxDEV: jsx };
`;
const mathjaxtosvg_pkg = isLib ? "" : fs.readFileSync("./MathjaxToSVG/dist/index.js", "utf8");
// Add non-English locales here to embed them as compressed payloads in main.js.
// When adding a locale file:
// 1) add its code to this list, 2) build once, 3) if build fails because the locale
// contains a new dynamic expression, extend tokenizeLocaleContent below and mirror
// the new token in src/lang/helpers.ts token resolution.
const LANGUAGES = ['ru', 'zh-cn', 'zh-tw', 'es']; // english is loaded by default
const SAFE_URLS_FILE = "./src/constants/safeUrls.ts";
const URL_TOKEN_PREFIX = "__EXD_URL_";
function getSafeUrlKeys() {
try {
const safeUrlsContent = fs.readFileSync(SAFE_URLS_FILE, "utf8");
const urlsObjectMatch = safeUrlsContent.match(/export\s+const\s+URLs\s*=\s*\{([\s\S]*?)\}\s*as\s+const/);
if (!urlsObjectMatch) {
return [];
}
const keys = [];
const keyRegex = /^\s*([A-Z0-9_]+)\s*:/gm;
let match;
while ((match = keyRegex.exec(urlsObjectMatch[1])) !== null) {
keys.push(match[1]);
}
return keys;
} catch {
return [];
}
}
const SAFE_URL_KEYS = getSafeUrlKeys();
const URL_TOKEN_VALUES = Object.fromEntries(
SAFE_URL_KEYS.map((key) => [key, `${URL_TOKEN_PREFIX}${key}__`]),
);
const LANGUAGES = ['ru', 'zh-cn', 'zh-tw', 'es']; //english is not compressed as it is always loaded by default
function trimLastSemicolon(input) {
if (input.endsWith(";")) {
@@ -114,123 +86,12 @@ function minifyCode(code) {
return minified.code;
}
// Build-time placeholders that are resolved at runtime in src/lang/helpers.ts.
// Kept in sync with TOKENS in helpers.ts.
const DEVICE_TOKEN_VALUES = {
IF_DESKTOP_START: "__EXD_IF_DESKTOP__",
IF_DESKTOP_END: "__EXD_END_IF_DESKTOP__",
IF_APPLE_START: "__EXD_IF_APPLE__",
IF_APPLE_ELSE: "__EXD_ELSE_APPLE__",
IF_APPLE_END: "__EXD_END_IF_APPLE__",
// We no longer need DEVTOOLS_SHORTCUT here, the Apple ternary regex catches it naturally.
// Variables mocked in our sandbox evaluation
LABEL_ALT: "__EXD_LABEL_ALT__",
LABEL_CTRL: "__EXD_LABEL_CTRL__",
LABEL_META: "__EXD_LABEL_META__",
LABEL_SHIFT: "__EXD_LABEL_SHIFT__",
FRONTMATTER_LINK_BRACKETS: "__EXD_FRONTMATTER_LINK_BRACKETS__",
FRONTMATTER_LINK_PREFIX: "__EXD_FRONTMATTER_LINK_PREFIX__",
FRONTMATTER_URL_PREFIX: "__EXD_FRONTMATTER_URL_PREFIX__",
CJK_FONTS: "__EXD_CJK_FONTS__",
PLUGIN_VERSION: "__EXD_PLUGIN_VERSION__",
};
function tokenizeLocaleContent(content, deviceTokens = DEVICE_TOKEN_VALUES) {
let tokenized = content;
// 1. Desktop Conditional
// Matches: ${ DEVICE.isDesktop ? `...` : "" }
// Robust against arbitrary spaces, newlines, and empty string quote types ("", '', or ``).
const desktopRegex = /\$\{\s*DEVICE\.isDesktop\s*\?\s*`([\s\S]*?)`\s*:\s*["'`]{2}\s*\}/g;
tokenized = tokenized.replace(desktopRegex, (match, trueBranch) => {
return `${deviceTokens.IF_DESKTOP_START}${trueBranch}${deviceTokens.IF_DESKTOP_END}`;
});
// 2. Apple / MacOS Ternaries
// Matches both: ( DEVICE.isIOS || DEVICE.isMacOS ? "A" : "B" ) AND DEVICE.isMacOS ? "A" : "B"
// Robust against optional parentheses, line breaks, and varying quote types.
const appleTernaryRegex = /(?:\(\s*)?(?:DEVICE\.isIOS\s*\|\|\s*)?DEVICE\.isMacOS\s*\?\s*(["'`])([\s\S]*?)\1\s*:\s*(["'`])([\s\S]*?)\3(?:\sbuildSafeUrl)?/g;
tokenized = tokenized.replace(appleTernaryRegex, (match, quote1, trueBranch, quote2, falseBranch) => {
// Wrap in double quotes so the resulting JS is a valid string literal
return `"${deviceTokens.IF_APPLE_START}${trueBranch}${deviceTokens.IF_APPLE_ELSE}${falseBranch}${deviceTokens.IF_APPLE_END}"`;
});
// 3. URLs constants from safeUrls.ts
// Matches: URLs.SOME_KEY and replaces with a stable token string literal.
const urlConstantRegex = /\bURLs\.([A-Z0-9_]+)\b/g;
tokenized = tokenized.replace(urlConstantRegex, (match, key) => {
const token = URL_TOKEN_VALUES[key];
return token ? `"${token}"` : match;
});
return tokenized;
}
function serializeLocaleToJson(content, deviceTokens = DEVICE_TOKEN_VALUES) {
// Rather than regex-replacing variables, we inject mock variables into the Node sandbox.
// When Node evaluates the file, it will natively resolve ${labelALT()} to the token string,
// perfectly bypassing any linter formatting, ES6 template literal breaks, or comment syntax.
const urlsSandboxObject = Object.entries(URL_TOKEN_VALUES)
.map(([key, token]) => `"${key}": "${token}"`)
.join(",\n ");
const sandboxEnvironment = `
const TAG_AUTOEXPORT = "Autoexport";
const TAG_MDREADINGMODE = "MDReadingMode";
const TAG_PDFEXPORT = "PDFExport";
const PLUGIN_VERSION = "${deviceTokens.PLUGIN_VERSION}";
const CJK_FONTS = "${deviceTokens.CJK_FONTS}";
const labelALT = () => "${deviceTokens.LABEL_ALT}";
const labelCTRL = () => "${deviceTokens.LABEL_CTRL}";
const labelMETA = () => "${deviceTokens.LABEL_META}";
const labelSHIFT = () => "${deviceTokens.LABEL_SHIFT}";
const FRONTMATTER_KEYS = {
"link-brackets": { name: "${deviceTokens.FRONTMATTER_LINK_BRACKETS}" },
"link-prefix": { name: "${deviceTokens.FRONTMATTER_LINK_PREFIX}" },
"url-prefix": { name: "${deviceTokens.FRONTMATTER_URL_PREFIX}" }
};
const URLs = {
${urlsSandboxObject}
};
// Fallback for DEVICE to prevent ReferenceErrors if a conditional regex misses an edge case
const DEVICE = { isDesktop: false, isIOS: false, isMacOS: false };
let x = ${content};
return x;
`;
try {
const locale = new Function(sandboxEnvironment)();
return JSON.stringify(locale);
} catch (err) {
console.error("Error evaluating locale content.");
throw err;
}
}
function compressLanguageFile(lang) {
const inputDir = "./src/lang/locale";
const filePath = `${inputDir}/${lang}.ts`;
let content = fs.readFileSync(filePath, "utf-8");
// Safely extract the default export object, ignoring surrounding types/interfaces
const exportMatch = content.match(/export\s+default\s+([\s\S]+)/);
if (!exportMatch) throw new Error(`Could not find 'export default' in ${filePath}`);
let objectContent = exportMatch[1].trim();
if (objectContent.endsWith(";")) {
objectContent = objectContent.slice(0, -1);
}
const tokenizedContent = tokenizeLocaleContent(objectContent);
const localeJson = serializeLocaleToJson(tokenizedContent);
return LZString.compressToBase64(localeJson);
content = trimLastSemicolon(content.split("export default")[1].trim());
return compressDeflateBase64(minifyCode(`x = ${content};`));
}
const excalidraw_pkg = isLib ? "" : minifyCode(isProd
@@ -243,7 +104,8 @@ const reactdom_pkg = isLib ? "" : minifyCode(isProd
? fs.readFileSync("./node_modules/react-dom/umd/react-dom.production.min.js", "utf8")
: fs.readFileSync("./node_modules/react-dom/umd/react-dom.development.js", "utf8"));
const lzstring_pkg = isLib ? "" : fs.readFileSync("./node_modules/lz-string/libs/lz-string.min.js", "utf8");
const pako_pkg = isLib ? "" : fs.readFileSync("./node_modules/pako/dist/pako.min.js", "utf8");
if (!isLib) {
const excalidraw_styles = isProd
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/styles.production.css", "utf8")
@@ -270,15 +132,28 @@ if (!isLib) {
}
const packageString = isLib
? ""
: ';const INITIAL_TIMESTAMP=Date.now();' + lzstring_pkg +
? ""
: ';const INITIAL_TIMESTAMP=Date.now();\n' +
'const pako = (function() {\n' +
' const module = { exports: {} };\n' +
' const exports = module.exports;\n' +
' ' + pako_pkg + '\n' +
' return module.exports;\n' +
'})();\n' +
'\nlet REACT_PACKAGES = `' +
jsesc(react_pkg + reactdom_pkg + jsxRuntimeShim, { quotes: 'backtick' }) +
'`;\n' +
'const unpackExcalidraw = () => LZString.decompressFromBase64("' + LZString.compressToBase64(excalidraw_pkg) + '");\n' +
// NEW: Fast, mobile-compatible runtime decompression
'const unpackBase64Deflate = (b64) => {\n' +
' const binStr = atob(b64);\n' +
' const len = binStr.length;\n' +
' const bytes = new Uint8Array(len);\n' +
' for (let i = 0; i < len; i++) bytes[i] = binStr.charCodeAt(i);\n' +
' return new TextDecoder().decode(pako.inflate(bytes));\n' +
'};\n' +
'const unpackExcalidraw = () => unpackBase64Deflate("' + compressDeflateBase64(excalidraw_pkg) + '");\n' +
'let {react, reactDOM } = new Function(`${REACT_PACKAGES}; return {react: React, reactDOM: ReactDOM};`)();\n' +
'let excalidrawLib = {};\n' +
'const loadMathjaxToSVG = () => new Function(`${LZString.decompressFromBase64("' + LZString.compressToBase64(mathjaxtosvg_pkg) + '")}; return MathjaxToSVG;`)();\n' +
`const PLUGIN_LANGUAGES = {${LANGUAGES.map(lang => `"${lang}": "${compressLanguageFile(lang)}"`).join(",")}};\n` +
'const PLUGIN_VERSION="' + manifest.version + '";';
@@ -342,6 +217,12 @@ const BUILD_CONFIG = {
(_, 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] ]),
]),
-63
View File
@@ -1,63 +0,0 @@
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { execSync } from 'node:child_process';
const mathjaxDir = path.resolve('MathjaxToSVG');
const distDir = path.join(mathjaxDir, 'dist');
const distFile = path.join(distDir, 'index.js');
const hashFile = path.join(distDir, '.build-hash');
const nodeModulesDir = path.join(mathjaxDir, 'node_modules');
// Recursively generates an MD5 hash of all source files in a directory
function hashDirectory(dir) {
const files = fs.readdirSync(dir, { withFileTypes: true });
const hash = crypto.createHash('md5');
// Sort to ensure consistent hashing across different operating systems
for (const file of files.sort((a, b) => a.name.localeCompare(b.name))) {
// Ignore build outputs, dependencies, and hidden files (like .git, .DS_Store)
if (file.name === 'node_modules' || file.name === 'dist' || file.name.startsWith('.')) {
continue;
}
const fullPath = path.join(dir, file.name);
if (file.isDirectory()) {
hash.update(hashDirectory(fullPath));
} else {
hash.update(fs.readFileSync(fullPath));
}
}
return hash.digest('hex');
}
const currentHash = hashDirectory(mathjaxDir);
let previousHash = '';
if (fs.existsSync(hashFile)) {
previousHash = fs.readFileSync(hashFile, 'utf8');
}
// Rebuild if the output file is missing, or if the source files have changed
if (!fs.existsSync(distFile) || currentHash !== previousHash) {
console.log('🔄 MathjaxToSVG changes detected (or missing build). Rebuilding...');
// Run npm install if node_modules is missing or if we know things changed
if (!fs.existsSync(nodeModulesDir) || currentHash !== previousHash) {
console.log('📦 Installing MathjaxToSVG dependencies...');
execSync('npm install', { stdio: 'inherit', cwd: mathjaxDir });
}
console.log('🔨 Building MathjaxToSVG...');
execSync('npm run build', { stdio: 'inherit', cwd: mathjaxDir });
// Save the new hash for next time
if (!fs.existsSync(distDir)) {
fs.mkdirSync(distDir, { recursive: true });
}
fs.writeFileSync(hashFile, currentHash);
console.log('✅ MathjaxToSVG build complete.\n');
} else {
console.log('⚡ MathjaxToSVG is up to date. Skipping build.\n');
}
+10 -10
View File
@@ -1,6 +1,6 @@
const path = require("path");
const fs = require("fs/promises");
const { minify } = require("uglify-js");
const { minify } = require("terser");
const LZString = require("lz-string");
const CHUNK_SIZE = 256;
@@ -40,8 +40,8 @@ The script balances **automation** (auto-layout, recursive grouping, and contras
const FOOTER = `
const VERSION = "v${new Date().toISOString().slice(2, 10).replace(/-/g, ".")}";
if (!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.21.0")) {
new Notice("Please update the Excalidraw Plugin to version 2.21.0 or higher.");
if (!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.23.4")) {
new Notice("Please update the Excalidraw Plugin to version 2.23.4 or higher.");
return;
}
@@ -62,7 +62,7 @@ const mmbSource = \`
`;
const FOOTER_TAIL = `\`;
const script = ea.decompressFromBase64(mmbSource.replaceAll("\\n", "").trim())
const script = ea.decompressFromBase64(mmbSource.replace(/[\\s\\r\\n]+/g, ""));
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
await new AsyncFunction("ea", "utils", "VERSION", script)(ea, utils, VERSION);
`;
@@ -87,8 +87,8 @@ function wrapAsyncIIFE(body) {
return `(async()=>{\n${body}\n})()`;
}
function minifyCode(source) {
const result = minify(source, {
async function minifyCode(source) {
const result = await minify(source, {
compress: { passes: 3 },
mangle: true,
output: { ascii_only: true }
@@ -102,9 +102,9 @@ function minifyCode(source) {
}
function unwrapAsyncIIFE(minified) {
const match = minified.match(/^\(async\(\)=>\{([\s\S]*)\}\)\(\);?$/);
const match = minified.match(/^\(async\s*\(\)\s*=>\s*\{([\s\S]*)\}\)\(\);?$/);
if (!match) {
throw new Error("Unable to strip async IIFE wrapper from minified output");
throw new Error("Unable to strip async IIFE wrapper from minified output:\n" + minified.substring(0, 100) + "...");
}
return match[1];
}
@@ -121,7 +121,7 @@ async function generate() {
const raw = await fs.readFile(sourcePath, "utf8");
const body = stripHeader(raw).trim();
const wrapped = wrapAsyncIIFE(body);
const minified = minifyCode(wrapped);
const minified = await minifyCode(wrapped);
const unwrapped = unwrapAsyncIIFE(minified);
const compressed = compressBase64(unwrapped);
const formatted = formatCompressed(compressed);
@@ -134,4 +134,4 @@ async function generate() {
generate().catch((err) => {
console.error(err);
process.exitCode = 1;
});
});
+32
View File
@@ -0,0 +1,32 @@
const fs = require('fs');
const { execSync } = require('child_process');
const content = fs.readFileSync('src/lang/locale/en.ts', 'utf8');
const lines = content.split('\n');
const keyRegex = /^\s{2}([A-Z0-9_]+):/;
const keys = [];
for (const line of lines) {
const match = line.match(keyRegex);
if (match) {
keys.push(match[1]);
}
}
if (keys.length === 0) {
console.error('No keys found');
process.exit(1);
}
const unusedKeys = [];
for (const key of keys) {
try {
const cmd = 'rg -w -F "' + key + '" . -g "!src/lang/locale/*.ts" -g "!dist/**" -g "!lib/**" -g "!node_modules/**"';
execSync(cmd, { stdio: 'ignore' });
} catch (e) {
unusedKeys.push(key);
}
}
unusedKeys.sort().forEach(k => console.log(k));
console.log('Total: ' + unusedKeys.length);
+13 -29
View File
@@ -59,6 +59,15 @@ For a reference, follow the implementation pattern used in the "Printable Layout
// 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.
@@ -114,6 +123,8 @@ For a reference, follow the implementation pattern used in the "Printable Layout
* 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.
* **Break the code into helper functions:** Avoid creating large monolithic blocks of code in your scripts. Instead, break your code into smaller, reusable helper functions. This improves readability and maintainability. For example, if you have a block of code that creates a specific type of element with certain styles, consider creating a helper function like \`createStyledRect(x, y, width, height)\` that encapsulates that logic.
* **Separate out constants and language strings to the top of the file:** Avoid hard coded values and strings embedded in the code. Instead the script file should start with a set of constants and language strings. Consistently collect these at the top of the file to make it easier to find and modify them later. This also makes it easier for translators to localize the script by providing a clear section for all user-facing text.
#### **9. Text Element**
* There are three text properties.
@@ -246,9 +257,9 @@ Two files follow. First the template startup script with documenation comments,
const EXCALIDRAW_STARTUP_TEMPLATE = "src/constants/assets/startupScript.md";
const EXCALIDRAW_STARTUP_EXAMPLE = "docs/AITrainingData/ExcalidrawStartupExample.md";
const ADDITIONAL_TYPE_DEFS_FOR_AI_TRAINING = [
/*const ADDITIONAL_TYPE_DEFS_FOR_AI_TRAINING = [
"node_modules/obsidian/obsidian.d.ts",
];
];*/
const TYPE_DEF_WHITELIST = [
"lib/shared/ExcalidrawAutomate.d.ts",
@@ -366,30 +377,6 @@ function buildTypeDefMarkdown() {
return body;
}
/**
* Build additional type defs used only in AI_TRAINING_OUT (e.g. obsidian.d.ts).
*/
function buildAdditionalTypeDefsMarkdown() {
const entries = ADDITIONAL_TYPE_DEFS_FOR_AI_TRAINING.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] Additional type def 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');
@@ -600,7 +587,6 @@ function main() {
const typeDefContent = fs.existsSync(TYPE_DEF_OUT)
? fs.readFileSync(TYPE_DEF_OUT, 'utf8')
: (TYPE_DEF_INTRO + '\n' + buildTypeDefMarkdown());
const additionalTypeDefs = buildAdditionalTypeDefsMarkdown();
const scriptLibContent = fs.existsSync(SCRIPT_LIBRARY_OUT)
? fs.readFileSync(SCRIPT_LIBRARY_OUT, 'utf8')
: '';
@@ -634,8 +620,6 @@ function main() {
'\n---\n\n' +
typeDefContent.trim() +
'\n\n---\n\n' +
additionalTypeDefs +
'\n\n---\n\n' +
excalidrawLibFunctionsSection +
'\n---\n\n' +
scriptLibContent.trim() +
+173 -25
View File
@@ -1,6 +1,166 @@
import { getIcon } from "obsidian";
import { getIcon, sanitizeHTMLToDom } from "obsidian";
import { PenStyle } from "src/types/penTypes";
import React from "react";
import { mainDocument } from "./constants";
import { isInstanceOfSVGSVGElement } from "src/utils/typechecks";
const BLOCKED_SVG_TAGS = new Set([
"script",
"foreignobject",
"iframe",
"object",
"embed",
"link",
"meta",
]);
const UNSAFE_PROTOCOL = /^\s*(?:javascript|vbscript):/i;
const UNSAFE_STYLE_URL =
/url\(\s*['"]?\s*(?:javascript|vbscript|data:text\/html)/i;
const isUnsafeAttribute = (name: string, value: string): boolean => {
const loweredName = name.toLowerCase();
const loweredValue = value.toLowerCase();
if (loweredName.startsWith("on")) {
return true;
}
if (loweredName === "src" || loweredName === "srcdoc") {
return true;
}
if (loweredName === "href" || loweredName === "xlink:href") {
return !value.trim().startsWith("#") && value.trim() !== "";
}
if (UNSAFE_PROTOCOL.test(loweredValue)) {
return true;
}
if (loweredName === "style" && UNSAFE_STYLE_URL.test(loweredValue)) {
return true;
}
return false;
};
const sanitizeSvgTree = (svg: SVGSVGElement) => {
const nodesToRemove: Element[] = [];
const walker = mainDocument.createTreeWalker(svg, NodeFilter.SHOW_ELEMENT);
let current = walker.currentNode as Element;
while (current) {
if (BLOCKED_SVG_TAGS.has(current.tagName.toLowerCase())) {
nodesToRemove.push(current);
} else {
[...current.attributes].forEach((attr) => {
if (isUnsafeAttribute(attr.name, attr.value)) {
current.removeAttribute(attr.name);
}
});
}
current = walker.nextNode() as Element;
}
nodesToRemove.forEach((node) => node.remove());
};
const sanitizeSvgFromString = (svgMarkup: string): SVGSVGElement | null => {
const fragment = sanitizeHTMLToDom(svgMarkup ?? "");
const svg = fragment.querySelector("svg");
if (!isInstanceOfSVGSVGElement(svg)) {
return null;
}
const clone = svg.cloneNode(true) as SVGSVGElement;
sanitizeSvgTree(clone);
return clone;
};
const sanitizeSvgElement = (svg: SVGSVGElement): SVGSVGElement => {
const clone = svg.cloneNode(true) as SVGSVGElement;
sanitizeSvgTree(clone);
return clone;
};
const applyDefaultSvgTheme = (svg: SVGSVGElement) => {
const walker = mainDocument.createTreeWalker(svg, NodeFilter.SHOW_ELEMENT);
let current = walker.currentNode as Element;
while (current) {
current.removeAttribute("stroke");
current.removeAttribute("width");
current.removeAttribute("height");
current = walker.nextNode() as Element;
}
svg.setAttribute("stroke", "var(--icon-fill-color)");
svg.setAttribute("color", "var(--icon-fill-color)");
svg.setAttribute("fill", "var(--icon-fill-color)");
svg.setAttribute("stroke-width", "6");
};
const cssTextToReactStyle = (
cssText: string,
): React.CSSProperties | undefined => {
const style: Record<string, string> = {};
cssText
.split(";")
.map((entry) => entry.trim())
.filter(Boolean)
.forEach((entry) => {
const splitIndex = entry.indexOf(":");
if (splitIndex === -1) {
return;
}
const key = entry.slice(0, splitIndex).trim();
const value = entry.slice(splitIndex + 1).trim();
if (!key || !value) {
return;
}
style[toReactAttributeName(key)] = value;
});
return Object.keys(style).length ? style : undefined;
};
const domNodeToReact = (
node: ChildNode,
key: string,
): React.ReactNode | null => {
if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent ?? "";
return text.length > 0 ? text : null;
}
if (node.nodeType !== Node.ELEMENT_NODE) {
return null;
}
const element = node as Element;
const props: Record<string, unknown> = { key };
[...element.attributes].forEach((attr) => {
const reactAttribute = toReactAttributeName(attr.name);
if (reactAttribute === "style") {
const style = cssTextToReactStyle(attr.value);
if (style) {
props.style = style;
}
return;
}
props[reactAttribute] = attr.value;
});
const children = [...element.childNodes]
.map((child, index) => domNodeToReact(child, `${key}-${index}`))
.filter((child): child is React.ReactNode => child !== null);
return React.createElement(element.tagName.toLowerCase(), props, ...children);
};
const svgElementToReact = (svg: SVGSVGElement): React.ReactElement => {
return domNodeToReact(svg, "svg") as React.ReactElement;
};
const toReactAttributeName = (attributeName: string) => {
if (attributeName === "class") {
@@ -15,24 +175,14 @@ const toReactAttributeName = (attributeName: string) => {
);
};
const getIconAttributes = (icon: SVGSVGElement) =>
[...icon.attributes].reduce<Record<string, string>>((attributes, attr) => {
attributes[toReactAttributeName(attr.nodeName)] = attr.nodeValue;
return attributes;
}, {});
export const getIconAsJSX = (iconId: string) => {
const icon = getIcon(iconId);
if (!icon) {
return <svg className="svg-icon excalidraw-icon-missing" />;
}
return (
<svg
{...getIconAttributes(icon as SVGSVGElement)}
dangerouslySetInnerHTML={{ __html: icon.innerHTML }}
/>
);
const sanitizedIcon = sanitizeSvgElement(icon);
return svgElementToReact(sanitizedIcon);
};
export const ICONS = {
@@ -877,7 +1027,7 @@ export const penIcon = (pen: PenStyle) => {
stroke={pen.strokeColor ?? "var(--icon-fill-color)"}
style={pen.strokeColor ? { filter: "var(--theme-filter)" } : {}}
>
<path d="m-.58 95.628.22-.89q.22-.89.49-2.44.26-1.54.77-3.35t1.31-3.43q.79-1.61.2-.26-.6 1.34-.03-.14.58-1.49 1.54-2.97.96-1.49 2.54-3.18 1.59-1.68 3.46-2.96 1.86-1.27.81-.54-1.04 .73 .6 -.46 1.64-1.19 2.8-1.81 1.16-.63.16-.08-.99.54 1.21-.5 2.2-1.03 1.11-.58-1.1.45-.03-.07 1.06-.53 2.32-.82 1.26-.3 2.91-.52 1.64-.23 3.05-.18 1.4.05 2.5.12 1.09.07 2.25.24 1.16.17 2.3.49 1.15.32 2.11.78.96.47 2.21 1.01 1.25.55 2.37 1.04t2.34.89q1.22.4 2.5.65 1.29.25 2.44.33 1.16.08 2.35.17 1.18.08 2.26-.1 1.08-.19 2-1.1.92-.91 1.25-1.93.32-1.02.38-2.15t.57.21q.51 1.34-.03-.02-.55-1.37-.96-2.83-.41-1.45.5-.67.92.79-.03-.06-.95-.85-1.52-1.8-.57-.94-1.5-1.52-.93-.57-1.94-1.22-1.01-.65-1.97-1.88-.96-1.22-1.44-2.54-.49-1.32-.65-2.57-.17-1.24-.11-2.35.06-1.11.31-2.91.24-1.79.76-2.77.51-.97 1.29-1.8.77-.84 1.64-1.55.88-.72 1.9-1.33 1.03-.61 2.43-1.15 1.41-.55 2.69-.92 1.29-.37 2.81-.68 1.53-.31 2.83-.58 1.31-.27 2.78-.47 1.47-.2 2.58-.49 1.12-.28 2.19-.58 1.08-.31 2.13-.73 1.05-.42 2.44-1.32 1.39-.9 2.68-1.85 1.3-.95 2.25-1.87.95-.91 2.06-2 1.11-1.09 1.92-1.93.82-.84 1.54-1.82.71-.98 1.4-1.88.69-.9 1.38-1.96.69-1.07 1.25-2.04.55-.97 1.21-1.94.65-.96 1.35-1.79.69-.83 1.46-1.74.77-.9 1.66-1.73.89-.84 2.72-2.31 1.84-1.48 1.84-1.47v.01l-1.1 1.03q-1.1 1.02-1.77 1.92-.68.9-1.39 1.85-.71.96-1.41 1.91-.7.96-1.19 1.92-.48.95-.95 1.92-.46.96-.9 1.95-.43.99-1.02 2.16-.59 1.17-1.17 2.15-.58.97-1.23 2.13t-1.29 2.02q-.64.86-1.3 1.73-.66.88-1.42 1.78-.75.9-1.72 2.03-.97 1.14-1.81 1.89-.85.75-1.98 1.71-1.14.96-2.05 1.61-.91.64-2.42 1.38-1.51.73-2.71 1.21t-2.49.92q-1.3.44-2.35.69-1.06.24-2.1.59-1.03.34-2.06.74-1.03.4-2.29.94-1.26.54-2.27 1.11-1.01.58-1.57 1.57-.56.99-.81 2.06-.25 1.08.56 2.02.8.94-.21-.02-1.02-.96-.01-.48 1 .49 1.87 1.25.87.77 0 0-.88-.77.46-.01 1.34.75 2.6 1.68 1.26.94 2.08 2.03.81 1.09.01.27-.8-.82.3.26 1.11 1.08 1.71 2.1.61 1.02 1.21 2.25.6 1.24.92 2.36.32 1.12-.16.13-.49-.98.02.36.51 1.35.71 2.69.2 1.34.24 2.46.03 1.12-.09 2.42-.13 1.29-.72 3.21-.6 1.92-1.4 3.49-.81 1.58-1.77 2.83-.96 1.24-2.88 2.72-1.92 1.48-2.95 1.85-1.04.36-2.47.76-1.44.41-3.33.72-1.89.32-3.37.41-1.48.09-2.63.15-1.15.05-2.74-.06-1.59-.1-2.8-.29-1.2-.19-3.2-.63-1.99-.45-3.63-.92-1.63-.48-3.28-.79-1.65-.31-2.76-.2-1.11.1-2.21.42-1.11.32.39-.29 1.49-.6-.12.21-1.61.8-.39.19 1.21-.61.29.13-.92.74-1.83 1.34-.92.61.15-.19t.3-.05q-.77.75-1.58 1.57-.81.82.01-.18.82-1 .24.23t-.72 2.72q-.15 1.48-.08 2.4.07.91-.19 2.16-.26 1.26-.81 2.41-.55 1.16-1.36 2.15t-1.84 1.75q-1.03.77-2.21 1.27t-2.44.7q-1.27.2-2.53.1-1.28-.11-2.49-.52-1.22-.41-2.3-1.1-1.08-.68-1.96-1.61-.89-.92-1.52-2.04-.64-1.11-.99-2.34-.36-1.23-.41-2.51l-.04-1.27Z" />
<path d="m-.58 95.628.22-.89q.22-.89.49-2.44.26-1.54.77-3.35t1.31-3.43q.79-1.61.2-.26-.6 1.34-.03-.14.58-1.49 1.54-2.97.96-1.49 2.54-3.18 1.59-1.68 3.46-2.96 1.86-1.27.81-.54-1.04 .73 .6 -.46 1.64-1.19 2.8-1.81 1.16-.63.16-.08-.99.54 1.21-.5 2.2-1.03 1.11-.58-1.1.45-.03-.07 1.06-.53 2.32-.82 1.26-.3 2.91-.52 1.64-.23 3.05-.18 1.4.05 2.5.12 1.09.07 2.25.24 1.16.17 2.3.49 1.15.32 2.11 0.78 .96.47 2.21 1.01 1.25.55 2.37 1.04t2.34.89q1.22.4 2.5.65 1.29.25 2.44.33 1.16.08 2.35.17 1.18.08 2.26-.1 1.08-.19 2-1.1.92-.91 1.25-1.93.32-1.02.38-2.15t.57.21q.51 1.34-.03-.02-.55-1.37-.96-2.83-.41-1.45.5-.67.92.79-.03-.06-.95-.85-1.52-1.8-.57-.94-1.5-1.52-.93-.57-1.94-1.22-1.01-.65-1.97-1.88-.96-1.22-1.44-2.54-.49-1.32-.65-2.57-.17-1.24-.11-2.35.06-1.11.31-2.91.24-1.79.76-2.77.51-.97 1.29-1.8.77-.84 1.64-1.55.88-.72 1.9-1.33 1.03-.61 2.43-1.15 1.41-.55 2.69-.92 1.29-.37 2.81-.68 1.53-.31 2.83-.58 1.31-.27 2.78-.47 1.47-.2 2.58-.49 1.12-.28 2.19-.58 1.08-.31 2.13-.73 1.05-.42 2.44-1.32 1.39-.9 2.68-1.85 1.3-.95 2.25-1.87.95-.91 2.06-2 1.11-1.09 1.92-1.93.82-.84 1.54-1.82.71-.98 1.4-1.88.69-.9 1.38-1.96.69-1.07 1.25-2.04.55-.97 1.21-1.94.65-.96 1.35-1.79.69-.83 1.46-1.74.77-.9 1.66-1.73.89-.84 2.72-2.31 1.84-1.48 1.84-1.47v.01l-1.1 1.03q-1.1 1.02-1.77 1.92-.68.9-1.39 1.85-.71.96-1.41 1.91-.7.96-1.19 1.92-.48.95-.95 1.92-.46.96-.9 1.95-.43.99-1.02 2.16-.59 1.17-1.17 2.15-.58.97-1.23 2.13t-1.29 2.02q-.64.86-1.3 1.73-.66.88-1.42 1.78-.75.9-1.72 2.03-.97 1.14-1.81 1.89-.85.75-1.98 1.71-1.14.96-2.05 1.61-.91.64-2.42 1.38-1.51.73-2.71 1.21t-2.49.92q-1.3.44-2.35.69-1.06.24-2.1.59-1.03.34-2.06.74-1.03.4-2.29.94-1.26.54-2.27 1.11-1.01.58-1.57 1.57-.56.99-.81 2.06-.25 1.08.56 2.02.8.94-.21-.02-1.02-.96-.01-.48 1 .49 1.87 1.25.87.77 0 0-.88-.77.46-.01 1.34.75 2.6 1.68 1.26.94 2.08 2.03.81 1.09.01.27-.8-.82.3.26 1.11 1.08 1.71 2.1.61 1.02 1.21 2.25.6 1.24.92 2.36.32 1.12-.16.13-.49-.98.02.36.51 1.35.71 2.69.2 1.34.24 2.46.03 1.12-.09 2.42-.13 1.29-.72 3.21-.6 1.92-1.4 3.49-.81 1.58-1.77 2.83-.96 1.24-2.88 2.72-1.92 1.48-2.95 1.85-1.04.36-2.47.76-1.44.41-3.33.72-1.89.32-3.37.41-1.48.09-2.63.15-1.15.05-2.74-.06-1.59-.1-2.8-.29-1.2-.19-3.2-.63-1.99-.45-3.63-.92-1.63-.48-3.28-.79-1.65-.31-2.76-.2-1.11.1-2.21.42-1.11.32.39-.29 1.49-.6-.12.21-1.61.8-.39.19 1.21-.61.29.13-.92.74-1.83 1.34-.92.61.15-.19t.3-.05q-.77.75-1.58 1.57-.81.82.01-.18.82-1 .24.23t-.72 2.72q-.15 1.48-.08 2.4.07.91-.19 2.16-.26 1.26-.81 2.41-.55 1.16-1.36 2.15t-1.84 1.75q-1.03.77-2.21 1.27t-2.44.7q-1.27.2-2.53.1-1.28-.11-2.49-.52-1.22-.41-2.3-1.1-1.08-.68-1.96-1.61-.89-.92-1.52-2.04-.64-1.11-.99-2.34-.36-1.23-.41-2.51l-.04-1.27Z" />
</svg>
);
case "thin-thick-thin":
@@ -912,19 +1062,17 @@ export const penIcon = (pen: PenStyle) => {
};
export const stringToSVG = (svg: string) => {
if (svg.match(/class=["'][^"']*(lucide|skip)[^"']*["']/)) {
return <div dangerouslySetInnerHTML={{ __html: svg }}></div>;
const sanitizedSvg = sanitizeSvgFromString(svg);
if (!sanitizedSvg) {
return <svg className="svg-icon excalidraw-icon-missing" />;
}
svg = svg
.replace(/stroke\s*=\s*['"][^"']*['"]/g, "")
.replace(/[^-]width\s*=\s*['"][^"']*['"]/g, "")
.replace(/[^-]height\s*=\s*['"][^"']*['"]/g, "")
.replace(
"<svg ",
`<svg style="stroke:var(--icon-fill-color);color:var(--icon-fill-color);fill:var(--icon-fill-color);stroke-width:6;" `,
);
return <div dangerouslySetInnerHTML={{ __html: svg }}></div>;
const className = sanitizedSvg.getAttribute("class") ?? "";
if (!/(?:^|\s)(?:lucide|skip)(?:\s|-|$)/.test(className)) {
applyDefaultSvgTheme(sanitizedSvg);
}
return <div>{svgElementToReact(sanitizedSvg)}</div>;
};
export const LogoWrapper = ({ children }: { children: React.ReactNode }) => {
+101 -37
View File
@@ -5,9 +5,12 @@ import { DeviceType } from "src/types/types";
import { errorHandler } from "../utils/ErrorHandler";
import { getLanguage } from "obsidian";
import { URLs } from "./safeUrls";
import { setStyle } from "src/utils/styleUtils";
//This is only for backward compatibility because an early version of obsidian included an encoding to avoid fantom links from littering Obsidian graph view
declare const PLUGIN_VERSION: string;
export let EXCALIDRAW_PLUGIN: ExcalidrawPlugin = null;
// eslint-disable-next-line obsidianmd/prefer-active-doc
export const mainDocument = document; //signals deliberate use of main document instead of activeDocument
export const setExcalidrawPlugin = (plugin: ExcalidrawPlugin) => {
EXCALIDRAW_PLUGIN = plugin;
};
@@ -173,7 +176,9 @@ export function updateExcalidrawLib() {
getDefaultColorPalette,
} = excalidrawLib);
} catch (error) {
errorHandler.handleError(error, "updateExcalidrawLib", true);
if (error instanceof Error || typeof error === "string") {
errorHandler.handleError(error, "updateExcalidrawLib", true);
}
// Don't throw here - we'll try to continue with potentially stale functions
// but at least we won't crash
}
@@ -188,19 +193,20 @@ export function JSON_parse<T>(x: string): T {
export const DEVICE: DeviceType = {
isDesktop:
!document.body.hasClass("is-tablet") &&
!document.body.hasClass("is-mobile"),
isPhone: document.body.hasClass("is-phone"),
isTablet: document.body.hasClass("is-tablet"),
isMobile: document.body.hasClass("is-mobile"), //running Obsidian Mobile, need to also check isTablet
!mainDocument.body.hasClass("is-tablet") &&
!mainDocument.body.hasClass("is-mobile"),
isPhone: mainDocument.body.hasClass("is-phone"),
isTablet: mainDocument.body.hasClass("is-tablet"),
isMobile: mainDocument.body.hasClass("is-mobile"), //running Obsidian Mobile, need to also check isTablet
isLinux:
document.body.hasClass("mod-linux") &&
!document.body.hasClass("is-android"),
mainDocument.body.hasClass("mod-linux") &&
!mainDocument.body.hasClass("is-android"),
isMacOS:
document.body.hasClass("mod-macos") && !document.body.hasClass("is-ios"),
isWindows: document.body.hasClass("mod-windows"),
isIOS: document.body.hasClass("is-ios"),
isAndroid: document.body.hasClass("is-android"),
mainDocument.body.hasClass("mod-macos") &&
!mainDocument.body.hasClass("is-ios"),
isWindows: mainDocument.body.hasClass("mod-windows"),
isIOS: mainDocument.body.hasClass("is-ios"),
isAndroid: mainDocument.body.hasClass("is-android"),
};
export let ROOTELEMENTSIZE: number = 16;
@@ -209,13 +215,13 @@ export function setRootElementSize(size?: number) {
ROOTELEMENTSIZE = size;
return;
}
const tempElement = document.createElement("div");
tempElement.style.fontSize = "1rem";
const tempElement = mainDocument.createElement("div");
setStyle(tempElement, { fontSize: "1rem" });
tempElement.hidden = true;
document.body.appendChild(tempElement);
mainDocument.body.appendChild(tempElement);
const computedStyle = getComputedStyle(tempElement);
const pixelSize = parseFloat(computedStyle.fontSize);
document.body.removeChild(tempElement);
mainDocument.body.removeChild(tempElement);
return pixelSize;
}
@@ -301,53 +307,111 @@ export const AUDIO_TYPES = [
];
export const CODE_TYPES = ["json", "css", "js"];
export const FRONTMATTER_KEYS: {
[key: string]: { name: string; type: string; depricated?: boolean };
} = {
plugin: { name: "excalidraw-plugin", type: "text" },
export const FRONTMATTER_KEYS = {
plugin: { name: "excalidraw-plugin", type: "text", depricated: false },
"export-transparent": {
name: "excalidraw-export-transparent",
type: "checkbox",
depricated: false,
},
mask: { name: "excalidraw-mask", type: "checkbox", depricated: false },
"export-dark": {
name: "excalidraw-export-dark",
type: "checkbox",
depricated: false,
},
mask: { name: "excalidraw-mask", type: "checkbox" },
"export-dark": { name: "excalidraw-export-dark", type: "checkbox" },
"export-svgpadding": {
name: "excalidraw-export-svgpadding",
type: "number",
depricated: true,
},
"export-padding": { name: "excalidraw-export-padding", type: "number" },
"export-pngscale": { name: "excalidraw-export-pngscale", type: "number" },
"export-padding": {
name: "excalidraw-export-padding",
type: "number",
depricated: false,
},
"export-pngscale": {
name: "excalidraw-export-pngscale",
type: "number",
depricated: false,
},
"export-embed-scene": {
name: "excalidraw-export-embed-scene",
type: "checkbox",
depricated: false,
},
"export-internal-links": {
name: "excalidraw-export-internal-links",
type: "checkbox",
depricated: false,
},
"link-prefix": {
name: "excalidraw-link-prefix",
type: "text",
depricated: false,
},
"url-prefix": {
name: "excalidraw-url-prefix",
type: "text",
depricated: false,
},
"link-brackets": {
name: "excalidraw-link-brackets",
type: "checkbox",
depricated: false,
},
"onload-script": {
name: "excalidraw-onload-script",
type: "text",
depricated: false,
},
"link-prefix": { name: "excalidraw-link-prefix", type: "text" },
"url-prefix": { name: "excalidraw-url-prefix", type: "text" },
"link-brackets": { name: "excalidraw-link-brackets", type: "checkbox" },
"onload-script": { name: "excalidraw-onload-script", type: "text" },
"linkbutton-opacity": {
name: "excalidraw-linkbutton-opacity",
type: "number",
depricated: false,
},
"default-mode": {
name: "excalidraw-default-mode",
type: "text",
depricated: false,
},
font: { name: "excalidraw-font", type: "text", depricated: false },
"font-color": {
name: "excalidraw-font-color",
type: "text",
depricated: false,
},
"border-color": {
name: "excalidraw-border-color",
type: "text",
depricated: false,
},
"md-css": { name: "excalidraw-css", type: "text", depricated: false },
autoexport: {
name: "excalidraw-autoexport",
type: "text",
depricated: false,
},
"default-mode": { name: "excalidraw-default-mode", type: "text" },
font: { name: "excalidraw-font", type: "text" },
"font-color": { name: "excalidraw-font-color", type: "text" },
"border-color": { name: "excalidraw-border-color", type: "text" },
"md-css": { name: "excalidraw-css", type: "text" },
autoexport: { name: "excalidraw-autoexport", type: "text" },
"iframe-theme": {
name: "excalidraw-iframe-theme",
type: "text",
depricated: true,
},
"embeddable-theme": { name: "excalidraw-embeddable-theme", type: "text" },
"open-as-markdown": { name: "excalidraw-open-md", type: "checkbox" },
"embed-as-markdown": { name: "excalidraw-embed-md", type: "checkbox" },
"embeddable-theme": {
name: "excalidraw-embeddable-theme",
type: "text",
depricated: false,
},
"open-as-markdown": {
name: "excalidraw-open-md",
type: "checkbox",
depricated: false,
},
"embed-as-markdown": {
name: "excalidraw-embed-md",
type: "checkbox",
depricated: false,
},
};
export const CaptureUpdateAction = {
+8 -2
View File
@@ -1,4 +1,5 @@
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import { EXCALIDRAW_PLUGIN } from "./constants";
type JsonValue =
| string
@@ -846,7 +847,12 @@ export const emptyDrawingElements: SerializedExcalidrawElement[] = [
},
];
export const getEmptyDrawingElementsRuntime = (): ExcalidrawElement[] =>
emptyDrawingElements.map(
export const getEmptyDrawingElementsRuntime = (): ExcalidrawElement[] => {
const plugin = EXCALIDRAW_PLUGIN;
if (plugin?.settings?.embedPlaceholderImage === false) {
return [];
}
return emptyDrawingElements.map(
(element) => element as SerializedExcalidrawElement & ExcalidrawElement,
);
};
+87 -584
View File
@@ -51,779 +51,277 @@ const defineUrl = (url: string, purpose: string) => ({ url, purpose });
export const URL_REGISTRY = {
RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON:
defineUrl(
buildSafeUrl(
["raw", "githubusercontent", "com"],
[
"zsviczian",
"obsidian-excalidraw-plugin",
"master",
"ea-scripts",
"directory-info.json",
],
),
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/directory-info.json",
UrlPurpose.APP_LOGIC,
),
API_GITHUB_COM_REPOS_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES: defineUrl(
"https://api.github.com/repos/zsviczian/obsidian-excalidraw-plugin/releases?per_page=15&page=1",
UrlPurpose.APP_LOGIC,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues"],
),
"https://github.com/zsviczian/obsidian-excalidraw-plugin/issues",
UrlPurpose.DOCS,
),
API_OPENAI_COM_V1: defineUrl(
buildSafeUrl(["api", "openai", "com"], ["v1"]),
UrlPurpose.AI_API,
),
API_OPENAI_COM_V1: defineUrl("https://api.openai.com/v1", UrlPurpose.AI_API),
API_ANTHROPIC_COM_V1: defineUrl(
buildSafeUrl(["api", "anthropic", "com"], ["v1"]),
"https://api.anthropic.com/v1",
UrlPurpose.AI_API,
),
GENERATIVELANGUAGE_GOOGLEAPIS_COM_V1BETA: defineUrl(
buildSafeUrl(["generativelanguage", "googleapis", "com"], ["v1beta"]),
UrlPurpose.AI_API,
),
API_X_AI_V1: defineUrl(
buildSafeUrl(["api", "x", "ai"], ["v1"]),
"https://generativelanguage.googleapis.com/v1beta",
UrlPurpose.AI_API,
),
API_X_AI_V1: defineUrl("https://api.x.ai/v1", UrlPurpose.AI_API),
API_OPENAI_COM_V1_CHAT_COMPLETIONS: defineUrl(
buildSafeUrl(["api", "openai", "com"], ["v1", "chat", "completions"]),
"https://api.openai.com/v1/chat/completions",
UrlPurpose.AI_API,
),
API_OPENAI_COM_V1_IMAGES_GENERATIONS: defineUrl(
buildSafeUrl(["api", "openai", "com"], ["v1", "images", "generations"]),
"https://api.openai.com/v1/images/generations",
UrlPurpose.AI_API,
),
API_OPENAI_COM_V1_IMAGES_EDITS: defineUrl(
buildSafeUrl(["api", "openai", "com"], ["v1", "images", "edits"]),
"https://api.openai.com/v1/images/edits",
UrlPurpose.AI_API,
),
API_OPENAI_COM_V1_IMAGES_VARIATIONS: defineUrl(
buildSafeUrl(["api", "openai", "com"], ["v1", "images", "variations"]),
"https://api.openai.com/v1/images/variations",
UrlPurpose.AI_API,
),
NOTEBOOKLM_GOOGLE_COM_NOTEBOOK_42D76A2F_C11D_4002_9286_1683C43D0AB0:
defineUrl(
buildSafeUrl(
["notebooklm", "google", "com"],
["notebook", "42d76a2f-c11d-4002-9286-1683c43d0ab0"],
),
"https://notebooklm.google.com/notebook/42d76a2f-c11d-4002-9286-1683c43d0ab0",
UrlPurpose.DOCS,
),
COMMUNITY_SKETCH_YOUR_MIND_COM_EM: defineUrl(
buildSafeUrl(["community", "sketch-your-mind", "com"], ["em"]),
UrlPurpose.SUPPORT,
),
KO_FI_COM_ZSOLT: defineUrl(
buildSafeUrl(["ko-fi", "com"], ["zsolt"]),
"https://community.sketch-your-mind.com/em",
UrlPurpose.SUPPORT,
),
KO_FI_COM_ZSOLT: defineUrl("https://ko-fi.com/zsolt", UrlPurpose.SUPPORT),
CDN_KO_FI_COM_CDN_KOFI3_PNG: defineUrl(
buildSafeUrl(["cdn", "ko-fi", "com"], ["cdn", "kofi3.png?v=3"]),
"https://cdn.ko-fi.com/cdn/kofi3.png?v=3",
UrlPurpose.SUPPORT,
),
COMMUNITY_SKETCH_YOUR_MIND_COM_WIKI: defineUrl(
buildSafeUrl(["community", "sketch-your-mind", "com"], ["wiki"]),
"https://community.sketch-your-mind.com/wiki",
UrlPurpose.SUPPORT,
),
WWW_YOUTUBE_COM_VISUALPKM: defineUrl(
buildSafeUrl(["www", "youtube", "com"], ["@visualPKM"]),
"https://www.youtube.com/@visualPKM",
UrlPurpose.SUPPORT,
),
COMMUNITY_SKETCH_YOUR_MIND_COM_EE: defineUrl(
buildSafeUrl(["community", "sketch-your-mind", "com"], ["ee"]),
"https://community.sketch-your-mind.com/ee",
UrlPurpose.SUPPORT,
),
TWITTER_COM_ZSVICZIAN: defineUrl(
buildSafeUrl(["twitter", "com"], ["zsviczian"]),
"https://twitter.com/zsviczian",
UrlPurpose.SUPPORT,
),
COMMUNITY_SKETCH_YOUR_MIND_COM_SYM: defineUrl(
buildSafeUrl(["community", "sketch-your-mind", "com"], ["sym"]),
"https://community.sketch-your-mind.com/sym",
UrlPurpose.SUPPORT,
),
PLATFORM_OPENAI_COM_DOCS_GUIDES_IMAGE_GENERATION: defineUrl(
buildSafeUrl(
["platform", "openai", "com"],
["docs", "guides", "image-generation"],
),
"https://platform.openai.com/docs/guides/image-generation",
UrlPurpose.DOCS,
),
WWW_W3SCHOOLS_COM_COLORS_COLORS_NAMES_ASP: defineUrl(
buildSafeUrl(["www", "w3schools", "com"], ["colors", "colors_names.asp"]),
"https://www.w3schools.com/colors/colors_names.asp",
UrlPurpose.DOCS,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RAW_REFS_HEADS_MASTER_ASSETS_EXCALIDRAW_FONTS_ZIP:
defineUrl(
buildSafeUrl(
["github", "com"],
[
"zsviczian",
"obsidian-excalidraw-plugin",
"raw",
"refs",
"heads",
"master",
"assets",
"excalidraw-fonts.zip",
],
),
"https://github.com/zsviczian/obsidian-excalidraw-plugin/raw/refs/heads/master/assets/excalidraw-fonts.zip",
UrlPurpose.DOCS,
),
SKETCH_YOUR_MIND_COM_IMAGES_LOGO_EE_PNG: defineUrl(
buildSafeUrl(["sketch-your-mind", "com"], ["images", "logo-EE.png"]),
"https://sketch-your-mind.com/images/logo-EE.png",
UrlPurpose.APP_LOGIC,
),
WWW_YOUTUBE_COM_WATCH: defineUrl(
buildSafeUrl(["www", "youtube", "com"], ["watch?v=P_Q6avJGoWI"]),
"https://www.youtube.com/watch?v=P_Q6avJGoWI",
UrlPurpose.VIDEO,
),
I_YTIMG_COM: defineUrl("https://i.ytimg.com", UrlPurpose.APP_LOGIC),
I_YTIMG_COM_VI_P_Q6AVJGOWI_MAXRESDEFAULT_JPG: defineUrl(
buildSafeUrl(
["i", "ytimg", "com"],
["vi", "P_Q6avJGoWI", "maxresdefault.jpg"],
),
"https://i.ytimg.com/vi/P_Q6avJGoWI/maxresdefault.jpg",
UrlPurpose.VIDEO,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "releases"],
),
"https://github.com/zsviczian/obsidian-excalidraw-plugin/releases",
UrlPurpose.RELEASE_LOG,
),
PIEROXY_NET_BLOG_PAGES_LZ_STRING_INDEX_HTML: defineUrl(
buildSafeUrl(
["pieroxy", "net"],
["blog", "pages", "lz-string", "index.html"],
),
"https://pieroxy.net/blog/pages/lz-string/index.html",
UrlPurpose.DOCS,
),
MOMENTJS_COM_DOCS: defineUrl(
buildSafeUrl(["momentjs", "com"], ["docs", "#", "displaying", "format"]),
"https://momentjs.com/docs/#/displaying/format",
UrlPurpose.DOCS,
),
YOUTUBE_COM_SHORTS_O_1LS9C6WBY: defineUrl(
buildSafeUrl(["youtube", "com"], ["shorts", "O_1ls9c6wBY?feature=share"]),
"https://youtube.com/shorts/O_1ls9c6wBY?feature=share",
UrlPurpose.VIDEO,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG_1_6_23:
defineUrl(
buildSafeUrl(
["github", "com"],
[
"zsviczian",
"obsidian-excalidraw-plugin",
"releases",
"tag",
"1.6.23",
],
),
"https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.6.23",
UrlPurpose.RELEASE_LOG,
),
EN_WIKIPEDIA_ORG_WIKI_SCALABLE_VECTOR_GRAPHICS: defineUrl(
buildSafeUrl(
["en", "wikipedia", "org"],
["wiki", "Scalable_Vector_Graphics"],
),
"https://en.wikipedia.org/wiki/Scalable_Vector_Graphics",
UrlPurpose.DOCS,
),
WWW_YOUTUBE_COM_WATCH_1: defineUrl(
buildSafeUrl(["www", "youtube", "com"], ["watch?v=yZQoJg2RCKI&t=633s"]),
"https://www.youtube.com/watch?v=yZQoJg2RCKI&t=633s",
UrlPurpose.VIDEO,
),
GITHUB_COM_DEATHAU_SLIDING_PANES_OBSIDIAN: defineUrl(
buildSafeUrl(["github", "com"], ["deathau", "sliding-panes-obsidian"]),
"https://github.com/deathau/sliding-panes-obsidian",
UrlPurpose.DOCS,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_API_EXCALIDRAWAUTOMATE_D_TS:
defineUrl(
buildSafeUrl(
["github", "com"],
[
"zsviczian",
"obsidian-excalidraw-plugin",
"blob",
"master",
"docs",
"API",
"ExcalidrawAutomate.d.ts",
],
),
"https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/API/ExcalidrawAutomate.d.ts",
UrlPurpose.DOCS,
),
ZSVICZIAN_GITHUB_IO_OBSIDIAN_EXCALIDRAW_PLUGIN: defineUrl(
buildSafeUrl(["zsviczian", "github", "io"], ["obsidian-excalidraw-plugin"]),
"https://zsviczian.github.io/obsidian-excalidraw-plugin",
UrlPurpose.DOCS,
),
WWW_TASKBONE_COM_LEGAL_TERMS: defineUrl(
buildSafeUrl(["www", "taskbone", "com"], ["legal", "terms"]),
"https://www.taskbone.com/legal/terms",
UrlPurpose.TASKBONE,
),
WWW_TASKBONE_COM_LEGAL_PRIVACY: defineUrl(
buildSafeUrl(["www", "taskbone", "com"], ["legal", "privacy"]),
UrlPurpose.TASKBONE,
),
WWW_TASKBONE_COM: defineUrl(
buildSafeUrl(["www", "taskbone", "com"]),
"https://www.taskbone.com/legal/privacy",
UrlPurpose.TASKBONE,
),
WWW_TASKBONE_COM: defineUrl("https://www.taskbone.com", UrlPurpose.TASKBONE),
COMMUNITY_SKETCH_YOUR_MIND_COM: defineUrl(
buildSafeUrl(["community", "sketch-your-mind", "com"]),
"https://community.sketch-your-mind.com",
UrlPurpose.SUPPORT,
),
WANGCHUJIANG_COM_FREE_FONT: defineUrl(
buildSafeUrl(["wangchujiang", "com"], ["free-font"]),
"https://wangchujiang.com/free-font",
UrlPurpose.DOCS,
),
WWW_YOUTUBE_COM_WATCH_2: defineUrl(
buildSafeUrl(["www", "youtube", "com"], ["watch?v=EiT56z3KPjI"]),
UrlPurpose.VIDEO,
),
I_YTIMG_COM_VI_EIT56Z3KPJI_MAXRESDEFAULT_JPG: defineUrl(
buildSafeUrl(
["i", "ytimg", "com"],
["vi", "EiT56z3KPjI", "maxresdefault.jpg"],
),
UrlPurpose.VIDEO,
),
SKETCH_YOUR_MIND_COM_IMAGES_LOGO_EM_PNG: defineUrl(
buildSafeUrl(["sketch-your-mind", "com"], ["images", "logo-EM.png"]),
"https://sketch-your-mind.com/images/logo-EM.png",
UrlPurpose.APP_LOGIC,
),
WWW_YOUTUBE_COM_WATCH_3: defineUrl(
buildSafeUrl(["www", "youtube", "com"], ["watch?v=TnwRlaIdhSU"]),
UrlPurpose.VIDEO,
),
SKETCH_YOUR_MIND_COM_IMAGES_THUMBNAIL_PODCAST_JPG: defineUrl(
buildSafeUrl(
["sketch-your-mind", "com"],
["images", "Thumbnail-podcast.jpg"],
),
"https://sketch-your-mind.com/images/Thumbnail-podcast.jpg",
UrlPurpose.RELEASE_LOG,
),
WWW_YOUTUBE_COM_WATCH_4: defineUrl(
buildSafeUrl(["www", "youtube", "com"], ["watch?v=g-BiyQ7TJTM"]),
UrlPurpose.VIDEO,
),
I_YTIMG_COM_VI_G_BIYQ7TJTM_MAXRESDEFAULT_JPG: defineUrl(
buildSafeUrl(
["i", "ytimg", "com"],
["vi", "g-BiyQ7TJTM", "maxresdefault.jpg"],
),
UrlPurpose.VIDEO,
),
WWW_YOUTUBE_COM_WATCH_5: defineUrl(
buildSafeUrl(["www", "youtube", "com"], ["watch?v=5G9QF-u9w0Q"]),
UrlPurpose.VIDEO,
),
I_YTIMG_COM_VI_5G9QF_U9W0Q_MAXRESDEFAULT_JPG: defineUrl(
buildSafeUrl(
["i", "ytimg", "com"],
["vi", "5G9QF-u9w0Q", "maxresdefault.jpg"],
),
UrlPurpose.VIDEO,
),
COMMUNITY_OBSIDIAN_MD_PLUGINS_OBSIDIAN_EXCALIDRAW_PLUGIN: defineUrl(
buildSafeUrl(
["community", "obsidian", "md"],
["plugins", "obsidian-excalidraw-plugin"],
),
"https://community.obsidian.md/plugins/obsidian-excalidraw-plugin",
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2688: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "2688"],
),
GITHUB_COM: defineUrl("https://github.com/", UrlPurpose.RELEASE_LOG),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES: defineUrl(
"https://github.com/excalidraw/excalidraw/issues",
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2652: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "2652"],
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL: defineUrl(
"https://github.com/excalidraw/excalidraw/pull",
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_798: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "798"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2739: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "2739"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2718: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "2718"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_HEINRICH26: defineUrl(
buildSafeUrl(["github", "com"], ["heinrich26"]),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES_11018: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "issues", "11018"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10979: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "10979"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_11031: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "11031"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10760: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "10760"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_11053: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "11053"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL_2715: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "pull", "2715"],
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL: defineUrl(
"https://github.com/zsviczian/obsidian-excalidraw-plugin/pull",
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_SREEDHARSREERAM: defineUrl(
buildSafeUrl(["github", "com"], ["sreedharsreeram"]),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2713: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "2713"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10970: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "10970"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL_2684: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "pull", "2684"],
),
"https://github.com/sreedharsreeram",
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_TRAVISLEBLANC1: defineUrl(
buildSafeUrl(["github", "com"], ["TravisLEBLANC1"]),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL_2698: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "pull", "2698"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10940: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "10940"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10906: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "10906"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL_2703: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "pull", "2703"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL_2687: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "pull", "2687"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL_2697: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "pull", "2697"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2685: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "2685"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2704: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "2704"],
),
"https://github.com/TravisLEBLANC1",
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_EA_SCRIPT_DOCS_MINDMAPBUILDERAPI_MD:
defineUrl(
buildSafeUrl(
["github", "com"],
[
"zsviczian",
"obsidian-excalidraw-plugin",
"blob",
"master",
"docs",
"ea-script-docs",
"MindMapBuilderAPI.md",
],
),
"https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/ea-script-docs/MindMapBuilderAPI.md",
UrlPurpose.DOCS,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10797: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "10797"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10824: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "10824"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10832: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "10832"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10831: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "10831"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10816: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "10816"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2673: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "2673"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2670: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "2670"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2665: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "2665"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES_10772: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "issues", "10772"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL_2668: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "pull", "2668"],
),
UrlPurpose.RELEASE_LOG,
),
VISUAL_THINKING_WORKSHOP_COM_MINDMAP: defineUrl(
buildSafeUrl(["visual-thinking-workshop", "com"], ["mindmap"]),
"https://visual-thinking-workshop.com/mindmap",
UrlPurpose.SUPPORT,
),
YOUTU_BE_HRTAAD34ZZG: defineUrl(
buildSafeUrl(["youtu", "be"], ["HRtaaD34Zzg"]),
UrlPurpose.VIDEO,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10611: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "10611"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2660: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "2660"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL_2655: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "pull", "2655"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_SUPERLE3: defineUrl(
buildSafeUrl(["github", "com"], ["superle3"]),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10613: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "10613"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2589: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "2589"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10726: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "10726"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2647: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "2647"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2636: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "2636"],
),
"https://github.com/superle3",
UrlPurpose.RELEASE_LOG,
),
WWW_TIMEANDDATE_COM_WORLDCLOCK_FIXEDTIME_HTML: defineUrl(
buildSafeUrl(
["www", "timeanddate", "com"],
[
"worldclock",
"fixedtime.html?msg=MindMap+Builder+Launch+Party&iso=20260131T17&p1=%3A&ah=1",
],
),
"https://www.timeanddate.com/worldclock/fixedtime.html?msg=MindMap+Builder+Launch+Party&iso=20260131T17&p1=%3A&ah=1",
UrlPurpose.RELEASE_LOG,
),
WWW_TIMEANDDATE_COM_WORLDCLOCK_FIXEDTIME_HTML_1: defineUrl(
buildSafeUrl(
["www", "timeanddate", "com"],
[
"worldclock",
"fixedtime.html?msg=MindMap+Builder+Launch+Party&iso=20260201T08&p1=%3A&ah=1",
],
),
UrlPurpose.RELEASE_LOG,
),
YOUTU_BE_ISUORBVKYHQ: defineUrl(
buildSafeUrl(["youtu", "be"], ["ISuORbVKyhQ"]),
UrlPurpose.VIDEO,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10578: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "10578"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10530: defineUrl(
buildSafeUrl(
["github", "com"],
["excalidraw", "excalidraw", "pull", "10530"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2625: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "2625"],
),
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2578: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "issues", "2578"],
),
"https://www.timeanddate.com/worldclock/fixedtime.html?msg=MindMap+Builder+Launch+Party&iso=20260201T08&p1=%3A&ah=1",
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_STEVERUIZOK_PERFECT_FREEHAND: defineUrl(
buildSafeUrl(
["github", "com"],
["steveruizok", "perfect-freehand#documentation"],
),
"https://github.com/steveruizok/perfect-freehand#documentation",
UrlPurpose.DOCS,
),
EASINGS_NET: defineUrl(buildSafeUrl(["easings", "net"]), UrlPurpose.DOCS),
EASINGS_NET: defineUrl("https://easings.net", UrlPurpose.DOCS),
VISUAL_THINKING_WORKSHOP_COM: defineUrl(
buildSafeUrl(["community", "sketch-your-mind", "com"], ["vtw"]),
"https://community.sketch-your-mind.com/vtw",
UrlPurpose.SUPPORT,
),
RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_INDEX_NEW_MD:
defineUrl(
buildSafeUrl(
["raw", "githubusercontent", "com"],
[
"zsviczian",
"obsidian-excalidraw-plugin",
"master",
"ea-scripts",
"index-new.md",
],
),
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/index-new.md",
UrlPurpose.APP_LOGIC,
),
WWW_W3SCHOOLS_COM_COLORS_DEFAULT_ASP: defineUrl(
buildSafeUrl(["www", "w3schools", "com"], ["colors", "default.asp"]),
"https://www.w3schools.com/colors/default.asp",
UrlPurpose.DOCS,
),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_TREE_MASTER_SRC_PACKAGES_EXCALIDRAW:
defineUrl(
buildSafeUrl(
["github", "com"],
[
"excalidraw",
"excalidraw",
"tree",
"master",
"src",
"packages",
"excalidraw#ref",
],
),
"https://github.com/excalidraw/excalidraw/tree/master/src/packages/excalidraw#ref",
UrlPurpose.DOCS,
),
ZSVICZIAN_GITHUB_IO_OBSIDIAN_EXCALIDRAW_PLUGIN_EXCALIDRAWSCRIPTSENGINE_HTML:
defineUrl(
buildSafeUrl(
["zsviczian", "github", "io"],
["obsidian-excalidraw-plugin", "ExcalidrawScriptsEngine.html"],
),
"https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html",
UrlPurpose.DOCS,
),
GITHUB_COM_LBRAGILE_COLORMASTER: defineUrl(
buildSafeUrl(["github", "com"], ["lbragile", "ColorMaster"]),
"https://github.com/lbragile/ColorMaster",
UrlPurpose.DOCS,
),
GITHUB_COM_OBSIDIANMD_OBSIDIAN_API_BLOB_MASTER_OBSIDIAN_D_TS: defineUrl(
buildSafeUrl(
["github", "com"],
["obsidianmd", "obsidian-api", "blob", "master", "obsidian.d.ts"],
),
"https://github.com/obsidianmd/obsidian-api/blob/master/obsidian.d.ts",
UrlPurpose.DOCS,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "releases", "tag"],
),
"https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag",
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG_1_9_9: defineUrl(
buildSafeUrl(
["github", "com"],
["zsviczian", "obsidian-excalidraw-plugin", "releases", "tag", "1.9.9"],
),
"https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.9.9",
UrlPurpose.RELEASE_LOG,
),
TRANSLATE_GOOGLE_COM: defineUrl(
buildSafeUrl(
["translate", "google", "com"],
[
"?sl=en&tl=zh-CN&text=This%20file%20contains%20embedded%20frames%20which%20will%20be%20migrated%20to%20a%20newer%20version%20for%20compatibility%20with%20excalidraw.com.%0A%0AIf%20you%27re%20using%20Obsidian%20on%20multiple%20devices%2C%20you%20may%20proceed%20now%2C%20but%20please%2C%20before%20opening%20this%20file%20on%20your%20other%20devices%2C%20update%20Excalidraw%20on%20those%20as%20well.%0A%0AMore%20info%20is%20available%20here%3A%20https%3A%2F%2Fgithub.com%2Fzsviczian%2Fobsidian-excalidraw-plugin%2Freleases%2Ftag%2F1.9.9%27%3Ehere%3C%2Fa%3E.&op=translate",
],
),
"https://translate.google.com/?sl=en&tl=zh-CN&text=This%20file%20contains%20embedded%20frames%20which%20will%20be%20migrated%20to%20a%20newer%20version%20for%20compatibility%20with%20excalidraw.com.%0A%0AIf%20you%27re%20using%20Obsidian%20on%20multiple%20devices%2C%20you%20may%20proceed%20now%2C%20but%20please%2C%20before%20opening%20this%20file%20on%20your%20other%20devices%2C%20update%20Excalidraw%20on%20those%20as%20well.%0A%0AMore%20info%20is%20available%20here%3A%20https%3A%2F%2Fgithub.com%2Fzsviczian%2Fobsidian-excalidraw-plugin%2Freleases%2Ftag%2F1.9.9%27%3Ehere%3C%2Fa%3E.&op=translate",
UrlPurpose.TRANSLATION,
),
API_TASKBONE_COM: defineUrl(
buildSafeUrl(["api", "taskbone", "com"]),
UrlPurpose.TASKBONE,
),
API_TASKBONE_COM: defineUrl("https://api.taskbone.com", UrlPurpose.TASKBONE),
CDN_TAILWINDCSS_COM: defineUrl(
buildSafeUrl(["cdn", "tailwindcss", "com"]),
"https://cdn.tailwindcss.com",
UrlPurpose.APP_LOGIC,
),
YOUTU_BE: defineUrl(buildSafeUrl(["youtu", "be"]), UrlPurpose.APP_LOGIC),
WWW_YOUTUBE_COM: defineUrl(
buildSafeUrl(["www", "youtube", "com"]),
YOUTU_BE: defineUrl("https://youtu.be", UrlPurpose.APP_LOGIC),
WWW_YOUTUBE_COM: defineUrl("https://www.youtube.com", UrlPurpose.APP_LOGIC),
YOUTUBE_COM: defineUrl("https://youtube.com", UrlPurpose.APP_LOGIC),
PLAYER_VIMEO_COM: defineUrl("https://player.vimeo.com", UrlPurpose.APP_LOGIC),
NOEMBED_COM_EMBED_URL: defineUrl(
"https://noembed.com/embed?url=",
UrlPurpose.APP_LOGIC,
),
YOUTUBE_COM: defineUrl(
buildSafeUrl(["youtube", "com"]),
UrlPurpose.APP_LOGIC,
),
PLAYER_VIMEO_COM: defineUrl(
buildSafeUrl(["player", "vimeo", "com"]),
UrlPurpose.APP_LOGIC,
),
YOUTU_BE_YZQOJG2RCKI: defineUrl(
buildSafeUrl(["youtu", "be"], ["yZQoJg2RCKI"]),
UrlPurpose.VIDEO,
),
YOUTU_BE_R08WK_58DPK: defineUrl(
buildSafeUrl(["youtu", "be"], ["r08wk-58DPk"]),
UrlPurpose.VIDEO,
),
YOUTU_BE_UHFD0XOHRXE: defineUrl(
buildSafeUrl(["youtu", "be"], ["uHFd0XoHRxE"]),
UrlPurpose.VIDEO,
),
} as const;
/**
@@ -834,3 +332,8 @@ export const URL_REGISTRY = {
export const URLs = Object.fromEntries(
Object.entries(URL_REGISTRY).map(([key, data]) => [key, data.url]),
) as { [K in keyof typeof URL_REGISTRY]: string };
export const getYouTubeThumbnailUrl = (id: string) =>
`${URLs.I_YTIMG_COM}/vi/${id}/maxresdefault.jpg`;
export const getYouTubeUrl = (id: string) =>
`${URLs.YOUTUBE_COM}/watch?v=${id}`;
+1 -1
View File
@@ -32,7 +32,7 @@ export class EditorHandler {
return;
}
if (extensionState == true) {
this.activeEditorExtensions.push(extension as TaggedExtension);
this.activeEditorExtensions.push(extension);
this.activeEditorExtensions[this.activeEditorExtensions.length - 1].exID =
extensionIdentifier;
} else {
+7 -2
View File
@@ -1,5 +1,6 @@
import "obsidian";
import type { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { errorlog } from "src/utils/coreUtils";
import type ExcalidrawView from "src/view/ExcalidrawView";
//import { ExcalidrawAutomate } from "./ExcalidrawAutomate";
//export ExcalidrawAutomate from "./ExcalidrawAutomate";
@@ -16,8 +17,12 @@ export type { Point } from "src/types/types";
export const getEA = (view?: ExcalidrawView): ExcalidrawAutomate | null => {
try {
return window.ExcalidrawAutomate.getAPI(view);
} catch (_) {
console.log({ message: "Excalidraw not available", fn: getEA });
} catch (error) {
errorlog({
message: "Excalidraw not available",
fn: getEA,
error: error as unknown,
});
return null;
}
};
+142 -396
View File
@@ -1,3 +1,4 @@
import { ExcalidrawExtrasGateway } from "../utils/ExcalidrawExtrasGateway";
import {
TFile,
Plugin,
@@ -10,9 +11,7 @@ import {
ViewState,
ViewStateResult,
Notice,
request,
MetadataCache,
Workspace,
TAbstractFile,
FrontMatterCache,
} from "obsidian";
@@ -28,7 +27,6 @@ import {
FRONTMATTER,
JSON_parse,
SCRIPT_INSTALL_CODEBLOCK,
SCRIPT_INSTALL_FOLDER,
EXPORT_TYPES,
EXPORT_IMG_ICON_NAME,
EXPORT_IMG_ICON,
@@ -37,8 +35,8 @@ import {
DEVICE,
FONTS_STYLE_ID,
CJK_STYLE_ID,
loadMermaid,
setRootElementSize,
mainDocument,
} from "../constants/constants";
import {
ExcalidrawSettings,
@@ -50,25 +48,18 @@ import {
KNOWN_AI_IMAGE_MODEL_CONFIGS,
} from "./settings";
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
import {
initExcalidrawAutomate,
insertLaTeXToView,
} from "src/utils/excalidrawAutomateUtils";
import { around, dedupe } from "monkey-around";
import { initExcalidrawAutomate } from "src/utils/excalidrawAutomateUtils";
import { t } from "../lang/helpers";
import {
createOrOverwriteFile,
fileShouldDefaultAsExcalidraw,
getDrawingFilename,
getIMGFilename,
getNewUniqueFilepath,
} from "../utils/fileUtils";
import {
getFontDataURL,
errorlog,
sleep,
isVersionNewerThanOther,
isCallerFromTemplaterPlugin,
versionUpdateCheckTimer,
getFontMetrics,
calculateUIModeValue,
@@ -89,18 +80,16 @@ import {
import { FieldSuggester } from "../shared/Suggesters/FieldSuggester";
import { ReleaseNotes } from "../shared/Dialogs/ReleaseNotes";
import { DeviceType, Packages } from "../types/types";
import { PreviewImageType } from "../types/utilTypes";
import { PaneTarget, PreviewImageType } from "../types/utilTypes";
import {
emulateCTRLClickForLinks,
linkClickModifierType,
PaneTarget,
} from "../utils/modifierkeyHelper";
import { imageCache } from "../shared/ImageCache";
import { getImageCache } from "../shared/ImageCache";
import { StylesManager } from "./managers/StylesManager";
import { CustomMutationObserver, log } from "../utils/debugHelper";
import { ExcalidrawConfig } from "../shared/ExcalidrawConfig";
import { EditorHandler } from "./editor/EditorHandler";
import { ExcalidrawLib } from "../types/excalidrawLib";
import { Rank, SwordColors } from "../constants/actionIcons";
import { RankMessage } from "../shared/Dialogs/RankMessage";
import {
@@ -113,10 +102,10 @@ import {
ExcalidrawLoading,
switchToExcalidraw,
} from "../view/ExcalidrawLoading";
import { clearMathJaxVariables } from "../shared/LaTeX";
import { PluginFileManager } from "./managers/FileManager";
import { ObserverManager } from "./managers/ObserverManager";
import { PackageManager } from "./managers/PackageManager";
import { MonkeyPatchManager } from "./managers/MonkeyPatchManager";
import ExcalidrawView from "../view/ExcalidrawView";
import { ExcalidrawSidepanelView } from "../view/sidepanel/Sidepanel";
import { CommandManager } from "./managers/CommandManager";
@@ -131,7 +120,10 @@ import {
decryptPersistedAPIKeys,
encryptPersistedAPIKeys,
} from "src/utils/settingsKeyObfuscation";
import { URLs } from "src/constants/safeUrls";
import { hideElement, setButtonBgColor } from "src/utils/styleUtils";
import { installButton } from "src/utils/scriptLibraryUtils";
import { isInstanceOfHTMLStyleElement } from "src/utils/typechecks";
import { insertLaTeXToView } from "src/utils/excalidrawViewHelpers";
declare const PLUGIN_VERSION: string;
declare const INITIAL_TIMESTAMP: number;
@@ -208,6 +200,25 @@ const LEGACY_PROVIDER_LABELS: Record<string, string> = {
"openai-compatible": "OpenAI-compatible",
};
/**
* Compatibility labels consumed by upstream Excalidraw via ExcalidrawPlugin.getLabel().
* Keep these keys present in `en.ts`, and keep maintained locales in sync.
*/
const EXCALIDRAW_EXTERNAL_GET_LABEL_KEYS = [
"COMP_FRAME_HINT",
"COMP_FRAME",
"COMP_IMG",
"COMP_IMG_FROM_SYSTEM",
"COMP_IMG_ANY_FILE",
"INSERT_CARD",
"COMP_IMG_LaTeX",
"ABOUT_LIBRARIES",
] as const satisfies readonly (keyof typeof en)[];
const EXCALIDRAW_EXTERNAL_GET_LABEL_KEY_SET = new Set<keyof typeof en>(
EXCALIDRAW_EXTERNAL_GET_LABEL_KEYS,
);
const stripLegacyAISettings = <T extends PersistedExcalidrawSettings>(
settings: T,
): T => {
@@ -393,8 +404,7 @@ const migrateLegacyAISettings = (
};
const providerProfiles = ensureProviderProfiles();
const legacyProviderType = (migrated.aiProvider ??
"openai") as ExcalidrawSettings["aiProvider"];
const legacyProviderType = migrated.aiProvider ?? "openai";
const providerProfileId =
LEGACY_PROVIDER_LABELS[legacyProviderType] ?? "OpenAI";
if (!hadProviderProfiles) {
@@ -566,9 +576,11 @@ const migrateLegacyAISettings = (
};
export default class ExcalidrawPlugin extends Plugin {
public extrasGateway: ExcalidrawExtrasGateway;
private fileManager: PluginFileManager;
private observerManager: ObserverManager;
private packageManager: PackageManager;
private monkeyPatchManager: MonkeyPatchManager;
private commandManager: CommandManager;
private eventManager: EventManager;
public eaInstances = new WeakArray<ExcalidrawAutomate>();
@@ -602,6 +614,7 @@ export default class ExcalidrawPlugin extends Plugin {
public loadTimestamp: number;
private isLocalCJKFontAvailabe: boolean = undefined;
public isReady = false;
private fontsReady = true; //setting this to true allows for a race condition during startup loading fonts and rendering Excalidraw
private startupAnalytics: string[] = [];
private lastLogTimestamp: number;
private settingsReady: boolean = false;
@@ -646,7 +659,7 @@ export default class ExcalidrawPlugin extends Plugin {
}
public printStarupBreakdown() {
console.log(
log(
`Excalidraw ${PLUGIN_VERSION} startup breakdown:\n${this.startupAnalytics.join(
"\n",
)}`,
@@ -661,13 +674,9 @@ export default class ExcalidrawPlugin extends Plugin {
return window;
}
get document(): Document {
return document;
}
// by adding the wrapper like this, likely in debug mode I am leaking memory because my code removes
// the original event handlers, not the wrapped ones. I will only uncomment this if I need to debug
/*public registerEvent(event: any) {
/*public registerEvent(event: EventRef) {
if (process.env.NODE_ENV !== 'development') {
super.registerEvent(event);
return;
@@ -676,10 +685,12 @@ export default class ExcalidrawPlugin extends Plugin {
super.registerEvent(event);
return;
}
const originalHandler = event.fn;
const originalHandler = event.fn as (
...handlerArgs: unknown[]
) => Promise<unknown> | unknown;
// Wrap the original event handler
const wrappedHandler = async (...args: any[]) => {
const wrappedHandler = async (...args: Parameters<typeof originalHandler>) => {
const startTime = performance.now(); // Get start time
// Invoke the original event handler
@@ -708,7 +719,25 @@ export default class ExcalidrawPlugin extends Plugin {
* @returns shared mermaid instance
*/
public async getMermaid() {
return await loadMermaid();
const mermaidApi = await this.extrasGateway.getMermaid();
if (mermaidApi) {
return {
loaded: true,
// Forwarding the raw module dynamically fetched by the Extras plugin.
// This makes your setup completely immune to upstream Mermaid signature changes.
api: mermaidApi.getModule(),
};
}
return {
loaded: false,
api: Promise.reject(
new Error(
"Mermaid to Excalidraw requires the Excalidraw Extras companion plugin.",
),
),
};
}
public isPenMode() {
@@ -771,15 +800,13 @@ export default class ExcalidrawPlugin extends Plugin {
addIcon(ICON_NAME, EXCALIDRAW_ICON);
addIcon(SCRIPTENGINE_ICON_NAME, SCRIPTENGINE_ICON);
addIcon(EXPORT_IMG_ICON_NAME, EXPORT_IMG_ICON);
this.addRibbonIcon(
ICON_NAME,
t("CREATE_NEW"),
this.actionRibbonClick.bind(this),
this.addRibbonIcon(ICON_NAME, t("CREATE_NEW"), (e) =>
this.actionRibbonClick(e),
);
try {
void this.loadSettings({ reEnableAutosave: true }).then(
this.onloadCheckForOnceOffSettingsUpdates.bind(this),
void this.loadSettings({ reEnableAutosave: true }).then(() =>
this.onloadCheckForOnceOffSettingsUpdates(),
);
} catch (e) {
new Notice("Error loading plugin settings", 6000);
@@ -791,7 +818,7 @@ export default class ExcalidrawPlugin extends Plugin {
// need it her for ExcaliBrain
this.ea = initExcalidrawAutomate(this);
} catch (e) {
new Notice("Error initializing Excalidraw Automate", 6000);
new Notice(t("ERROR_INITIALIZING_EA"), 6000);
console.error("Error initializing Excalidraw Automate", e);
}
this.logStartupEvent("Excalidraw Automate initialized");
@@ -800,12 +827,12 @@ export default class ExcalidrawPlugin extends Plugin {
//Licat: Are you registering your post processors in onLayoutReady? You should register them in onload instead
this.addMarkdownPostProcessor();
} catch (e) {
new Notice("Error adding markdown post processor", 6000);
console.error("Error adding markdown post processor", e);
new Notice("Error adding Markdown post processor", 6000);
console.error("Error adding Markdown post processor", e);
}
this.logStartupEvent("Markdown post processor added");
this.app.workspace.onLayoutReady(this.onloadOnLayoutReady.bind(this));
this.app.workspace.onLayoutReady(() => this.onloadOnLayoutReady());
this.logStartupEvent("Workspace ready event handler added");
}
@@ -838,6 +865,7 @@ export default class ExcalidrawPlugin extends Plugin {
);
await this.awaitSettings();
this.logStartupEvent("Settings awaited");
this.extrasGateway = new ExcalidrawExtrasGateway(this.app, this);
if (!this.settings.overrideObsidianFontSize) {
setRootElementSize();
}
@@ -845,6 +873,7 @@ export default class ExcalidrawPlugin extends Plugin {
this.packageManager = new PackageManager(this);
this.eventManager = new EventManager(this);
this.observerManager = new ObserverManager(this);
this.monkeyPatchManager = new MonkeyPatchManager(this);
this.commandManager = new CommandManager(this);
try {
@@ -868,7 +897,7 @@ export default class ExcalidrawPlugin extends Plugin {
try {
//inspiration taken from kanban:
//https://github.com/mgmeyers/obsidian-kanban/blob/44118e25661bff9ebfe54f71ae33805dc88ffa53/src/main.ts#L267
this.registerMonkeyPatches();
this.monkeyPatchManager.initialize();
} catch (e) {
new Notice("Error registering monkey patches", 6000);
console.error("Error registering monkey patches", e);
@@ -893,16 +922,10 @@ export default class ExcalidrawPlugin extends Plugin {
}
this.logStartupEvent("Script engine initialized");
try {
await this.initializeFonts();
} catch (e) {
new Notice("Error initializing fonts", 6000);
console.error("Error initializing fonts", e);
}
this.logStartupEvent("Fonts initialized");
void this.initializeFonts();
try {
void imageCache.initializeDB(this);
void getImageCache().initializeDB(this);
} catch (e) {
new Notice("Error initializing image cache", 6000);
console.error("Error initializing image cache", e);
@@ -1006,7 +1029,7 @@ export default class ExcalidrawPlugin extends Plugin {
public async awaitInit() {
let counter = 0;
while (!this.isReady && counter < 150) {
while ((!this.isReady || !this.fontsReady) && counter < 200) {
await sleep(50);
counter++;
}
@@ -1022,13 +1045,15 @@ export default class ExcalidrawPlugin extends Plugin {
return;
}
const app = this.app;
Object.keys(FRONTMATTER_KEYS).forEach((key) => {
if (FRONTMATTER_KEYS[key].depricated === true) {
return;
}
const { name, type } = FRONTMATTER_KEYS[key];
app.metadataTypeManager.setType(name, type);
});
Object.keys(FRONTMATTER_KEYS).forEach(
(key: keyof typeof FRONTMATTER_KEYS) => {
if (FRONTMATTER_KEYS[key].depricated === true) {
return;
}
const { name, type } = FRONTMATTER_KEYS[key];
app.metadataTypeManager.setType(name, type);
},
);
}
public async initializeFonts() {
@@ -1085,7 +1110,7 @@ export default class ExcalidrawPlugin extends Plugin {
if (!fontMetrics) {
return;
}
(excalidrawLib as typeof ExcalidrawLib).registerLocalFont(
excalidrawLib.registerLocalFont(
{ metrics: fontMetrics },
fourthFontDataURL,
);
@@ -1104,11 +1129,12 @@ export default class ExcalidrawPlugin extends Plugin {
this.fourthFontLoaded = true;
}, 100);
}
this.fontsReady = true;
}
public async addFonts(
declarations: string[],
ownerDocument: Document = document,
ownerDocument: Document = mainDocument,
styleId: string = FONTS_STYLE_ID,
) {
// replace the old local font <style> element with the one we just created
@@ -1139,7 +1165,7 @@ export default class ExcalidrawPlugin extends Plugin {
public updatePhoneFooterSafeAreaPadding() {
const documents = new Set<Document>([
document,
mainDocument,
...this.getOpenObsidianDocuments(),
]);
const shouldEnable =
@@ -1155,8 +1181,7 @@ export default class ExcalidrawPlugin extends Plugin {
}
return;
}
if (existingStylesheet instanceof HTMLStyleElement) {
if (isInstanceOfHTMLStyleElement(existingStylesheet)) {
existingStylesheet.textContent = PHONE_FOOTER_SAFE_AREA_CSS;
return;
}
@@ -1170,7 +1195,7 @@ export default class ExcalidrawPlugin extends Plugin {
private removePhoneFooterSafeAreaPadding() {
const documents = new Set<Document>([
document,
mainDocument,
...this.getOpenObsidianDocuments(),
]);
documents.forEach((ownerDocument) => {
@@ -1187,7 +1212,7 @@ export default class ExcalidrawPlugin extends Plugin {
const visitedDocs = new Set<Document>();
this.app.workspace.iterateAllLeaves((leaf) => {
const ownerDocument = DEVICE.isMobile
? document
? mainDocument
: leaf.view.containerEl.ownerDocument;
if (!ownerDocument) {
return;
@@ -1211,7 +1236,7 @@ export default class ExcalidrawPlugin extends Plugin {
this.isExcalidrawFile(leaf.view.file)
) {
if (fileShouldDefaultAsExcalidraw(leaf.view.file?.path, this.app)) {
this.excalidrawFileModes[(leaf as any).id || leaf.view.file.path] =
this.excalidrawFileModes[leaf.id || leaf.view.file.path] =
VIEW_TYPE_EXCALIDRAW;
void setExcalidrawView(leaf);
} else {
@@ -1246,211 +1271,36 @@ export default class ExcalidrawPlugin extends Plugin {
"data-heading",
)}"]`,
);
link.style.paddingRight = "10px";
link.addClass("excalidraw-installCodeBlock-link");
button2 = link.parentElement.createEl("button", null, (b) => {
b.setText(t("UPDATE_SCRIPT"));
b.addClass("mod-muted");
b.style.backgroundColor = "var(--interactive-success)";
b.style.display = "none";
setButtonBgColor(b, "success");
hideElement(b);
});
} catch (e) {
errorlog({
where: "this.registerInstallCodeblockProcessor",
source,
error: e,
error: e as unknown,
});
}
source = source.trim();
el.createEl("button", null, async (button) => {
const setButtonText = (
text: "CHECKING" | "INSTALL" | "UPTODATE" | "UPDATE" | "ERROR",
) => {
if (button2) {
button2.style.display = "none";
}
switch (text) {
case "CHECKING":
button.setText(t("CHECKING_SCRIPT"));
button.style.backgroundColor = "var(--interactive-normal)";
break;
case "INSTALL":
button.setText(t("INSTALL_SCRIPT"));
button.style.backgroundColor = "var(--interactive-accent)";
break;
case "UPTODATE":
button.setText(t("UPTODATE_SCRIPT"));
button.style.backgroundColor = "var(--interactive-normal)";
break;
case "UPDATE":
button.setText(t("UPDATE_SCRIPT"));
button.style.backgroundColor = "var(--interactive-success)";
if (button2) {
button2.style.display = null;
}
break;
case "ERROR":
button.setText(t("UNABLETOCHECK_SCRIPT"));
button.style.backgroundColor = "var(--interactive-normal)";
break;
}
};
button.addClass("mod-muted");
let decodedURI = source;
try {
decodedURI = decodeURI(source);
} catch (e) {
errorlog({
where:
"ExcalidrawPlugin.registerInstallCodeblockProcessor.codeblockProcessor.onClick",
source,
error: e,
});
}
const fname = decodedURI.substring(decodedURI.lastIndexOf("/") + 1);
const folder = `${this.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}`;
const downloaded = this.app.vault
.getFiles()
.filter((f) => f.path.startsWith(folder) && f.name === fname)
.sort((a, b) => (a.path > b.path ? 1 : -1));
let scriptFile = downloaded[0];
const scriptPath = scriptFile?.path ?? `${folder}/${fname}`;
const svgPath = getIMGFilename(scriptPath, "svg");
let svgFile = this.app.vault.getFileByPath(svgPath);
setButtonText(scriptFile ? "CHECKING" : "INSTALL");
button.onclick = async () => {
const download = async (
url: string,
file: TFile,
localPath: string,
): Promise<TFile> => {
const data = await request({ url });
if (!data || data.startsWith("404: Not Found")) {
return null;
}
return await createOrOverwriteFile(
this.app,
file?.path ?? localPath,
data,
);
};
try {
scriptFile = await download(source, scriptFile, scriptPath);
if (!scriptFile) {
setButtonText("ERROR");
throw "File not found";
}
if (svgFile && svgFile instanceof TFile) {
svgFile = await download(
getIMGFilename(source, "svg"),
svgFile,
svgPath,
);
}
setButtonText("UPTODATE");
if (Object.keys(this.scriptEngine.scriptIconMap).length === 0) {
this.scriptEngine.loadScripts();
}
const restartSidepanelTabIfActive = async () => {
if (!this.scriptEngine || !(scriptFile instanceof TFile)) {
return;
}
const scriptName = this.scriptEngine.getScriptName(scriptFile);
const spView = ExcalidrawSidepanelView.getExisting(false);
if (
!spView ||
!scriptName ||
!spView.getTabByScript(scriptName)
) {
return;
}
try {
await spView.restartTabForScript(scriptName);
} catch (error) {
errorlog({
where:
"ExcalidrawPlugin.registerInstallCodeblockProcessor.restartSidepanelTab",
error,
scriptName,
});
}
};
await restartSidepanelTabIfActive();
new Notice(`Installed: ${scriptFile.basename}`);
} catch (e) {
new Notice(`Error installing script: ${fname}`);
errorlog({
where:
"ExcalidrawPlugin.registerInstallCodeblockProcessor.codeblockProcessor.onClick",
error: e,
});
}
};
if (button2) {
button2.onclick = button.onclick;
}
//check modified date on github
//https://superuser.com/questions/1406875/how-to-get-the-latest-commit-date-of-a-file-from-a-given-github-reposotiry
if (!scriptFile || !(scriptFile instanceof TFile)) {
return;
}
const files = new Map<string, number>();
type RemoteDirectoryInfo = {
fname: string;
mtime: number;
};
JSON.parse(
await request({
url: URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON,
}),
).forEach((f: RemoteDirectoryInfo) => files.set(f.fname, f.mtime));
const checkModifyDate = (
gitFilename: string,
file: TFile,
): "ERROR" | "UPDATE" | "UPTODATE" => {
if (files.size === 0 || !files.has(gitFilename)) {
//setButtonText("ERROR");
return "ERROR";
}
const mtime = files.get(gitFilename);
if (!file || mtime > file.stat.mtime) {
//setButtonText("UPDATE");
return "UPDATE";
}
return "UPTODATE";
};
const scriptButtonText = checkModifyDate(fname, scriptFile);
const svgButtonText = checkModifyDate(
getIMGFilename(fname, "svg"),
!svgFile || !(svgFile instanceof TFile) ? null : svgFile,
);
setButtonText(
scriptButtonText === "UPTODATE" && svgButtonText === "UPTODATE"
? "UPTODATE"
: scriptButtonText === "UPTODATE" && svgButtonText === "ERROR"
? "UPTODATE"
: scriptButtonText === "ERROR"
? "ERROR"
: scriptButtonText === "UPDATE" || svgButtonText === "UPDATE"
? "UPDATE"
: "UPTODATE",
);
el.createEl("button", null, (button) => {
void installButton(this, button, button2, source);
});
};
this.registerMarkdownCodeBlockProcessor(
SCRIPT_INSTALL_CODEBLOCK,
async (source, el) => {
el.addEventListener(RERENDER_EVENT, async (e) => {
e.stopPropagation();
el.empty();
await codeblockProcessor(source, el);
el.addEventListener(RERENDER_EVENT, (e) => {
void (async () => {
e.stopPropagation();
el.empty();
await codeblockProcessor(source, el);
})();
});
await codeblockProcessor(source, el);
},
@@ -1481,7 +1331,7 @@ export default class ExcalidrawPlugin extends Plugin {
if (!this.legacyExcalidrawPopoverObserver) {
//monitoring for div.popover.hover-popover.file-embed.is-loaded to be added to the DOM tree
this.legacyExcalidrawPopoverObserver = legacyExcalidrawPopoverObserver;
this.legacyExcalidrawPopoverObserver.observe(document.body, {
this.legacyExcalidrawPopoverObserver.observe(mainDocument.body, {
childList: true,
subtree: false,
});
@@ -1527,7 +1377,7 @@ export default class ExcalidrawPlugin extends Plugin {
});
}
if (!keepOriginal) {
void this.app.vault.delete(file);
void this.app.fileManager.trashFile(file);
}
return result;
}
@@ -1549,124 +1399,6 @@ export default class ExcalidrawPlugin extends Plugin {
new Notice(`Converted ${files.length} files.`);
}
private registerMonkeyPatches() {
const key = URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES;
this.register(
around(Workspace.prototype, {
getActiveViewOfType(old) {
return dedupe(key, old, function (...args) {
const result = old && old.apply(this, args);
const maybeEAView = self.app?.workspace?.activeLeaf?.view;
if (!maybeEAView || !(maybeEAView instanceof ExcalidrawView)) {
return result;
}
const error = new Error();
const stackTrace = error.stack;
if (!isCallerFromTemplaterPlugin(stackTrace)) {
return result;
}
const leafOrNode = maybeEAView.getActiveEmbeddable();
if (leafOrNode) {
if (leafOrNode.node && leafOrNode.node.isEditing) {
return {
file: leafOrNode.node.file,
editor: leafOrNode.node.child.editor,
};
}
}
return result;
});
},
}),
);
if (!this.app.plugins.plugins?.["obsidian-hover-editor"]) {
this.register(
//stolen from hover editor
around(WorkspaceLeaf.prototype, {
getRoot(old) {
return function () {
const top = old.call(this);
return top.getRoot === this.getRoot ? top : top.getRoot();
};
},
}),
);
}
const self = this;
// Monkey patch WorkspaceLeaf to open Excalidraw drawings with ExcalidrawView by default
this.register(
around(WorkspaceLeaf.prototype, {
// Drawings can be viewed as markdown or Excalidraw, and we keep track of the mode
// while the file is open. When the file closes, we no longer need to keep track of it.
detach(next) {
return function () {
const state = this.view?.getState();
if (
state?.file &&
self.excalidrawFileModes[this.id || state.file]
) {
delete self.excalidrawFileModes[this.id || state.file];
}
return next.apply(this);
};
},
setViewState(next) {
return function (state: ViewState, ...rest: [ViewStateResult?]) {
const markdownViewLoaded =
self._loaded && // Don't force excalidraw mode during shutdown
state.type === "markdown" && // If we have a markdown file
state.state?.file;
if (
markdownViewLoaded &&
self.excalidrawFileModes[this.id || state.state.file] !==
"markdown"
) {
const filepath: string = state.state.file as string;
if (
self.forceToOpenInMarkdownFilepath !== filepath &&
fileShouldDefaultAsExcalidraw(filepath, this.app)
) {
// If we have it, force the view type to excalidraw
const newState = {
...state,
type: VIEW_TYPE_EXCALIDRAW,
};
self.excalidrawFileModes[filepath] = VIEW_TYPE_EXCALIDRAW;
return next.apply(this, [newState, ...rest]);
}
self.forceToOpenInMarkdownFilepath = null;
}
if (markdownViewLoaded) {
const leaf = this;
window.setTimeout(async () => {
if (
!leaf ||
!leaf.view ||
!(leaf.view instanceof MarkdownView) ||
!leaf.view.file ||
!self.isExcalidrawFile(leaf.view.file)
) {
return;
}
foldExcalidrawSection(leaf.view);
}, 500);
}
return next.apply(this, [state, ...rest]);
};
},
}),
);
}
/**
* Loads the startup script that will add event hooks to ExcalidrawAutomate (if provided by the user)
* Because of file operations, this must be run after the Obsidian Layout is ready
@@ -1734,15 +1466,6 @@ export default class ExcalidrawPlugin extends Plugin {
this.eventManager.setDebounceActiveLeafChangeHandler();
}
private getPathForFile(file: File) {
let path = "";
const { webUtils } = require("electron");
if (webUtils && webUtils.getPathForFile) {
path = webUtils.getPathForFile(file);
}
return path;
}
public registerHotkeyOverrides() {
//this is repeated here because the same function is called when settings is closed after hotkeys have changed
if (this.popScope) {
@@ -1825,8 +1548,8 @@ export default class ExcalidrawPlugin extends Plugin {
this.scriptEngine = null;
}
if (imageCache) {
imageCache.destroy();
if (getImageCache()) {
getImageCache().destroy();
}
this.stylesManager.destroy();
@@ -1874,7 +1597,6 @@ export default class ExcalidrawPlugin extends Plugin {
this.lastActiveExcalidrawFilePath = null;
this.settings = null;
clearMathJaxVariables();
//pluginPackages = null;
//PLUGIN_VERSION = null;
delete window.PolyBool;
@@ -1897,6 +1619,19 @@ export default class ExcalidrawPlugin extends Plugin {
const persistedSettings = stripLegacyAISettings(migratedSettings);
const decryptedSettings = decryptPersistedAPIKeys(persistedSettings);
this.settings = Object.assign({}, DEFAULT_SETTINGS, decryptedSettings);
let didSettingsMigration = false;
const settingsRecord = this.settings as unknown as Record<string, unknown>;
if (
typeof settingsRecord.iframelyAllowed === "boolean" &&
typeof this.settings.oEmbedAllowed !== "boolean"
) {
this.settings.oEmbedAllowed = settingsRecord.iframelyAllowed;
didSettingsMigration = true;
}
if ("iframelyAllowed" in settingsRecord) {
delete settingsRecord.iframelyAllowed;
didSettingsMigration = true;
}
if (!this.settings.previewImageType) {
//migration 1.9.13
if (typeof this.settings.displaySVGInPreview === "undefined") {
@@ -1913,7 +1648,7 @@ export default class ExcalidrawPlugin extends Plugin {
const shouldPersistEncryptedSettings =
JSON.stringify(encryptedPersistedSettings) !==
JSON.stringify(persistedSettings);
if (didMigrate || shouldPersistEncryptedSettings) {
if (didMigrate || didSettingsMigration || shouldPersistEncryptedSettings) {
await this.saveData(encryptedPersistedSettings);
}
if (opts.reEnableAutosave) {
@@ -1928,6 +1663,10 @@ export default class ExcalidrawPlugin extends Plugin {
await this.saveData(encryptPersistedAPIKeys(persistedSettings));
}
async onExternalSettingsChange() {
await this.loadSettings();
}
public async openSidepanel(
reveal: boolean = true,
): Promise<ExcalidrawSidepanelView | null> {
@@ -1958,7 +1697,7 @@ export default class ExcalidrawPlugin extends Plugin {
this.app.workspace.getLeavesOfType("markdown").forEach((leaf) => {
// this.app.workspace.iterateAllLeaves((leaf)=>{
const ownerDocument = DEVICE.isMobile
? document
? mainDocument
: leaf.view.containerEl.ownerDocument;
if (!ownerDocument) {
return;
@@ -1967,8 +1706,10 @@ export default class ExcalidrawPlugin extends Plugin {
return;
}
visitedDocs.add(ownerDocument);
const e = ownerDocument.createEvent("Event");
e.initEvent(RERENDER_EVENT, true, false);
const e = new CustomEvent(RERENDER_EVENT, {
bubbles: true,
cancelable: false,
});
ownerDocument
.querySelectorAll(
`.excalidraw-embedded-img${
@@ -2017,7 +1758,6 @@ export default class ExcalidrawPlugin extends Plugin {
await this.saveSettings();
new RankMessage(
this.app,
this,
filecount,
rank,
decoration,
@@ -2106,11 +1846,11 @@ export default class ExcalidrawPlugin extends Plugin {
await this.fileManager.renameEventHandler(file, oldPath);
}
public async modifyEventHandler(file: TFile) {
public async modifyEventHandler(file: TAbstractFile) {
await this.fileManager.modifyEventHandler(file);
}
public async deleteEventHandler(file: TFile) {
public async deleteEventHandler(file: TAbstractFile) {
await this.fileManager.deleteEventHandler(file);
}
@@ -2187,11 +1927,7 @@ export default class ExcalidrawPlugin extends Plugin {
switch (action) {
case "anyFile":
this.activeExcalidrawView.setCurrentPositionToCenter();
const insertFileModal = new UniversalInsertFileModal(
this,
this.activeExcalidrawView,
);
insertFileModal.open();
new UniversalInsertFileModal(this, this.activeExcalidrawView).open();
break;
case "LaTeX":
insertLaTeXToView(this.activeExcalidrawView, true);
@@ -2205,7 +1941,17 @@ export default class ExcalidrawPlugin extends Plugin {
//used by obsidianUtils in the Excalidraw Pacakge
//aweful coding, but does the job
public getLabel(key: keyof typeof en): string {
return t(key);
const localizedLabel = t(key);
if (
EXCALIDRAW_EXTERNAL_GET_LABEL_KEY_SET.has(key) &&
localizedLabel === key
) {
console.warn(
`Excalidraw localization key '${key}' is missing. Falling back to English compatibility label.`,
);
return en[key];
}
return localizedLabel;
}
public getObsidianDevice(): DeviceType {
+52 -71
View File
@@ -34,7 +34,7 @@ import { InsertImageDialog } from "../../shared/Dialogs/InsertImageDialog";
import { ImportSVGDialog } from "../../shared/Dialogs/ImportSVGDialog";
import { InsertMDDialog } from "../../shared/Dialogs/InsertMDDialog";
import { ExcalidrawAutomate } from "../../shared/ExcalidrawAutomate";
import { insertLaTeXToView, search } from "src/utils/excalidrawAutomateUtils";
import { search } from "src/utils/excalidrawAutomateUtils";
import { templatePromt } from "../../shared/Dialogs/Prompt";
import { t } from "../../lang/helpers";
import {
@@ -49,12 +49,7 @@ import {
getListOfTemplateFiles,
getURLImageExtension,
} from "../../utils/fileUtils";
import {
setLeftHandedMode,
sleep,
decompress,
getImageSize,
} from "../../utils/utils";
import { setLeftHandedMode, getImageSize } from "../../utils/utils";
import {
extractSVGPNGFileName,
getActivePDFPageNumberFromPDFView,
@@ -68,7 +63,6 @@ import {
ExcalidrawElement,
ExcalidrawEmbeddableElement,
ExcalidrawImageElement,
ExcalidrawTextElement,
FileId,
} from "@zsviczian/excalidraw/types/element/src/types";
import { ReleaseNotes } from "../../shared/Dialogs/ReleaseNotes";
@@ -77,7 +71,6 @@ import Taskbone from "../../shared/OCR/Taskbone";
import {
emulateCTRLClickForLinks,
linkClickModifierType,
PaneTarget,
} from "../../utils/modifierkeyHelper";
import { InsertPDFModal } from "../../shared/Dialogs/InsertPDFModal";
import { ExportDialog } from "../../shared/Dialogs/ExportDialog";
@@ -96,6 +89,9 @@ import { showFrameSettings } from "../../shared/Dialogs/FrameSettings";
import { insertImageToView } from "../../utils/excalidrawViewUtils";
import ExcalidrawPlugin from "src/core/main";
import { UIModeSettings } from "src/shared/Dialogs/UIModeSettings";
import { PaneTarget } from "src/types/utilTypes";
import { decompress } from "src/utils/sceneDataUtils";
import { insertLaTeXToView } from "src/utils/excalidrawViewHelpers";
declare const PLUGIN_VERSION: string;
@@ -194,7 +190,7 @@ export class CommandManager {
let folderpath = file.path;
if (file instanceof TFile) {
folderpath = normalizePath(
file.path.substr(0, file.path.lastIndexOf(file.name)),
file.path.substring(0, file.path.lastIndexOf(file.name)),
);
}
void this.plugin.createAndOpenDrawing(
@@ -351,9 +347,7 @@ export class CommandManager {
}
const els = view
.getViewSelectedElements()
.filter(
(el) => el.type === "embeddable",
) as ExcalidrawEmbeddableElement[];
.filter((el) => el.type === "embeddable");
if (els.length !== 1) {
if (checking) {
return false;
@@ -395,9 +389,7 @@ export class CommandManager {
}
const els = view
.getViewSelectedElements()
.filter(
(el) => el.type === "embeddable",
) as ExcalidrawEmbeddableElement[];
.filter((el) => el.type === "embeddable");
if (els.length === 0) {
if (checking) {
return false;
@@ -427,7 +419,7 @@ export class CommandManager {
if (!view) {
return false;
}
if (view.leaf !== this.app.workspace.activeLeaf) {
if (view.leaf !== this.app.workspace.getMostRecentLeaf()) {
return false;
}
const editor = view.editor;
@@ -728,10 +720,7 @@ export class CommandManager {
}
if (view) {
if (!this.settings.taskboneEnabled) {
new Notice(
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
4000,
);
new Notice(t("TASKBONE_NOT_ENABLED"), 4000);
return true;
}
void this.taskbone.getTextForView(view, { forceReScan: false });
@@ -751,10 +740,7 @@ export class CommandManager {
}
if (view) {
if (!this.settings.taskboneEnabled) {
new Notice(
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
4000,
);
new Notice(t("TASKBONE_NOT_ENABLED"), 4000);
return true;
}
void this.taskbone.getTextForView(view, { forceReScan: true });
@@ -774,10 +760,7 @@ export class CommandManager {
}
if (view) {
if (!this.settings.taskboneEnabled) {
new Notice(
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
4000,
);
new Notice(t("TASKBONE_NOT_ENABLED"), 4000);
return true;
}
void this.taskbone.getTextForView(view, {
@@ -944,6 +927,7 @@ export class CommandManager {
this.forceSaveCommand = this.addCommand({
id: "save",
//eslint-disable-next-line obsidianmd/commands/no-default-hotkeys
hotkeys: [{ modifiers: ["Ctrl"], key: "s" }], //See also Poposcope
name: t("FORCE_SAVE"),
checkCallback: (checking: boolean) =>
@@ -1002,21 +986,15 @@ export class CommandManager {
this.ea.setView(view);
const el = this.ea.getViewSelectedElement();
if (el.type !== "image") {
new Notice(
"Please select an image or embedded markdown document",
4000,
);
new Notice(t("DELETE_IMAGE_NOTICE"), 4000);
return true;
}
const file = this.ea.getViewFileForImageElement(el);
if (!file) {
new Notice(
"Please select an image or embedded markdown document",
4000,
);
new Notice(t("DELETE_IMAGE_NOTICE"), 4000);
return true;
}
void this.app.vault.delete(file);
void this.app.fileManager.trashFile(file);
this.ea.deleteViewElements([el]);
return true;
}
@@ -1038,8 +1016,7 @@ export class CommandManager {
if (selectedTextElements.length !== 1) {
return false;
}
const selectedTextElement =
selectedTextElements[0] as ExcalidrawTextElement;
const selectedTextElement = selectedTextElements[0];
const containerElement = (
view.getViewElements() as ExcalidrawElement[]
).find((el) => el.id === selectedTextElement.containerId);
@@ -1058,7 +1035,6 @@ export class CommandManager {
this.addCommand({
id: "insert-link",
hotkeys: [{ modifiers: ["Mod", "Shift"], key: "k" }],
name: t("INSERT_LINK"),
checkCallback: (checking: boolean) => {
if (checking) {
@@ -1070,8 +1046,9 @@ export class CommandManager {
if (view) {
this.insertLinkDialog.start(
view.file.path,
(markdownlink: string, path: string, alias: string) =>
view.addLink(markdownlink, path, alias),
(markdownlink: string, path: string, alias: string) => {
void view.addLink(markdownlink, path, alias);
},
);
return true;
}
@@ -1080,6 +1057,7 @@ export class CommandManager {
});
this.addCommand({
// eslint-disable-next-line obsidianmd/commands/no-command-in-command-id -- this is actually the command to insert a "command" into the drawing.
id: "insert-command",
name: t("INSERT_COMMAND"),
checkCallback: (checking: boolean) => {
@@ -1091,8 +1069,9 @@ export class CommandManager {
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (view) {
this.insertCommandDialog.start(
(text: string, fontFamily?: 1 | 2 | 3 | 4, save?: boolean) =>
view.addText(text, fontFamily, save),
(text: string, fontFamily?: 1 | 2 | 3 | 4, save?: boolean) => {
void view.addText(text, fontFamily, save);
},
);
return true;
}
@@ -1315,7 +1294,7 @@ export class CommandManager {
new Notice("Select a single image element and try again");
return false;
}
const el = els[0] as ExcalidrawImageElement;
const el = els[0];
const ef = view.excalidrawData.getFile(el.fileId);
if (!ef?.file) {
return false;
@@ -1385,7 +1364,7 @@ export class CommandManager {
}
void (async () => {
const el = els[0] as ExcalidrawImageElement;
const el = els[0];
const ef = view.excalidrawData.getFile(el.fileId);
if (!ef) {
await view.forceSave();
@@ -1440,7 +1419,7 @@ export class CommandManager {
}
void (async () => {
const el = els[0] as ExcalidrawImageElement;
const el = els[0];
const ef = view.excalidrawData.getFile(el.fileId);
if (!ef) {
await view.forceSave();
@@ -1482,7 +1461,7 @@ export class CommandManager {
return true;
}
const el = els[0] as ExcalidrawImageElement;
const el = els[0];
const ef = view.excalidrawData.getFile(el.fileId);
const eq = view.excalidrawData.getEquation(el.fileId);
if (!ef && !eq) {
@@ -1574,7 +1553,7 @@ export class CommandManager {
return true;
}
const embeddableEl = embeddables[0] as ExcalidrawEmbeddableElement;
const embeddableEl = embeddables[0];
const ea = new ExcalidrawAutomate(this.plugin, excalidrawView);
const view = excalidrawView.getEmbeddableLeafElementById(
embeddableEl.id,
@@ -1637,7 +1616,7 @@ export class CommandManager {
nodes: CanvasNodeLike[];
};
};
const activeView = this.app.workspace.activeLeaf?.view;
const activeView = this.app.workspace.getMostRecentLeaf()?.view;
const isCanvasViewLike = (
view: typeof activeView,
): view is CanvasViewLike =>
@@ -1699,7 +1678,7 @@ export class CommandManager {
}
if (isPDF) {
const embeddableEl = embeddables[0] as ExcalidrawEmbeddableElement;
const embeddableEl = embeddables[0];
const ea = new ExcalidrawAutomate(this.plugin, excalidrawView);
const view = excalidrawView.getEmbeddableLeafElementById(
embeddableEl.id,
@@ -1714,7 +1693,7 @@ export class CommandManager {
return;
}
const imageEl = imageEls[0] as ExcalidrawImageElement;
const imageEl = imageEls[0];
void (async () => {
let ef = excalidrawView.excalidrawData.getFile(imageEl.fileId);
@@ -1827,12 +1806,14 @@ export class CommandManager {
const replacer = (link: string, file: TFile) => {
if (node.file) {
node.file.extension === "pdf"
? node.canvas.createFileNode({
pos: { x: node.x + node.width + 10, y: node.y },
file,
})
: node.setFile(file);
if (node.file.extension === "pdf") {
node.canvas.createFileNode({
pos: { x: node.x + node.width + 10, y: node.y },
file,
});
} else {
node.setFile(file);
}
}
if (node.url) {
node.canvas.createFileNode({
@@ -1967,7 +1948,7 @@ export class CommandManager {
nodes: CanvasNodeLike[];
};
};
const activeView = this.app.workspace.activeLeaf?.view;
const activeView = this.app.workspace.getMostRecentLeaf()?.view;
const isCanvasViewLike = (
view: typeof activeView,
): view is CanvasViewLike =>
@@ -2065,9 +2046,7 @@ export class CommandManager {
}
//console.log({counter, file});
if (!newFile || !(newFile instanceof TFile)) {
new Notice(
"File not found. NewExcalidraw Drawing is taking too long to create. Please try again.",
);
new Notice(t("ANNOTATE_IMAGE_ERROR"));
return;
}
@@ -2115,12 +2094,14 @@ export class CommandManager {
const replacer = (link: string, file: TFile) => {
if (node.file) {
node.file.extension === "pdf"
? node.canvas.createFileNode({
pos: { x: node.x + node.width + 10, y: node.y },
file,
})
: node.setFile(file);
if (node.file.extension === "pdf") {
node.canvas.createFileNode({
pos: { x: node.x + node.width + 10, y: node.y },
file,
});
} else {
node.setFile(file);
}
}
if (node.url) {
node.canvas.createFileNode({
@@ -2347,7 +2328,7 @@ export class CommandManager {
name: t("INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE"),
checkCallback: (checking: boolean) => {
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (!Boolean(view)) {
if (!view) {
return false;
}
const PDFLink = this.plugin.getLastActivePDFPageLink(view.file);
@@ -2442,7 +2423,7 @@ export class CommandManager {
const fileIsExcalidraw = this.isExcalidrawFile(activeFile);
if (checking) {
if (Boolean(this.app.workspace.getActiveViewOfType(ExcalidrawView))) {
if (this.app.workspace.getActiveViewOfType(ExcalidrawView)) {
return !this.app.workspace.getActiveViewOfType(ExcalidrawView)
.compatibilityMode;
}
+68 -29
View File
@@ -9,6 +9,7 @@ import {
EventRef,
Menu,
FileView,
TAbstractFile,
} from "obsidian";
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import { getLink } from "../../utils/fileUtils";
@@ -24,11 +25,16 @@ import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import {
FRONTMATTER_KEYS,
ICON_NAME,
mainDocument,
VIEW_TYPE_EXCALIDRAW,
} from "src/constants/constants";
import ExcalidrawView from "src/view/ExcalidrawView";
import { t } from "src/lang/helpers";
import { setMobileNavbarPosition } from "src/utils/excalidrawViewUtils";
import {
getChangedTopLevelDependencyFileIDs,
setMobileNavbarPosition,
} from "src/utils/excalidrawViewUtils";
import { setStyle } from "src/utils/styleUtils";
/**
* Registers event listeners for the plugin
@@ -100,37 +106,39 @@ export class EventManager {
public async registerEvents() {
await this.plugin.awaitInit();
this.registerEvent(
this.app.workspace.on("editor-paste", this.onPasteHandler.bind(this)),
this.app.workspace.on("editor-paste", (evt, editor, info) =>
this.onPasteHandler(evt, editor, info),
),
);
this.registerEvent(
this.app.vault.on("rename", this.onRenameHandler.bind(this)),
this.app.vault.on("rename", (file, oldPath) =>
this.onRenameHandler(file, oldPath),
),
);
this.registerEvent(
this.app.vault.on("modify", this.onModifyHandler.bind(this)),
this.app.vault.on("modify", (file) => this.onModifyHandler(file)),
);
this.registerEvent(
this.app.vault.on("delete", this.onDeleteHandler.bind(this)),
this.app.vault.on("delete", (file) => this.onDeleteHandler(file)),
);
//save Excalidraw leaf and update embeds when switching to another leaf
this.registerEvent(
this.plugin.app.workspace.on(
"active-leaf-change",
this.onActiveLeafChangeHandler.bind(this),
this.plugin.app.workspace.on("active-leaf-change", (leaf) =>
this.onActiveLeafChangeHandler(leaf),
),
);
this.registerEvent(
this.app.workspace.on(
"layout-change",
this.onLayoutChangeHandler.bind(this),
this.app.workspace.on("layout-change", () =>
this.onLayoutChangeHandler(),
),
);
//File Save Trigger Handlers
//Save the drawing if the user clicks outside the Excalidraw Canvas
const onClickEventSaveActiveDrawing =
this.onClickSaveActiveDrawing.bind(this);
const onClickEventSaveActiveDrawing = (e: PointerEvent) =>
this.onClickSaveActiveDrawing(e);
this.app.workspace.containerEl.addEventListener(
"click",
onClickEventSaveActiveDrawing,
@@ -142,9 +150,8 @@ export class EventManager {
);
});
this.registerEvent(
this.app.workspace.on(
"file-menu",
this.onFileMenuSaveActiveDrawing.bind(this),
this.app.workspace.on("file-menu", () =>
this.onFileMenuSaveActiveDrawing(),
),
);
@@ -156,13 +163,20 @@ export class EventManager {
);
this.registerEvent(
this.app.workspace.on("file-menu", this.onFileMenuHandler.bind(this)),
this.app.workspace.on("file-menu", (menu, file, source, leaf) => {
if (!(file instanceof TFile)) {
return;
}
this.onFileMenuHandler(menu, file, source, leaf);
}),
);
this.plugin.registerEvent(
this.plugin.app.workspace.on(
"editor-menu",
this.onEditorMenuHandler.bind(this),
),
this.plugin.app.workspace.on("editor-menu", (menu, editor, view) => {
if (!(view instanceof MarkdownView)) {
return;
}
this.onEditorMenuHandler(menu, editor, view);
}),
);
}
@@ -199,7 +213,11 @@ export class EventManager {
if (data.startsWith(`{"type":"excalidraw/clipboard"`)) {
evt.preventDefault();
try {
const drawing = JSON.parse(data);
const drawing = JSON.parse(data) as {
type: string;
elements: ExcalidrawElement[];
};
const hasOneTextElement =
drawing.elements.filter((el: ExcalidrawElement) => el.type === "text")
.length === 1;
@@ -237,19 +255,25 @@ export class EventManager {
if (element.link) {
editorInsertText(editor, `${element.link}`);
}
} catch (_) {}
} catch (error) {
console.error(
"Error parsing pasted Excalidraw element",
this.onPasteHandler.bind(this),
error,
);
}
}
}
private onRenameHandler(file: TFile, oldPath: string) {
private onRenameHandler(file: TAbstractFile, oldPath: string) {
void this.plugin.renameEventHandler(file, oldPath);
}
private onModifyHandler(file: TFile) {
private onModifyHandler(file: TAbstractFile) {
void this.plugin.modifyEventHandler(file);
}
private onDeleteHandler(file: TFile) {
private onDeleteHandler(file: TAbstractFile) {
void this.plugin.deleteEventHandler(file);
}
@@ -262,7 +286,10 @@ export class EventManager {
//In Obsidian 1.8.x the active excalidraw leaf is obscured by an empty leaf without a parent
//This hack resolves it
if (this.app.workspace.activeLeaf === leaf && isUnwantedLeaf(leaf)) {
if (
//this.app.workspace.getMostRecentLeaf() === leaf &&
isUnwantedLeaf(leaf)
) {
leaf.detach();
return;
}
@@ -291,7 +318,9 @@ export class EventManager {
if (this.settings.overrideObsidianFontSize) {
if (leaf.view && leaf.view.getViewType() === VIEW_TYPE_EXCALIDRAW) {
document.documentElement.style.fontSize = "";
setStyle(mainDocument.documentElement, {
fontSize: "",
});
}
}
@@ -357,7 +386,17 @@ export class EventManager {
if (newActiveviewEV.activeLoader) {
return;
}
void newActiveviewEV.loadSceneFiles();
const changedDependencyFileIDs =
getChangedTopLevelDependencyFileIDs(newActiveviewEV);
if (changedDependencyFileIDs.size > 0) {
// Reload only top-level embeds whose own file changed or whose
// dependency tree contains a newer nested Excalidraw file.
newActiveviewEV.scheduleSceneFileDeferredValidation(
changedDependencyFileIDs,
false,
true,
);
}
}, 2000);
} //refresh embedded files
}
+106 -96
View File
@@ -38,7 +38,6 @@ import {
getListOfTemplateFiles,
getNewUniqueFilepath,
} from "src/utils/fileUtils";
import { PaneTarget } from "src/utils/modifierkeyHelper";
import {
getExcalidrawViews,
getNewOrAdjacentLeaf,
@@ -46,7 +45,8 @@ import {
openLeaf,
} from "src/utils/obsidianUtils";
import { errorlog, getExportTheme } from "src/utils/utils";
import { imageCache } from "src/shared/ImageCache";
import { getImageCache } from "src/shared/ImageCache";
import { PaneTarget } from "src/types/utilTypes";
export class PluginFileManager {
private plugin: ExcalidrawPlugin;
@@ -148,7 +148,7 @@ export class PluginFileManager {
errorlog({
file,
error: "new drawing not recognized as an excalidraw file",
fn: this.createDrawing,
fn: "createDrawing",
});
}
@@ -238,7 +238,7 @@ export class PluginFileManager {
} catch (e) {
errorlog({
where: "FileManager.embedDrawing",
fn: this.plugin.ea.onImageExportPathHook,
fn: "plugin.ea.onImageExportPathHook",
error: e,
});
}
@@ -390,20 +390,22 @@ export class PluginFileManager {
"my-library",
"filename, leave blank to cancel action",
);
void prompt.openAndGetValue(async (filename: string) => {
if (!filename) {
return;
}
filename = `${filename}.excalidrawlib`;
const folderpath = normalizePath(this.settings.folder);
await checkAndCreateFolder(folderpath); //create folder if it does not exist
const fname = getNewUniqueFilepath(
this.app.vault,
filename,
folderpath,
);
await this.app.vault.create(fname, this.settings.library);
new Notice(`Exported library to ${fname}`, 6000);
void prompt.openAndGetValue((filename: string) => {
void (async () => {
if (!filename) {
return;
}
filename = `${filename}.excalidrawlib`;
const folderpath = normalizePath(this.settings.folder);
await checkAndCreateFolder(folderpath); //create folder if it does not exist
const fname = getNewUniqueFilepath(
this.app.vault,
filename,
folderpath,
);
await this.app.vault.create(fname, this.settings.library);
new Notice(`Exported library to ${fname}`, 6000);
})();
});
return;
}
@@ -551,8 +553,8 @@ export class PluginFileManager {
}
if (
this.app.workspace.activeLeaf?.view instanceof ExcalidrawView &&
this.app.workspace.activeLeaf.view.file === file
this.app.workspace.getMostRecentLeaf()?.view instanceof ExcalidrawView &&
this.app.workspace.getMostRecentLeaf()?.view.file === file
) {
this.plugin.lastActiveExcalidrawFilePath = file.path;
}
@@ -586,10 +588,10 @@ export class PluginFileManager {
excalidrawFile: file,
action: "export",
}) ?? newImgPath;
} catch (e) {
} catch (e: unknown) {
errorlog({
where: "FileManager.renameEventHandler",
fn: this.plugin.ea.onImageExportPathHook,
fn: "plugin.ea.onImageExportPathHook",
error: e,
});
}
@@ -610,83 +612,91 @@ export class PluginFileManager {
});
}
public async modifyEventHandler(file: TFile) {
public async modifyEventHandler(file: TAbstractFile) {
if (!(file instanceof TFile)) {
return;
}
const excalidrawViews = getExcalidrawViews(this.app);
excalidrawViews.forEach(async (excalidrawView) => {
if (excalidrawView.semaphores?.viewunload) {
return;
}
if (
excalidrawView.file &&
(excalidrawView.file.path === file.path ||
(file.extension === "excalidraw" &&
`${file.path.substring(
0,
file.path.lastIndexOf(".excalidraw"),
)}.md` === excalidrawView.file.path))
) {
if (excalidrawView.semaphores?.preventReload) {
excalidrawView.semaphores.preventReload = false;
excalidrawViews.forEach((excalidrawView) => {
void (async () => {
if (excalidrawView.semaphores?.viewunload) {
return;
}
// Avoid synchronizing or reloading if the user hasn't interacted with the file for 5 minutes.
// This prevents complex sync issues when multiple remote changes occur outside an active collaboration session.
// The following logic handles a rare edge case where:
// 1. The user opens an Excalidraw file.
// 2. Immediately splits the view without saving Excalidraw (since no changes were made).
// 3. Switches the new split view to Markdown, edits the file, and quickly returns to Excalidraw.
// 4. The "modify" event may fire while Excalidraw is active, triggering an unwanted reload and zoom reset.
// To address this:
// - We check if the user is currently editing the Markdown version of the Excalidraw file in a split view.
// - As a heuristic, we also check for recent leaf switches.
// This is not perfectly accurate (e.g., rapid switching between views within a few seconds),
// but it is sufficient to avoid most edge cases without introducing complexity.
// Edge case impact:
// - In extremely rare situations, an update arriving within the "recent switch" timeframe (e.g., from Obsidian Sync)
// might not trigger a reload. This is unlikely and an acceptable trade-off for better user experience.
const activeView = this.app.workspace.activeLeaf.view;
const isEditingMarkdownSideInSplitView =
(activeView !== excalidrawView &&
activeView instanceof MarkdownView &&
activeView.file === excalidrawView.file) ||
(activeView === excalidrawView &&
this.plugin.isRecentSplitViewSwitch());
if (
!isEditingMarkdownSideInSplitView &&
excalidrawView.lastSaveTimestamp + 300000 < Date.now()
excalidrawView.file &&
(excalidrawView.file.path === file.path ||
(file.extension === "excalidraw" &&
`${file.path.substring(
0,
file.path.lastIndexOf(".excalidraw"),
)}.md` === excalidrawView.file.path))
) {
await excalidrawView.reload(true, excalidrawView.file);
return;
}
if (file.extension === "md") {
if (excalidrawView.semaphores?.embeddableIsEditingSelf) {
if (excalidrawView.semaphores?.preventReload) {
excalidrawView.semaphores.preventReload = false;
return;
}
const inData = new ExcalidrawData(this.plugin);
const data = await this.app.vault.read(file);
await inData.loadData(data, file, getTextMode(data));
await excalidrawView.synchronizeWithData(inData);
inData.destroy();
if (excalidrawView?.isDirty()) {
if (
excalidrawView.autosaveTimer &&
excalidrawView.autosaveFunction
) {
clearTimeout(excalidrawView.autosaveTimer);
// Avoid synchronizing or reloading if the user hasn't interacted with the file for 5 minutes.
// This prevents complex sync issues when multiple remote changes occur outside an active collaboration session.
// The following logic handles a rare edge case where:
// 1. The user opens an Excalidraw file.
// 2. Immediately splits the view without saving Excalidraw (since no changes were made).
// 3. Switches the new split view to Markdown, edits the file, and quickly returns to Excalidraw.
// 4. The "modify" event may fire while Excalidraw is active, triggering an unwanted reload and zoom reset.
// To address this:
// - We check if the user is currently editing the Markdown version of the Excalidraw file in a split view.
// - As a heuristic, we also check for recent leaf switches.
// This is not perfectly accurate (e.g., rapid switching between views within a few seconds),
// but it is sufficient to avoid most edge cases without introducing complexity.
// Edge case impact:
// - In extremely rare situations, an update arriving within the "recent switch" timeframe (e.g., from Obsidian Sync)
// might not trigger a reload. This is unlikely and an acceptable trade-off for better user experience.
const activeView = this.app.workspace.getMostRecentLeaf()?.view;
if (!activeView) {
return;
}
const isEditingMarkdownSideInSplitView =
(activeView !== excalidrawView &&
activeView instanceof MarkdownView &&
activeView.file === excalidrawView.file) ||
(activeView === excalidrawView &&
this.plugin.isRecentSplitViewSwitch());
if (
!isEditingMarkdownSideInSplitView &&
excalidrawView.lastSaveTimestamp + 300000 < Date.now()
) {
await excalidrawView.reload(true, excalidrawView.file);
return;
}
if (file.extension === "md") {
if (excalidrawView.semaphores?.embeddableIsEditingSelf) {
return;
}
if (excalidrawView.autosaveFunction) {
await excalidrawView.autosaveFunction();
const inData = new ExcalidrawData(this.plugin);
const data = await this.app.vault.read(file);
await inData.loadData(data, file, getTextMode(data));
await excalidrawView.synchronizeWithData(inData);
inData.destroy();
if (excalidrawView?.isDirty()) {
if (
excalidrawView.autosaveTimer &&
excalidrawView.autosaveFunction
) {
window.clearTimeout(excalidrawView.autosaveTimer);
}
if (excalidrawView.autosaveFunction) {
excalidrawView.autosaveFunction();
}
}
} else {
await excalidrawView.reload(true, excalidrawView.file);
}
} else {
await excalidrawView.reload(true, excalidrawView.file);
}
}
})();
});
}
@@ -694,10 +704,10 @@ export class PluginFileManager {
//this will not work in a short period when Obsidian is starting up, however
//because there is housekeeping in ImageCache at each startup to delete
//BAK files, this is not a major issue.
if (!imageCache.isReady() || !path) {
if (!getImageCache().isReady() || !path) {
return;
}
await imageCache.removeBAKFromCache(path);
await getImageCache().removeBAKFromCache(path);
}
private async moveBAKFile(oldPath: string, newPath: string) {
@@ -708,12 +718,12 @@ export class PluginFileManager {
//this will only effect a very few files, statistically unlikely to cause
//much/any real user impact.
//a proper queuing feels overkill for this.
if (!imageCache.isReady()) {
if (!getImageCache().isReady()) {
return;
}
const backup = await imageCache.getBAKFromCache(oldPath);
const backup = await getImageCache().getBAKFromCache(oldPath);
if (backup) {
await imageCache.addBAKToCache(newPath, `${backup}`);
await getImageCache().addBAKToCache(newPath, `${backup}`);
await this.removeBAKFromCache(oldPath);
}
}
@@ -723,7 +733,7 @@ export class PluginFileManager {
* @param file
* @returns
*/
public async deleteEventHandler(file: TFile) {
public async deleteEventHandler(file: TAbstractFile) {
if (!(file instanceof TFile)) {
return;
}
@@ -764,7 +774,7 @@ export class PluginFileManager {
} catch (e) {
errorlog({
where: "FileManager.deleteEventHandler",
fn: this.plugin.ea.onImageExportPathHook,
fn: "plugin.ea.onImageExportPathHook",
error: e,
});
}
@@ -776,7 +786,7 @@ export class PluginFileManager {
imgMap.forEach((imgPath: string) => {
const imgFile = this.app.vault.getFileByPath(normalizePath(imgPath));
if (imgFile) {
void this.app.vault.delete(imgFile);
void this.app.fileManager.trashFile(imgFile);
}
});
}, 500);
+160 -97
View File
@@ -6,7 +6,11 @@ import {
TFile,
Vault,
} from "obsidian";
import { DEVICE, RERENDER_EVENT } from "../../constants/constants";
import {
DEVICE,
mainDocument,
RERENDER_EVENT,
} from "../../constants/constants";
import { EmbeddedFilesLoader } from "../../shared/EmbeddedFileLoader";
import { createPNG, createSVG } from "../../utils/excalidrawAutomateUtils";
import ExcalidrawPlugin from "../main";
@@ -27,21 +31,25 @@ import {
getFileCSSClasses,
} from "../../utils/obsidianUtils";
import { linkClickModifierType } from "../../utils/modifierkeyHelper";
import { ImageKey, imageCache } from "../../shared/ImageCache";
import { ImageKey, getImageCache } from "../../shared/ImageCache";
import { FILENAMEPARTS, PreviewImageType } from "../../types/utilTypes";
import { CustomMutationObserver, DEBUGGING } from "../../utils/debugHelper";
import { getExcalidrawFileForwardLinks } from "../../utils/excalidrawViewUtils";
import { linkPrompt } from "../../shared/Dialogs/Prompt";
import { isHTMLElement } from "../../utils/typechecks";
import {
isInstanceOfHTMLElement,
isInstanceOfHTMLImageElement,
} from "../../utils/typechecks";
import { ExportSettings } from "src/types/exportUtilTypes";
import { setElementDisplay } from "src/utils/htmlUtils";
import { setStyle } from "src/utils/styleUtils";
interface imgElementAttributes {
file?: TFile;
fname: string; //Excalidraw filename
fwidth: string; //Display width of image
fheight: string; //Display height of image
style: string[]; //css style to apply to IMG element
imgstyle: string[]; //css style to apply to IMG element
}
let plugin: ExcalidrawPlugin;
@@ -116,7 +124,7 @@ const _getPNG = async ({
};
if (cacheReady) {
const src = await imageCache.getImageFromCache(cacheKey);
const src = await getImageCache().getImageFromCache(cacheKey);
//In case of PNG I cannot change the viewBox to select the area of the element
//being referenced. For PNG only the group reference works
if (src && typeof src === "string") {
@@ -170,11 +178,14 @@ const _getPNG = async ({
img.addEventListener("error", cleanup, { once: true });
}
cacheReady && imageCache.addImageToCache(cacheKey, blobUrl, png);
if (cacheReady) {
getImageCache().addImageToCache(cacheKey, blobUrl, png);
}
return img;
};
const setStyle = ({
const setImgStyle = ({
element,
imgAttributes,
onCanvas,
@@ -185,19 +196,36 @@ const setStyle = ({
onCanvas: boolean;
isNativeSVG: boolean;
}) => {
let style = "";
if (imgAttributes.fwidth) {
style = `${isNativeSVG ? "max-width:" : "max-width:100%; width:"}${imgAttributes.fwidth}${imgAttributes.fwidth.match(/\d$/) ? "px" : ""}; `; //width:100%;`; //removed !important https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/886
} else {
style = "width: fit-content;";
}
if (imgAttributes.fheight) {
style += `${imgAttributes.fwidth ? "min-" : "max-"}height:${imgAttributes.fheight}px;`;
}
if (!onCanvas) {
element.setAttribute("style", style);
const styles: Partial<CSSStyleDeclaration> = {};
// 1. Resolve Width & Max-Width
if (imgAttributes.fwidth) {
const unit = imgAttributes.fwidth.match(/\d$/) ? "px" : "";
const finalWidth = `${imgAttributes.fwidth}${unit}`;
if (isNativeSVG) {
styles.maxWidth = finalWidth;
} else {
styles.maxWidth = "100%";
styles.width = finalWidth;
}
} else {
styles.width = "fit-content";
}
// 2. Resolve Height (Min vs Max)
if (imgAttributes.fheight) {
const targetHeightProperty = imgAttributes.fwidth
? "minHeight"
: "maxHeight";
styles[targetHeightProperty] = `${imgAttributes.fheight}px`;
}
// Apply styles uniformly using the generic function
setStyle(element, styles);
}
element.classList.add(...Array.from(imgAttributes.style));
element.classList.add(...Array.from(imgAttributes.imgstyle));
if (!element.hasClass("excalidraw-embedded-img")) {
element.addClass("excalidraw-embedded-img");
}
@@ -237,7 +265,7 @@ const _getSVGIMG = async ({
};
if (cacheReady) {
const src = await imageCache.getImageFromCache(cacheKey);
const src = await getImageCache().getImageFromCache(cacheKey);
if (src && typeof src === "string") {
img.setAttribute("src", src);
return img;
@@ -329,7 +357,7 @@ const _getSVGNative = async ({
};
let maybeSVG;
if (cacheReady) {
maybeSVG = await imageCache.getImageFromCache(cacheKey);
maybeSVG = await getImageCache().getImageFromCache(cacheKey);
}
const svg =
@@ -376,8 +404,8 @@ const _getSVGNative = async ({
}
//cache SVG should have the width and height parameters and not the embedded font
if (!Boolean(maybeSVG)) {
cacheReady && imageCache.addImageToCache(cacheKey, "", svg);
if (!maybeSVG && cacheReady) {
getImageCache().addImageToCache(cacheKey, "", svg);
}
if (width && !isNaN(width)) {
@@ -413,7 +441,9 @@ const getIMG = async (
const filenameParts = getEmbeddedFilenameParts(imgAttributes.fname);
// https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/387
imgAttributes.style = imgAttributes.style.map((s) => s.replaceAll(" ", "-"));
imgAttributes.imgstyle = imgAttributes.imgstyle.map((s) =>
s.replaceAll(" ", "-"),
);
const forceTheme = hasExportTheme(plugin, file)
? getExportTheme(plugin, file, "light")
@@ -442,13 +472,18 @@ const getIMG = async (
theme ? theme === "dark" : undefined,
);
const cacheReady = imageCache.isReady();
const cacheReady = getImageCache().isReady();
await plugin.awaitInit();
switch (plugin.settings.previewImageType) {
case PreviewImageType.PNG: {
const img = createEl("img");
setStyle({ element: img, imgAttributes, onCanvas, isNativeSVG: false });
setImgStyle({
element: img,
imgAttributes,
onCanvas,
isNativeSVG: false,
});
return await _getPNG({
imgAttributes,
filenameParts,
@@ -462,7 +497,12 @@ const getIMG = async (
}
case PreviewImageType.SVGIMG: {
const img = createEl("img");
setStyle({ element: img, imgAttributes, onCanvas, isNativeSVG: false });
setImgStyle({
element: img,
imgAttributes,
onCanvas,
isNativeSVG: false,
});
return await _getSVGIMG({
filenameParts,
theme,
@@ -475,7 +515,7 @@ const getIMG = async (
}
case PreviewImageType.SVG: {
const img = createEl("div");
setStyle({ element: img, imgAttributes, onCanvas, isNativeSVG: true });
setImgStyle({ element: img, imgAttributes, onCanvas, isNativeSVG: true });
return await _getSVGNative({
filenameParts,
theme,
@@ -514,7 +554,9 @@ const addSVGToImgSrc = (
img.addEventListener("error", cleanup, { once: true });
}
cacheReady && imageCache.addImageToCache(cacheKey, blobUrl, blob);
if (cacheReady) {
getImageCache().addImageToCache(cacheKey, blobUrl, blob);
}
return img;
};
@@ -538,10 +580,10 @@ const createImgElement = async (
let timer: number;
const clickEvent = (ev: PointerEvent) => {
if (!isHTMLElement(ev.target)) {
if (!isInstanceOfHTMLElement(ev.target)) {
return;
}
const targetElement = ev.target as HTMLElement;
const targetElement = ev.target;
const containerElement = targetElement.hasClass("excalidraw-embedded-img")
? ev.target
: getParentOfClass(targetElement, "excalidraw-embedded-img");
@@ -599,7 +641,7 @@ const createImgElement = async (
} //.ctrlKey||ev.metaKey);
};
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1003
let pointerDownEvent: any;
let pointerDownEvent: PointerEvent | null = null;
const eventElement = imgOrDiv as HTMLElement;
/*plugin.settings.previewImageType === PreviewImageType.SVG
@@ -638,32 +680,36 @@ const createImgElement = async (
timer = null;
});
eventElement.addEventListener("dblclick", clickEvent);
eventElement.addEventListener(RERENDER_EVENT, async (e) => {
eventElement.addEventListener(RERENDER_EVENT, (e) => {
e.stopPropagation();
const parent = imgOrDiv.parentElement;
const imgMaxWidth = imgOrDiv.style.maxWidth;
const imgMaxHeigth = imgOrDiv.style.maxHeight;
const fileSource = imgOrDiv.getAttribute("fileSource");
const onCanvas = imgOrDiv.getAttribute("onCanvas") === "true";
const newImg = await createImgElement(
{
fname: fileSource,
fwidth: imgOrDiv.getAttribute("w"),
fheight: imgOrDiv.getAttribute("h"),
style: [...Array.from(imgOrDiv.classList)],
},
onCanvas,
);
if (!newImg) {
return;
}
parent.empty();
if (!onCanvas) {
newImg.style.maxHeight = imgMaxHeigth;
newImg.style.maxWidth = imgMaxWidth;
}
newImg.setAttribute("fileSource", fileSource);
parent.append(newImg);
void (async () => {
const parent = imgOrDiv.parentElement;
const imgMaxWidth = imgOrDiv.style.maxWidth;
const imgMaxHeigth = imgOrDiv.style.maxHeight;
const fileSource = imgOrDiv.getAttribute("fileSource");
const onCanvas = imgOrDiv.getAttribute("onCanvas") === "true";
const newImg = await createImgElement(
{
fname: fileSource,
fwidth: imgOrDiv.getAttribute("w"),
fheight: imgOrDiv.getAttribute("h"),
imgstyle: [...Array.from(imgOrDiv.classList)],
},
onCanvas,
);
if (!newImg) {
return;
}
parent.empty();
if (!onCanvas) {
setStyle(newImg, {
maxHeight: imgMaxHeigth,
maxWidth: imgMaxWidth,
});
}
newImg.setAttribute("fileSource", fileSource);
parent.append(newImg);
})();
});
const cssClasses = getFileCSSClasses(attr.file);
cssClasses.forEach((cssClass) => {
@@ -687,7 +733,7 @@ const createImageDiv = async (
onCanvas: boolean = false,
): Promise<HTMLDivElement> => {
const img = await createImgElement(attr, onCanvas);
return createDiv(attr.style.join(" "), (el) => el.append(img));
return createDiv(attr.imgstyle.join(" "), (el) => el.append(img));
};
const processReadingMode = async (
@@ -734,7 +780,7 @@ const processInternalEmbed = async (
fname: "",
fheight: "",
fwidth: "",
style: [],
imgstyle: [],
};
const src = internalEmbedEl.getAttribute("src");
@@ -755,7 +801,7 @@ const processInternalEmbed = async (
? internalEmbedEl.getAttribute("height")
: getDefaultHeight(plugin);
const alt = internalEmbedEl.getAttribute("alt");
attr.style = ["excalidraw-svg"];
attr.imgstyle = ["excalidraw-svg"];
processAltText(src.split("#")[0], alt, attr);
const fnameParts = getEmbeddedFilenameParts(src);
attr.fname =
@@ -807,15 +853,16 @@ function parseAlias(input: string): AliasParts {
const parts = input.split("|").map((part) => part.trim());
switch (parts.length) {
case 1:
case 1: {
const singleMatch = getDimensionsFromAliasString(parts[0]);
if (singleMatch) {
return singleMatch; // Return dimensions if valid
}
result.style = parts[0]; // Otherwise, return as style
break;
}
case 2:
case 2: {
const firstDim = getDimensionsFromAliasString(parts[0]);
const secondDim = getDimensionsFromAliasString(parts[1]);
@@ -832,8 +879,9 @@ function parseAlias(input: string): AliasParts {
result.style = parts[1]; // Assuming second part is style
}
break;
}
case 3:
case 3: {
const middleMatch = getDimensionsFromAliasString(parts[1]);
if (middleMatch) {
result.alias = parts[0];
@@ -845,8 +893,9 @@ function parseAlias(input: string): AliasParts {
result.style = parts[2]; // Last part is style
}
break;
}
default:
default: {
const secondValue = getDimensionsFromAliasString(parts[1]);
if (secondValue) {
result.alias = parts[0];
@@ -858,6 +907,7 @@ function parseAlias(input: string): AliasParts {
result.style = parts[parts.length - 1]; // Last part is style
}
break;
}
}
// Clean up the result to remove undefined properties
@@ -880,7 +930,7 @@ const processAltText = (
attr.fwidth = aliasParts.width ?? attr.fwidth;
attr.fheight = aliasParts.height ?? attr.fheight;
if (aliasParts.style && !aliasParts.style.startsWith(fname)) {
attr.style = [`excalidraw-svg${`-${aliasParts.style}`}`];
attr.imgstyle = [`excalidraw-svg${`-${aliasParts.style}`}`];
}
}
};
@@ -979,7 +1029,7 @@ const tmpObsidianWYSIWYG = async (
fname: ctx.sourcePath,
fheight: isPrinting ? "100%" : getDefaultHeight(plugin),
fwidth: isPrinting ? "100%" : getDefaultWidth(plugin),
style: ["excalidraw-svg"],
imgstyle: ["excalidraw-svg"],
};
attr.file = file;
@@ -997,7 +1047,7 @@ const tmpObsidianWYSIWYG = async (
//the excalidraw file in markdown preview mode
const isFrontmatterDiv = Boolean(el.querySelector(".frontmatter"));
let areaPreview = false;
if (Boolean(ctx.frontmatter)) {
if (ctx.frontmatter) {
el.empty();
} else {
//Obsidian changed this at some point from h3 to h5 and also the text...
@@ -1038,15 +1088,17 @@ const tmpObsidianWYSIWYG = async (
internalEmbedDiv.removeClass("inline-embed");
internalEmbedDiv.addClass("media-embed");
internalEmbedDiv.addClass("image-embed");
if (!onCanvas && imgDiv.firstChild instanceof HTMLElement) {
imgDiv.firstChild.style.maxHeight = "100%";
imgDiv.firstChild.style.maxWidth = null;
if (!onCanvas && isInstanceOfHTMLElement(imgDiv.firstChild)) {
setStyle(imgDiv.firstChild, {
maxHeight: "100%",
maxWidth: null,
});
}
// Resolve the cyclic size dependency by applying a CSS width and/or height
if (
!onCanvas &&
isHoverPopover &&
imgDiv.firstChild instanceof HTMLImageElement
isInstanceOfHTMLImageElement(imgDiv.firstChild)
) {
internalEmbedDiv.style.setProperty(
"--popover-width",
@@ -1056,8 +1108,10 @@ const tmpObsidianWYSIWYG = async (
"--popover-height",
`${attr.fheight}px`,
);
internalEmbedDiv.style.width = "var(--popover-width)";
internalEmbedDiv.style.height = "var(--popover-height)";
setStyle(internalEmbedDiv, {
width: "var(--popover-width)",
height: "var(--popover-height)",
});
}
internalEmbedDiv.appendChild(imgDiv.firstChild);
return;
@@ -1092,11 +1146,13 @@ const tmpObsidianWYSIWYG = async (
if (timer) {
window.clearTimeout(timer);
}
timer = window.setTimeout(async () => {
timer = window.setTimeout(() => {
timer = null;
internalEmbedDiv.empty();
const imgDiv = await processInternalEmbed(internalEmbedDiv, file);
internalEmbedDiv.appendChild(imgDiv);
void (async () => {
const imgDiv = await processInternalEmbed(internalEmbedDiv, file);
internalEmbedDiv.appendChild(imgDiv);
})();
}, 500);
};
const observer = DEBUGGING
@@ -1122,7 +1178,7 @@ export const markdownPostProcessor = async (
) => {
await plugin.awaitSettings();
const isPrinting = Boolean(
document.body.querySelectorAll("body > .print").length > 0,
mainDocument.body.querySelectorAll("body > .print").length > 0,
);
//firstElementChild: https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1956
const isFrontmatter =
@@ -1193,7 +1249,7 @@ export const markdownPostProcessor = async (
//transcluded text element or some other transcluded content inside the Excalidraw file
//in reading mode these elements should be hidden
const excalidrawFile = Boolean(
ctx.frontmatter?.hasOwnProperty("excalidraw-plugin"),
ctx.frontmatter && "excalidraw-plugin" in ctx.frontmatter,
);
if (!(isPreview || isMarkdownReadingMode || isPrinting) && excalidrawFile) {
setElementDisplay(el, "none");
@@ -1208,7 +1264,9 @@ export const markdownPostProcessor = async (
* @param e
* @returns
*/
export const hoverEvent = (e: any) => {
export const hoverEvent = (
e: MouseEvent & { linktext?: string; sourcePath?: string },
) => {
if (!e.linktext) {
plugin.hover.linkText = null;
return;
@@ -1218,7 +1276,7 @@ export const hoverEvent = (e: any) => {
};
//monitoring for div.popover.hover-popover.file-embed.is-loaded to be added to the DOM tree
const legacyExcalidrawPopoverObserverFn: MutationCallback = async (m) => {
const legacyExcalidrawPopoverObserverFn: MutationCallback = (m) => {
if (m.length === 0) {
return;
}
@@ -1273,25 +1331,30 @@ const legacyExcalidrawPopoverObserverFn: MutationCallback = async (m) => {
//this div will be on top of original DIV. By stopping the propagation of the click
//I prevent the default Obsidian feature of opening the link in the native app
const img = await getIMG({
file,
fname: file.path,
fwidth: "300",
fheight: null,
style: ["excalidraw-svg"],
});
const div = createDiv("", async (el) => {
el.appendChild(img);
el.setAttribute("src", file.path);
el.onClickEvent((ev) => {
ev.stopImmediatePropagation();
const src = el.getAttribute("src");
if (src) {
plugin.openDrawing(vault.getFileByPath(src), linkClickModifierType(ev));
} //.ctrlKey||ev.metaKey);
void (async () => {
const img = await getIMG({
file,
fname: file.path,
fwidth: "300",
fheight: null,
imgstyle: ["excalidraw-svg"],
});
});
node.appendChild(div);
const div = createDiv("", (el) => {
el.appendChild(img);
el.setAttribute("src", file.path);
el.onClickEvent((ev) => {
ev.stopImmediatePropagation();
const src = el.getAttribute("src");
if (src) {
plugin.openDrawing(
vault.getFileByPath(src),
linkClickModifierType(ev),
);
} //.ctrlKey||ev.metaKey);
});
});
node.appendChild(div);
})();
};
export const legacyExcalidrawPopoverObserver = DEBUGGING
+182
View File
@@ -0,0 +1,182 @@
import {
MarkdownView,
View,
ViewState,
ViewStateResult,
Workspace,
WorkspaceLeaf,
} from "obsidian";
import { around, dedupe } from "monkey-around";
import type ExcalidrawPlugin from "src/core/main";
import { VIEW_TYPE_EXCALIDRAW } from "src/constants/constants";
import { URLs } from "src/constants/safeUrls";
import { fileShouldDefaultAsExcalidraw } from "src/utils/fileUtils";
import { foldExcalidrawSection } from "src/utils/obsidianUtils";
import type ExcalidrawView from "src/view/ExcalidrawView";
type ViewConstructor<T extends View = View> = new (...args: unknown[]) => T;
/**
* Registers workspace monkey patches that adapt Obsidian behavior
* for Excalidraw and known plugin integrations.
*/
export class MonkeyPatchManager {
private readonly plugin: ExcalidrawPlugin;
constructor(plugin: ExcalidrawPlugin) {
this.plugin = plugin;
}
public initialize(): void {
this.patchTemplaterGetActiveViewOfType();
this.patchHoverEditorGetRoot();
this.patchWorkspaceLeafExcalidrawDefault();
}
private patchTemplaterGetActiveViewOfType(): void {
const key = URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES;
this.plugin.register(
around(Workspace.prototype, {
getActiveViewOfType(old: Workspace["getActiveViewOfType"]) {
return dedupe(key, old, function <
T extends View,
>(this: Workspace, type: ViewConstructor<T>): T | null {
const result = old.call(this, type) as T | null;
const maybeEAView = this.getMostRecentLeaf()?.view;
if (
!maybeEAView ||
maybeEAView.getViewType() !== VIEW_TYPE_EXCALIDRAW
) {
return result;
}
const stackTrace = new Error().stack ?? "";
if (!MonkeyPatchManager.isCallerFromTemplaterPlugin(stackTrace)) {
return result;
}
const leafOrNode = (
maybeEAView as ExcalidrawView
).getActiveEmbeddable();
if (leafOrNode?.node?.isEditing) {
return {
file: leafOrNode.node.file,
editor: leafOrNode.node.child.editor,
} as unknown as T;
}
return result;
});
},
}),
);
}
private patchHoverEditorGetRoot(): void {
if (this.plugin.app.plugins.plugins?.["obsidian-hover-editor"]) {
return;
}
this.plugin.register(
// Stolen from hover editor.
around(WorkspaceLeaf.prototype, {
getRoot(old: WorkspaceLeaf["getRoot"]) {
return function (
this: WorkspaceLeaf,
): ReturnType<WorkspaceLeaf["getRoot"]> {
const top = old.call(this) as WorkspaceLeaf;
return top.getRoot === this.getRoot ? top : top.getRoot();
};
},
}),
);
}
private patchWorkspaceLeafExcalidrawDefault(): void {
const plugin = this.plugin;
this.plugin.register(
around(WorkspaceLeaf.prototype, {
// Drawings can be viewed as markdown or Excalidraw, and we keep track of the mode
// while the file is open. When the file closes, we no longer need to keep track of it.
detach(next: WorkspaceLeaf["detach"]) {
return function (
this: WorkspaceLeaf,
): ReturnType<WorkspaceLeaf["detach"]> {
const state = this.view?.getState();
const stateFile =
typeof state?.file === "string" ? state.file : null;
const leafKey = this.id || stateFile;
if (leafKey && plugin.excalidrawFileModes[leafKey]) {
delete plugin.excalidrawFileModes[leafKey];
}
return next.apply(this) as ReturnType<WorkspaceLeaf["detach"]>;
};
},
setViewState(next: WorkspaceLeaf["setViewState"]) {
return function (
this: WorkspaceLeaf,
state: ViewState,
...rest: [ViewStateResult?]
): ReturnType<WorkspaceLeaf["setViewState"]> {
const filePath = state.state?.file;
const markdownViewLoaded =
plugin._loaded && // Do not force Excalidraw mode during shutdown.
state.type === "markdown" &&
typeof filePath === "string";
if (
markdownViewLoaded &&
plugin.excalidrawFileModes[this.id || filePath] !== "markdown"
) {
if (
plugin.forceToOpenInMarkdownFilepath !== filePath &&
fileShouldDefaultAsExcalidraw(filePath, plugin.app)
) {
const newState: ViewState = {
...state,
type: VIEW_TYPE_EXCALIDRAW,
};
plugin.excalidrawFileModes[filePath] = VIEW_TYPE_EXCALIDRAW;
return next.apply(this, [newState, ...rest]) as ReturnType<
WorkspaceLeaf["setViewState"]
>;
}
plugin.forceToOpenInMarkdownFilepath = null;
}
if (markdownViewLoaded) {
window.setTimeout(() => {
if (
!(this.view instanceof MarkdownView) ||
!this.view.file ||
!plugin.isExcalidrawFile(this.view.file)
) {
return;
}
foldExcalidrawSection(this.view);
}, 500);
}
return next.apply(this, [state, ...rest]) as ReturnType<
WorkspaceLeaf["setViewState"]
>;
};
},
}),
);
}
private static isCallerFromTemplaterPlugin(stackTrace: string): boolean {
const lines = stackTrace.split("\n");
for (const line of lines) {
if (line.trim().startsWith("at Templater.")) {
return true;
}
}
return false;
}
}
+22 -17
View File
@@ -1,12 +1,16 @@
import { DEBUGGING } from "src/utils/debugHelper";
import ExcalidrawPlugin from "src/core/main";
import { CustomMutationObserver } from "src/utils/debugHelper";
import { DEVICE } from "src/constants/constants";
import { DEVICE, mainDocument } from "src/constants/constants";
import {
getExcalidrawViews,
isObsidianThemeDark,
} from "src/utils/obsidianUtils";
import { App, Notice, TFile } from "obsidian";
import {
isInstanceOfDocumentFragment,
isInstanceOfElement,
} from "src/utils/typechecks";
export class ObserverManager {
private plugin: ExcalidrawPlugin;
@@ -80,15 +84,13 @@ export class ObserverManager {
return;
}
const themeObserverFn: MutationCallback = async (
mutations: MutationRecord[],
) => {
const themeObserverFn: MutationCallback = (mutations: MutationRecord[]) => {
const { matchThemeTrigger } = this.settings;
if (!matchThemeTrigger) {
return;
}
const bodyClassList = document.body.classList;
const bodyClassList = mainDocument.body.classList;
const mutation = mutations[0];
if (mutation?.oldValue === bodyClassList.value) {
return;
@@ -115,7 +117,7 @@ export class ObserverManager {
? new CustomMutationObserver(themeObserverFn, "themeObserver")
: new MutationObserver(themeObserverFn);
this.themeObserver.observe(document.body, {
this.themeObserver.observe(mainDocument.body, {
attributeOldValue: true,
attributeFilter: ["class"],
});
@@ -178,11 +180,14 @@ export class ObserverManager {
mutationsList.forEach((mutation) => {
if (mutation.type === "childList") {
mutation.addedNodes.forEach((node) => {
if (node instanceof Element || node instanceof DocumentFragment) {
if (
isInstanceOfElement(node) ||
isInstanceOfDocumentFragment(node)
) {
ensureFiletypes(node);
}
});
if (mutation.target instanceof Element) {
if (isInstanceOfElement(mutation.target)) {
// Handles folders that were collapsed/expanded without adding nodes
ensureFiletypes(mutation.target);
}
@@ -191,7 +196,7 @@ export class ObserverManager {
if (
mutation.type === "attributes" &&
mutation.target instanceof Element
isInstanceOfElement(mutation.target)
) {
ensureFiletypes(mutation.target);
}
@@ -207,7 +212,7 @@ export class ObserverManager {
const attachObserversToContainers = (): boolean => {
const containers = Array.from(
document.querySelectorAll(".nav-files-container"),
mainDocument.querySelectorAll(".nav-files-container"),
);
if (!containers.length) {
return false;
@@ -237,7 +242,7 @@ export class ObserverManager {
const added = Array.from(mutation.addedNodes ?? []);
const hasContainer = added.some(
(node) =>
node instanceof Element &&
isInstanceOfElement(node) &&
(node.matches?.(".nav-files-container") ||
node.querySelector?.(".nav-files-container")),
);
@@ -252,7 +257,7 @@ export class ObserverManager {
},
);
waitForFileExplorer.observe(document.body, {
waitForFileExplorer.observe(mainDocument.body, {
childList: true,
subtree: true,
});
@@ -276,7 +281,7 @@ export class ObserverManager {
this.removeModalContainerObserver();
}
//The user clicks settings, or "open another vault", or the command palette
const modalContainerObserverFn: MutationCallback = async (
const modalContainerObserverFn: MutationCallback = (
m: MutationRecord[],
) => {
const view = this.plugin.activeExcalidrawView;
@@ -293,7 +298,7 @@ export class ObserverManager {
const { errorMessage } = view.excalidrawAPI.getAppState();
if (!errorMessage) {
await this.plugin.activeExcalidrawView.save();
void this.plugin.activeExcalidrawView.save();
}
};
@@ -324,10 +329,10 @@ export class ObserverManager {
return;
}
const leftWorkspaceDrawer = document.querySelector<HTMLElement>(
const leftWorkspaceDrawer = mainDocument.querySelector<HTMLElement>(
".workspace .workspace-drawer.mod-left",
);
const rightWorkspaceDrawer = document.querySelector<HTMLElement>(
const rightWorkspaceDrawer = mainDocument.querySelector<HTMLElement>(
".workspace .workspace-drawer.mod-right",
);
if (!leftWorkspaceDrawer && !rightWorkspaceDrawer) {
@@ -358,7 +363,7 @@ export class ObserverManager {
const target = mutation.target as HTMLElement;
const newDisplay = target.style.display;
const oldDisplay = parseDisplay(mutation.oldValue as string);
const oldDisplay = parseDisplay(mutation.oldValue);
// Drawer finished closing: refresh to fix pointer offset after CSS transitions
if (newDisplay === "none" && oldDisplay !== "none") {
+16 -10
View File
@@ -2,6 +2,7 @@ import { WorkspaceWindow } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
import { getAllWindowDocuments } from "../../utils/obsidianUtils";
import { setStyleText } from "src/utils/htmlUtils";
import { mainDocument } from "src/constants/constants";
export let REM_VALUE = 16;
@@ -75,10 +76,12 @@ export class StylesManager {
private onWindowOpen(win: WorkspaceWindow) {
this.stylesMap.set(win.doc, {
light: document.head.querySelector(
light: mainDocument.head.querySelector(
`style[id="excalidraw-embedded-light"]`,
),
dark: document.head.querySelector(`style[id="excalidraw-embedded-dark"]`),
dark: mainDocument.head.querySelector(
`style[id="excalidraw-embedded-dark"]`,
),
});
//this.copyPropertiesToTheme(win.doc);
}
@@ -90,7 +93,7 @@ export class StylesManager {
private async harvestStyles() {
REM_VALUE = parseInt(
window
.getComputedStyle(document.body)
.getComputedStyle(mainDocument.body)
.getPropertyValue("--font-text-size")
.trim(),
);
@@ -98,8 +101,8 @@ export class StylesManager {
REM_VALUE = 16;
}
const body = document.body;
const iframe: HTMLIFrameElement = document.createElement("iframe");
const body = mainDocument.body;
const iframe: HTMLIFrameElement = mainDocument.createElement("iframe");
iframe.hidden = true;
body.appendChild(iframe);
@@ -109,13 +112,18 @@ export class StylesManager {
const iframeDoc = iframe.contentWindow.document;
const iframeWin = iframe.contentWindow;
iframeDoc.open();
iframeDoc.write(`<head>${document.head.innerHTML}</head>`);
iframeDoc.close();
iframeDoc.close(); // Closes the stream to clear out the default page skeleton
const newHead = iframeDoc.createElement("head");
Array.from(mainDocument.head.children).forEach((child) => {
newHead.appendChild(child.cloneNode(true));
});
iframeDoc.documentElement.replaceChild(newHead, iframeDoc.head);
await iframeLoadedPromise;
const iframeBody = iframe.contentWindow.document.body;
const iframeBody = iframeDoc.body;
iframeBody.setAttribute("style", body.getAttribute("style"));
iframeBody.setAttribute("class", body.getAttribute("class"));
@@ -161,7 +169,6 @@ export class StylesManager {
);
} else {
const lightStyleTag = doc.createElement("style");
lightStyleTag.type = "text/css";
lightStyleTag.setAttribute("id", "excalidraw-embedded-light");
setStyleText(
lightStyleTag,
@@ -170,7 +177,6 @@ export class StylesManager {
doc.head.appendChild(lightStyleTag);
const darkStyleTag = doc.createElement("style");
darkStyleTag.type = "text/css";
darkStyleTag.setAttribute("id", "excalidraw-embedded-dark");
setStyleText(
darkStyleTag,
+239 -122
View File
@@ -12,6 +12,7 @@ import {
import {
GITHUB_RELEASES,
LOGO_EXCALIDRAW_MASTERY,
mainDocument,
setRootElementSize,
} from "src/constants/constants";
import { t } from "src/lang/helpers";
@@ -28,7 +29,7 @@ import {
import { PENS } from "src/utils/pens";
import { addYouTubeThumbnail, fragWithHTML } from "src/utils/utils";
import { setElementIconAndText, setSanitizedHtml } from "src/utils/htmlUtils";
import { imageCache } from "src/shared/ImageCache";
import { getImageCache } from "src/shared/ImageCache";
import { MultiOptionConfirmationPrompt } from "src/shared/Dialogs/Prompt";
import { EmbeddableMDCustomProps } from "src/shared/Dialogs/EmbeddableSettings";
import { EmbeddalbeMDFileCustomDataSettingsComponent } from "src/shared/Dialogs/EmbeddableMDFileCustomDataSettingsComponent";
@@ -64,10 +65,15 @@ import {
} from "src/types/AIUtilTypes";
import { AIProviderProfileModal } from "src/shared/Dialogs/AIProviderProfileModal";
import { AIModelConfigModal } from "src/shared/Dialogs/AIModelConfigModal";
import { AIUsageModal } from "src/shared/Dialogs/AIUsageModal";
import { getAIUsage, formatAIUsageLabel } from "src/utils/AIUtils";
import { decryptProviderProfiles } from "src/utils/settingsKeyObfuscation";
import { getGeminiSupportedSizes } from "src/utils/geminiImageModelUtils";
import { URLs } from "src/constants/safeUrls";
import { hideElement, setStyle, showElement } from "src/utils/styleUtils";
export interface ExcalidrawSettings {
showTabTitlebarButtons: boolean;
copyLinkToElemenetAnchorTo100: boolean;
copyFrameLinkByName: boolean;
disableDoubleClickTextEditing: boolean;
@@ -154,7 +160,7 @@ export interface ExcalidrawSettings {
pageTransclusionCharLimit: number;
wordWrappingDefault: number;
removeTransclusionQuoteSigns: boolean;
iframelyAllowed: boolean;
oEmbedAllowed: boolean;
pngExportScale: number;
exportWithTheme: boolean;
exportWithBackground: boolean;
@@ -168,6 +174,10 @@ export interface ExcalidrawSettings {
embedType: "excalidraw" | "PNG" | "SVG";
embedMarkdownCommentLinks: boolean;
embedWikiLink: boolean;
/**
* If true, embed a placeholder image when no drawing is present. If false, do not embed any image.
*/
embedPlaceholderImage: boolean;
syncExcalidraw: boolean;
compatibilityMode: boolean;
experimentalFileType: boolean;
@@ -181,6 +191,7 @@ export interface ExcalidrawSettings {
zoteroCompatibility: boolean;
fieldSuggester: boolean;
enableOnloadScripts: boolean;
enableCommandLinks: boolean;
//loadCount: number; //version 1.2 migration counter
drawingOpenCount: number;
library: string;
@@ -197,7 +208,7 @@ export interface ExcalidrawSettings {
mdCSS: string;
scriptEngineSettings: {
[key: string]: {
[key: string]: ScriptSettingValue;
[key: string]: ScriptSettingValue | string | number | boolean;
};
};
previousRelease: string;
@@ -330,17 +341,23 @@ const KNOWN_AI_IMAGE_MODEL_CAPABILITIES: Record<
supportsMaskImageEdits: true,
},
"gemini-2.5-flash-image": {
supportedSizes: ["1024x1024"],
supportedSizes: getGeminiSupportedSizes("google", "gemini-2.5-flash-image"),
supportsPromptImageTransforms: true,
supportsMaskImageEdits: false,
},
"gemini-3.1-flash-image-preview": {
supportedSizes: ["1024x1024"],
supportedSizes: getGeminiSupportedSizes(
"google",
"gemini-3.1-flash-image-preview",
),
supportsPromptImageTransforms: true,
supportsMaskImageEdits: false,
},
"gemini-3-pro-image-preview": {
supportedSizes: ["1024x1024"],
supportedSizes: getGeminiSupportedSizes(
"google",
"gemini-3-pro-image-preview",
),
supportsPromptImageTransforms: true,
supportsMaskImageEdits: false,
},
@@ -540,6 +557,7 @@ export const cloneModelConfigs = <TConfig extends AIModelConfig>(
) as Record<string, TConfig>;
export const DEFAULT_SETTINGS: ExcalidrawSettings = {
showTabTitlebarButtons: true,
copyLinkToElemenetAnchorTo100: false,
copyFrameLinkByName: false,
disableDoubleClickTextEditing: false,
@@ -608,8 +626,8 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
zoomStep: 0.05,
zoomMin: 0.1,
zoomMax: 30,
linkPrefix: "📍",
urlPrefix: "🌐",
linkPrefix: "",
urlPrefix: "",
parseTODO: false,
todo: "☐",
done: "🗹",
@@ -626,7 +644,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
pageTransclusionCharLimit: 200,
wordWrappingDefault: 0,
removeTransclusionQuoteSigns: true,
iframelyAllowed: false,
oEmbedAllowed: false,
pngExportScale: 1,
exportWithTheme: true,
exportWithBackground: true,
@@ -640,6 +658,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
embedType: "excalidraw",
embedMarkdownCommentLinks: true,
embedWikiLink: true,
embedPlaceholderImage: true,
syncExcalidraw: false,
experimentalFileType: false,
experimentalFileTag: "✏️",
@@ -652,6 +671,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
zoteroCompatibility: false,
fieldSuggester: true,
enableOnloadScripts: false,
enableCommandLinks: false,
compatibilityMode: false,
//loadCount: 0,
drawingOpenCount: 0,
@@ -668,7 +688,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
//fixInfinitePreviewLoop: true,
mdSVGwidth: 500,
mdSVGmaxHeight: 800,
mdFont: "Virgil",
mdFont: "Cascadia",
mdFontColor: "Black",
mdBorderColor: "Black",
mdCSS: "",
@@ -1213,34 +1233,38 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}
}
async hide() {
hide() {
this.detachSettingsFocusoutHandler();
if (this.plugin.settings.overrideObsidianFontSize) {
document.documentElement.style.fontSize = "";
setStyle(mainDocument.documentElement, { fontSize: "" });
setRootElementSize(16);
} else if (!document.documentElement.style.fontSize) {
document.documentElement.style.fontSize = getComputedStyle(
document.body,
).getPropertyValue("--font-text-size");
} else if (!mainDocument.documentElement.style.fontSize) {
setStyle(mainDocument.documentElement, {
fontSize: getComputedStyle(mainDocument.body).getPropertyValue(
"--font-text-size",
),
});
setRootElementSize();
}
await this.persistDirtySettings();
await this.applyPendingActions();
this.hotkeyEditor.unload();
if (this.hotkeyEditor.isDirty) {
this.plugin.registerHotkeyOverrides();
}
this.plugin.scriptEngine.updateScriptPath();
void (async () => {
void (await this.persistDirtySettings());
void (await this.applyPendingActions());
this.hotkeyEditor.unload();
if (this.hotkeyEditor.isDirty) {
this.plugin.registerHotkeyOverrides();
}
this.plugin.scriptEngine.updateScriptPath();
})();
/* if(this.reloadMathJax) {
this.plugin.loadMathJax();
}*/
}
async display() {
display() {
let detailsEl: HTMLElement;
await this.plugin.loadSettings(); //in case sync loaded changed settings in the background
//await this.plugin.loadSettings(); //in case sync loaded changed settings in the background
this.settingsDirty = false;
this.requestEmbedUpdate = false;
this.requestReloadDrawings = false;
@@ -1295,7 +1319,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
"span",
{
cls: "excalidraw-mastery-promo__summary-title",
text: "Excalidraw Mastery",
text: t("EXCALIDRAW_MASTERY"),
},
);
const excalidrawMasterySummaryState = excalidrawMasterySummary.createEl(
@@ -1487,7 +1511,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("FOLDER_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: Excalidraw")
.setPlaceholder(t("FOLDER_PLACEHOLDER"))
.setValue(this.plugin.settings.folder)
.onChange(async (value) => {
this.plugin.settings.folder = value;
@@ -1512,7 +1536,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("CROP_FOLDER_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: Excalidraw/Cropped")
.setPlaceholder(t("CROP_FOLDER_PLACEHOLDER"))
.setValue(this.plugin.settings.cropFolder)
.onChange(async (value) => {
this.plugin.settings.cropFolder = value;
@@ -1525,7 +1549,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("ANNOTATE_FOLDER_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: Excalidraw/Annotations")
.setPlaceholder(t("ANNOTATE_FOLDER_PLACEHOLDER"))
.setValue(this.plugin.settings.annotateFolder)
.onChange(async (value) => {
this.plugin.settings.annotateFolder = value;
@@ -1538,7 +1562,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("TEMPLATE_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: Excalidraw/Template")
.setPlaceholder(t("TEMPLATE_PLACEHOLDER"))
.setValue(this.plugin.settings.templateFilePath)
.onChange(async (value) => {
this.plugin.settings.templateFilePath = value;
@@ -1552,7 +1576,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("SCRIPT_FOLDER_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: Excalidraw/Scripts")
.setPlaceholder(t("SCRIPT_FOLDER_PLACEHOLDER"))
.setValue(this.plugin.settings.scriptFolderPath)
.onChange(async (value) => {
this.plugin.settings.scriptFolderPath = value;
@@ -1664,7 +1688,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("FILENAME_PREFIX_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: Drawing ")
.setPlaceholder(t("FILENAME_PREFIX_PLACEHOLDER"))
.setValue(this.plugin.settings.drawingFilenamePrefix)
.onChange(async (value) => {
this.plugin.settings.drawingFilenamePrefix = value.replaceAll(
@@ -1744,7 +1768,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("CROP_PREFIX_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: cropped_")
.setPlaceholder(t("CROP_PREFIX_PLACEHOLDER"))
.setValue(this.plugin.settings.cropPrefix)
.onChange(async (value) => {
this.plugin.settings.cropPrefix = value.replaceAll(
@@ -1761,7 +1785,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("CROP_SUFFIX_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: _cropped")
.setPlaceholder(t("CROP_SUFFIX_PLACEHOLDER"))
.setValue(this.plugin.settings.cropSuffix)
.onChange(async (value) => {
this.plugin.settings.cropSuffix = value.replaceAll(
@@ -1778,7 +1802,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("ANNOTATE_PREFIX_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: annotated_")
.setPlaceholder(t("ANNOTATE_PREFIX_PLACEHOLDER"))
.setValue(this.plugin.settings.annotatePrefix)
.onChange(async (value) => {
this.plugin.settings.annotatePrefix = value.replaceAll(
@@ -1795,7 +1819,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("ANNOTATE_SUFFIX_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: _annotated")
.setPlaceholder(t("ANNOTATE_SUFFIX_PLACEHOLDER"))
.setValue(this.plugin.settings.annotateSuffix)
.onChange(async (value) => {
this.plugin.settings.annotateSuffix = value.replaceAll(
@@ -1840,12 +1864,36 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
toggle
.setValue(this.plugin.settings.aiEnabled ?? true)
.onChange(async (value) => {
aiEl.style.display = value ? "block" : "none";
if (value) {
showElement(aiEl);
} else {
hideElement(aiEl);
}
this.plugin.settings.aiEnabled = value;
this.applySettingsUpdate();
}),
);
detailsEl = detailsEl.createDiv();
const aiEl = detailsEl;
if (!(this.plugin.settings.aiEnabled ?? true)) {
hideElement(detailsEl);
}
new Setting(detailsEl)
.setName(t("AI_USAGE_SETTINGS_BUTTON_NAME"))
.setDesc(t("AI_USAGE_SETTINGS_BUTTON_DESC"))
.addButton((button) => {
const updateLabel = () => {
button.setButtonText(formatAIUsageLabel());
};
updateLabel();
button.onClick(() => {
updateLabel();
new AIUsageModal(this.app, getAIUsage()).open();
});
});
new Setting(detailsEl)
.setName(t("AI_VERBOSE_LOGGING_NAME"))
.setDesc(fragWithHTML(t("AI_VERBOSE_LOGGING_DESC")))
@@ -1858,12 +1906,6 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}),
);
detailsEl = detailsEl.createDiv();
const aiEl = detailsEl;
if (!(this.plugin.settings.aiEnabled ?? true)) {
detailsEl.style.display = "none";
}
let selectedProviderProfile =
Object.keys(this.plugin.settings.aiProviderProfiles ?? {})[0] || "OpenAI";
let selectedTextModelConfig =
@@ -1947,10 +1989,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
),
);
if (kind === "text") {
this.plugin.settings.aiTextModelConfigs = sorted as Record<
string,
AIModelConfig
>;
this.plugin.settings.aiTextModelConfigs = sorted;
}
if (kind === "image") {
this.plugin.settings.aiImageModelConfigs = sorted as Record<
@@ -2063,10 +2102,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.plugin.settings.aiDefaultMultimodalModel = nextModelId;
}
if (kind === "image") {
setModelConfigs(
kind,
updatedConfigs as Record<string, AIImageModelConfig>,
);
setModelConfigs(kind, updatedConfigs);
selectedImageModelConfig = nextModelId;
this.plugin.settings.aiDefaultImageGenerationModel = nextModelId;
}
@@ -2076,6 +2112,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
{
kind,
providerIds: Object.keys(getProviderProfiles()),
providerProfiles: getProviderProfiles(),
previousModelId: modelId,
initialModelId: modelId,
initialConfig: modelId ? configs[modelId] : undefined,
@@ -2182,9 +2219,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
left.localeCompare(right),
);
const selectedValue = getValidSelection(kind);
const config = configs[selectedValue] as
| AIModelConfig
| AIImageModelConfig;
const config = configs[selectedValue];
const providerProfile = getProviderProfiles()[config.providerId];
const apiStatus = getApiStatusMarkup(
Boolean(providerProfile?.apiKey?.trim()),
@@ -2193,6 +2228,10 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
value
? t("AI_IMAGE_MODEL_CAPABILITIES_EDITS_YES")
: t("AI_IMAGE_MODEL_CAPABILITIES_EDITS_NO");
const supportedSizes =
kind === "image"
? getGeminiSupportedSizes(providerProfile?.provider, config.model)
: [];
const description =
kind === "image"
@@ -2208,7 +2247,10 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.replace("{{model}}", config.model)
.replace(
"{{sizes}}",
(config as AIImageModelConfig).supportedSizes.join(", "),
(supportedSizes.length > 0
? supportedSizes
: (config as AIImageModelConfig).supportedSizes
).join(", "),
)
.replace(
"{{supportsPromptImageTransforms}}",
@@ -2250,8 +2292,10 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
)
.setDesc(fragWithHTML(description))
.addDropdown((dropdown) => {
optionValues.forEach((value) => dropdown.addOption(value, value));
return dropdown.setValue(selectedValue).onChange(async (value) => {
optionValues.forEach((value) => {
void dropdown.addOption(value, value);
});
return dropdown.setValue(selectedValue).onChange((value) => {
if (kind === "text") {
selectedTextModelConfig = value;
this.plugin.settings.aiDefaultTextModel = value;
@@ -2356,7 +2400,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
text
.setPlaceholder(placeholder)
.setValue(getter().toString())
.onChange(async (value) => {
.onChange((value) => {
const intVal = parseInt(value, 10);
if (isNaN(intVal) && value !== "") {
text.setValue(getter().toString());
@@ -2472,6 +2516,24 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
cls: "excalidraw-setting-h3",
});
new Setting(detailsEl)
.setName(t("SHOW_TAB_TITLEBAR_BUTTONS"))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.showTabTitlebarButtons)
.onChange(async (value) => {
this.plugin.settings.showTabTitlebarButtons = value;
this.applySettingsUpdate();
getExcalidrawViews(this.app, true).forEach((excalidrawView) => {
if (value) {
excalidrawView.addTabTitlebarButtons();
} else {
excalidrawView.removeTabTitlebarButtons();
}
});
}),
);
new UIModeSettingsComponent(detailsEl, this.plugin.settings, this.app, () =>
this.applySettingsUpdate(),
).render();
@@ -2489,7 +2551,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.hotkeyEditor = new HotkeyEditor(
detailsEl,
this.plugin.settings,
this.applySettingsUpdate,
(x: boolean = false) => this.applySettingsUpdate(x),
);
this.hotkeyEditor.onload();
@@ -2516,9 +2578,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("DYNAMICSTYLE_DESC")))
.addDropdown((dropdown) =>
dropdown
.addOption("none", "Dynamic Styling OFF")
.addOption("colorful", "Match color")
.addOption("gray", "Gray, match tone")
.addOption("none", t("DYNAMICSTYLE_OPTION_NONE"))
.addOption("colorful", t("DYNAMICSTYLE_OPTION_COLORFUL"))
.addOption("gray", t("DYNAMICSTYLE_OPTION_GRAY"))
.setValue(this.plugin.settings.dynamicStyling)
.onChange(async (value) => {
this.requestUpdateDynamicStyling = true;
@@ -2587,10 +2649,10 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("DEFAULT_OPEN_MODE_DESC")))
.addDropdown((dropdown) =>
dropdown
.addOption("normal", "Always in normal-mode")
.addOption("zen", "Always in zen-mode")
.addOption("view", "Always in view-mode")
.addOption("view-mobile", "Usually normal, but view-mode on Phone")
.addOption("normal", t("DEFAULT_OPEN_MODE_OPTION_NORMAL"))
.addOption("zen", t("DEFAULT_OPEN_MODE_OPTION_ZEN"))
.addOption("view", t("DEFAULT_OPEN_MODE_OPTION_VIEW"))
.addOption("view-mobile", t("DEFAULT_OPEN_MODE_OPTION_VIEW_MOBILE"))
.setValue(this.plugin.settings.defaultMode)
.onChange(async (value) => {
this.plugin.settings.defaultMode = value;
@@ -2751,9 +2813,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("DEFAULT_PEN_MODE_DESC")))
.addDropdown((dropdown) =>
dropdown
.addOption("never", "Never")
.addOption("mobile", "On Obsidian Mobile")
.addOption("always", "Always")
.addOption("never", t("DEFAULT_PEN_MODE_OPTION_NEVER"))
.addOption("mobile", t("DEFAULT_PEN_MODE_OPTION_MOBILE"))
.addOption("always", t("DEFAULT_PEN_MODE_OPTION_ALWAYS"))
.setValue(this.plugin.settings.defaultPenMode)
.onChange(async (value: "never" | "always" | "mobile") => {
this.plugin.settings.defaultPenMode = value;
@@ -2868,7 +2930,11 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setValue(this.plugin.settings.gridSettings.DYNAMIC_COLOR)
.onChange(async (value) => {
this.plugin.settings.gridSettings.DYNAMIC_COLOR = value;
gridColorSection.style.display = value ? "none" : "block";
if (value) {
hideElement(gridColorSection);
} else {
showElement(gridColorSection);
}
this.applySettingsUpdate();
updateGridColor();
}),
@@ -2876,10 +2942,11 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
// Create a div to contain color and opacity settings
const gridColorSection = detailsEl.createDiv();
gridColorSection.style.display = this.plugin.settings.gridSettings
.DYNAMIC_COLOR
? "none"
: "block";
if (this.plugin.settings.gridSettings.DYNAMIC_COLOR) {
hideElement(gridColorSection);
} else {
showElement(gridColorSection);
}
// Grid color picker
new Setting(gridColorSection)
@@ -3007,7 +3074,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
new ModifierKeySettingsComponent(
detailsEl,
this.plugin.settings.modifierKeyConfig,
this.applySettingsUpdate.bind(this),
() => this.applySettingsUpdate(),
).render();
// ------------------------------------------------
@@ -3299,9 +3366,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("GET_URL_TITLE_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.iframelyAllowed)
.setValue(this.plugin.settings.oEmbedAllowed)
.onChange(async (value) => {
this.plugin.settings.iframelyAllowed = value;
this.plugin.settings.oEmbedAllowed = value;
this.applySettingsUpdate();
}),
);
@@ -3326,9 +3393,18 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("EMBED_PREVIEW_IMAGETYPE_DESC")))
.addDropdown((dropdown) =>
dropdown
.addOption(PreviewImageType.PNG, "PNG Image")
.addOption(PreviewImageType.SVG, "Native SVG")
.addOption(PreviewImageType.SVGIMG, "SVG Image")
.addOption(
PreviewImageType.PNG,
t("EMBED_PREVIEW_IMAGETYPE_OPTION_PNG"),
)
.addOption(
PreviewImageType.SVG,
t("EMBED_PREVIEW_IMAGETYPE_OPTION_SVG"),
)
.addOption(
PreviewImageType.SVGIMG,
t("EMBED_PREVIEW_IMAGETYPE_OPTION_SVGIMG"),
)
.setValue(this.plugin.settings.previewImageType)
.onChange((value) => {
this.plugin.settings.previewImageType = value as PreviewImageType;
@@ -3345,7 +3421,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("EMBED_TYPE_DESC")))
.addDropdown(async (d: DropdownComponent) => {
dropdown = d;
dropdown.addOption("excalidraw", "excalidraw");
dropdown.addOption("excalidraw", "Excalidraw");
if (this.plugin.settings.autoexportPNG) {
dropdown.addOption("PNG", "PNG");
} else if (this.plugin.settings.embedType === "PNG") {
@@ -3363,8 +3439,11 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.onChange(async (value) => {
this.plugin.settings.embedType =
value as typeof this.plugin.settings.embedType;
embedComment.settingEl.style.display =
value === "excalidraw" ? "none" : "";
if (value === "excalidraw") {
hideElement(embedComment.settingEl);
} else {
showElement(embedComment.settingEl);
}
this.applySettingsUpdate();
});
});
@@ -3381,8 +3460,11 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}),
);
embedComment.settingEl.style.display =
this.plugin.settings.embedType === "excalidraw" ? "none" : "";
if (this.plugin.settings.embedType === "excalidraw") {
hideElement(embedComment.settingEl);
} else {
showElement(embedComment.settingEl);
}
new Setting(detailsEl)
.setName(t("EMBED_WIKILINK_NAME"))
@@ -3396,6 +3478,18 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}),
);
// Embed placeholder image setting
new Setting(detailsEl)
.setName(t("EMBED_PLACEHOLDER_NAME"))
.setDesc(fragWithHTML(t("EMBED_PLACEHOLDER_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.embedPlaceholderImage)
.onChange(async (value) => {
this.plugin.settings.embedPlaceholderImage = value;
this.applySettingsUpdate();
}),
);
detailsEl = embedDetailsEl.createEl("details");
detailsEl.createEl("summary", {
text: t("EMBED_CANVAS"),
@@ -3473,7 +3567,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setName(t("EMBED_IMAGE_CACHE_CLEAR"))
.addButton((button) =>
button.setButtonText(t("EMBED_IMAGE_CACHE_CLEAR")).onClick(() => {
void imageCache.clearImageCache();
void getImageCache().clearImageCache();
}),
);
new Setting(detailsEl)
@@ -3486,7 +3580,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
);
void confirmationPrompt.waitForClose.then((confirmed) => {
if (confirmed) {
void imageCache.clearBackupCache();
void getImageCache().clearBackupCache();
}
});
}),
@@ -3547,7 +3641,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("EMBED_WIDTH_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: 400")
.setPlaceholder("400")
.setValue(this.plugin.settings.width)
.onChange(async (value) => {
this.plugin.settings.width = value;
@@ -3561,7 +3655,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("EMBED_HEIGHT_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: 400")
.setPlaceholder("400")
.setValue(this.plugin.settings.height)
.onChange(async (value) => {
this.plugin.settings.height = value;
@@ -3676,7 +3770,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
const removeDropdownOption = (opt: string) => {
let i = 0;
for (i = 0; i < dropdown.selectEl.options.length; i++) {
if ((dropdown.selectEl.item(i) as HTMLOptionElement).label === opt) {
if (dropdown.selectEl.item(i).label === opt) {
dropdown.selectEl.item(i).remove();
}
}
@@ -3869,9 +3963,12 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setName(t("MD_DEFAULT_FONT_NAME"))
.setDesc(fragWithHTML(t("MD_DEFAULT_FONT_DESC")))
.addDropdown(async (d: DropdownComponent) => {
//I do not know why Lilita One and Nunito do not work. The font string is there, but it is not rendered
d.addOption("Virgil", "Virgil");
d.addOption("Cascadia", "Cascadia");
d.addOption("Assistant", "Assistant");
d.addOption("Excalifont", "Excalifont");
d.addOption("Comic Shanns", "Comic Shanns");
d.addOption("Liberation Sans", "Liberation Sans");
this.app.vault
.getFiles()
.filter(
@@ -3894,7 +3991,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("MD_DEFAULT_COLOR_DESC")))
.addText((text) =>
text
.setPlaceholder("CSS Color-name|RGB-HEX")
.setPlaceholder(t("DEFAULT_COLOR_MD_DESC"))
.setValue(this.plugin.settings.mdFontColor)
.onChange((value) => {
this.requestReloadDrawings = true;
@@ -3908,7 +4005,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("MD_DEFAULT_BORDER_COLOR_DESC")))
.addText((text) =>
text
.setPlaceholder("CSS Color-name|RGB-HEX")
.setPlaceholder(t("DEFAULT_COLOR_MD_DESC"))
.setValue(this.plugin.settings.mdBorderColor)
.onChange((value) => {
this.requestReloadDrawings = true;
@@ -3922,7 +4019,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("MD_CSS_DESC")))
.addText((text) =>
text
.setPlaceholder("filename of css file in vault")
.setPlaceholder(t("MD_CSS_PLACEHOLDER"))
.setValue(this.plugin.settings.mdCSS)
.onChange((value) => {
this.requestReloadDrawings = true;
@@ -4072,7 +4169,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("CJK_ASSETS_FOLDER_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: Excalidraw/FontAssets")
.setPlaceholder(t("CJK_ASSETS_FOLDER_PLACEHOLDER"))
.setValue(this.plugin.settings.fontAssetsPath)
.onChange(async (value) => {
this.plugin.settings.fontAssetsPath = value;
@@ -4304,6 +4401,18 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}),
);
new Setting(detailsEl)
.setName(t("ENABLE_COMMAND_LINKS_NAME"))
.setDesc(fragWithHTML(t("ENABLE_COMMAND_LINKS_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.enableCommandLinks)
.onChange(async (value) => {
this.plugin.settings.enableCommandLinks = value;
this.applySettingsUpdate();
}),
);
//STARTUP_SCRIPT_NAME
//STARTUP_SCRIPT_BUTTON
let startupScriptPathText: TextComponent;
@@ -4368,7 +4477,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}
startupScriptButton.setButtonText(t("STARTUP_SCRIPT_BUTTON_OPEN"));
await this.app.workspace.openLinkText(f.path, "", true);
await this.hide();
this.hide();
});
});
@@ -4472,7 +4581,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
const textAreaHeight = (
scriptName: string,
variableName: string,
): any => {
): number | undefined | null => {
const variable =
this.plugin.settings.scriptEngineSettings[scriptName][variableName];
switch (typeof variable) {
@@ -4483,7 +4592,10 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}
};
const getValue = (scriptName: string, variableName: string): any => {
const getValue = (
scriptName: string,
variableName: string,
): string | number | boolean | undefined => {
const variable =
this.plugin.settings.scriptEngineSettings[scriptName][variableName];
switch (typeof variable) {
@@ -4497,7 +4609,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
const setValue = (
scriptName: string,
variableName: string,
value: any,
value: string | number | boolean | undefined,
) => {
switch (
typeof this.plugin.settings.scriptEngineSettings[scriptName][
@@ -4526,7 +4638,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(description ?? ""))
.addToggle((toggle) =>
toggle
.setValue(getValue(scriptName, variableName))
.setValue(getValue(scriptName, variableName) as boolean)
.onChange(async (value) => {
setValue(scriptName, variableName, value);
this.applySettingsUpdate();
@@ -4538,7 +4650,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
scriptName: string,
variableName: string,
description?: string,
valueset?: any,
valueset?: string[],
) => {
if (
valueset &&
@@ -4549,11 +4661,11 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setName(variableName)
.setDesc(fragWithHTML(description ?? ""))
.addDropdown((dropdown) => {
valueset.forEach((val: any) =>
dropdown.addOption(val.toString(), val.toString()),
);
valueset.forEach((val: string) => {
void dropdown.addOption(val.toString(), val.toString());
});
dropdown
.setValue(getValue(scriptName, variableName))
.setValue(getValue(scriptName, variableName) as string)
.onChange(async (value) => {
setValue(scriptName, variableName, value);
this.applySettingsUpdate();
@@ -4564,14 +4676,15 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setName(variableName)
.setDesc(fragWithHTML(description ?? ""))
.addTextArea((text) => {
text.inputEl.style.minHeight = textAreaHeight(
scriptName,
variableName,
);
text.inputEl.style.minWidth = "400px";
text.inputEl.style.width = "100%";
setStyle(text.inputEl, {
minHeight: textAreaHeight(scriptName, variableName)
? `${textAreaHeight(scriptName, variableName)}px`
: "",
minWidth: "400px",
width: "100%",
});
text
.setValue(getValue(scriptName, variableName))
.setValue(getValue(scriptName, variableName) as string)
.onChange(async (value) => {
setValue(scriptName, variableName, value);
this.applySettingsUpdate();
@@ -4583,7 +4696,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(description ?? ""))
.addText((text) =>
text
.setValue(getValue(scriptName, variableName))
.setValue(getValue(scriptName, variableName) as string)
.onChange(async (value) => {
setValue(scriptName, variableName, value);
this.applySettingsUpdate();
@@ -4639,7 +4752,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
values.length === 0 ||
(values.length > 0 &&
values
.map((val: any): number => (val.hidden ? 0 : 1))
.map((val: ScriptSettingValue): number => (val.hidden ? 0 : 1))
.reduce((prev, cur) => prev + cur) === 0)
) {
return;
@@ -4652,33 +4765,37 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
Object.keys(settings).forEach((variableName) => {
const variable = settings[variableName];
const item = variable.value ?? variable;
const scriptSetting =
typeof variable === "object" && variable !== null
? variable
: null;
const item = scriptSetting?.value ?? variable;
switch (typeof item) {
case "boolean":
if (!variable.hidden) {
if (!scriptSetting?.hidden) {
addBooleanSetting(
scriptName,
variableName,
variable.description,
scriptSetting?.description,
);
}
break;
case "string":
if (!variable.hidden) {
if (!scriptSetting?.hidden) {
addStringSetting(
scriptName,
variableName,
variable.description,
variable.valueset,
scriptSetting?.description,
scriptSetting?.valueset,
);
}
break;
case "number":
if (!variable.hidden) {
if (!scriptSetting?.hidden) {
addNumberSetting(
scriptName,
variableName,
variable.description,
scriptSetting?.description,
);
}
break;
+76 -91
View File
@@ -1,126 +1,111 @@
//Solution copied from obsidian-kanban: https://github.com/mgmeyers/obsidian-kanban/blob/44118e25661bff9ebfe54f71ae33805dc88ffa53/src/lang/helpers.ts
import {
CJK_FONTS,
LOCALE,
DEVICE,
FRONTMATTER_KEYS,
LOCALE,
CJK_FONTS,
} from "src/constants/constants";
import {
TAG_AUTOEXPORT,
TAG_MDREADINGMODE,
TAG_PDFEXPORT,
} from "src/constants/constSettingsTags";
import { URLs } from "src/constants/safeUrls";
import {
labelALT,
labelCTRL,
labelMETA,
labelSHIFT,
} from "src/utils/modifierKeyLabels";
import { URLs } from "src/constants/safeUrls";
import en from "./locale/en";
import { errorHandler } from "src/utils/ErrorHandler";
declare const PLUGIN_LANGUAGES: Record<string, string>;
declare const PLUGIN_VERSION: string;
declare const LZString: {
decompressFromBase64: (value: string) => string | null;
};
let locale: Partial<typeof en> | null = null;
// Runtime token map for compressed locales.
// Keep this in sync with token emission in rollup.config.js tokenizeLocaleContent.
// If you add a locale and it needs a new dynamic placeholder, add it in both places.
const TOKENS = {
IF_DESKTOP_START: "__EXD_IF_DESKTOP__",
IF_DESKTOP_END: "__EXD_END_IF_DESKTOP__",
LABEL_ALT: "__EXD_LABEL_ALT__",
LABEL_CTRL: "__EXD_LABEL_CTRL__",
LABEL_META: "__EXD_LABEL_META__",
LABEL_SHIFT: "__EXD_LABEL_SHIFT__",
FRONTMATTER_LINK_BRACKETS: "__EXD_FRONTMATTER_LINK_BRACKETS__",
FRONTMATTER_LINK_PREFIX: "__EXD_FRONTMATTER_LINK_PREFIX__",
FRONTMATTER_URL_PREFIX: "__EXD_FRONTMATTER_URL_PREFIX__",
CJK_FONTS: "__EXD_CJK_FONTS__",
PLUGIN_VERSION: "__EXD_PLUGIN_VERSION__",
DEVTOOLS_SHORTCUT: "__EXD_DEVTOOLS_SHORTCUT__",
} as const;
type LocaleFactory = (
device: typeof DEVICE,
frontmatterKeys: typeof FRONTMATTER_KEYS,
cjkFonts: typeof CJK_FONTS,
tagAutoexport: typeof TAG_AUTOEXPORT,
tagMdReadingMode: typeof TAG_MDREADINGMODE,
tagPdfExport: typeof TAG_PDFEXPORT,
safeUrls: typeof URLs,
altLabel: typeof labelALT,
ctrlLabel: typeof labelCTRL,
metaLabel: typeof labelMETA,
shiftLabel: typeof labelSHIFT,
pluginVersion: string,
) => Partial<typeof en>;
function resolveTokenizedString(value: string): string {
// Evaluate deferred desktop-only fragments generated during build.
const desktopResolved = value.replace(
/__EXD_IF_DESKTOP__([\s\S]*?)__EXD_END_IF_DESKTOP__/g,
(_, content: string) => (DEVICE.isDesktop ? content : ""),
);
// Evaluate deferred Apple vs non-Apple fragments generated during build.
const appleResolved = desktopResolved.replace(
/__EXD_IF_APPLE__([\s\S]*?)__EXD_ELSE_APPLE__([\s\S]*?)__EXD_END_IF_APPLE__/g,
(_, appleValue: string, nonAppleValue: string) =>
DEVICE.isIOS || DEVICE.isMacOS ? appleValue : nonAppleValue,
);
// Resolve URL placeholders emitted during build from safeUrls constants.
const withResolvedUrls = appleResolved.replace(
/__EXD_URL_([A-Z0-9_]+)__/g,
(match: string, key: string) =>
(URLs as Record<string, string>)[key] ?? match,
);
// Token replacements for runtime-dependent values.
const replacements: Record<string, string> = {
[TOKENS.LABEL_ALT]: labelALT(),
[TOKENS.LABEL_CTRL]: labelCTRL(),
[TOKENS.LABEL_META]: labelMETA(),
[TOKENS.LABEL_SHIFT]: labelSHIFT(),
[TOKENS.FRONTMATTER_LINK_BRACKETS]: FRONTMATTER_KEYS["link-brackets"].name,
[TOKENS.FRONTMATTER_LINK_PREFIX]: FRONTMATTER_KEYS["link-prefix"].name,
[TOKENS.FRONTMATTER_URL_PREFIX]: FRONTMATTER_KEYS["url-prefix"].name,
[TOKENS.CJK_FONTS]: CJK_FONTS,
[TOKENS.PLUGIN_VERSION]: PLUGIN_VERSION,
[TOKENS.DEVTOOLS_SHORTCUT]:
DEVICE.isIOS || DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i",
};
let resolved = withResolvedUrls;
for (const [token, replacement] of Object.entries(replacements)) {
resolved = resolved.split(token).join(replacement);
}
return resolved;
}
function resolveTokensDeep(value: unknown): unknown {
if (typeof value === "string") {
return resolveTokenizedString(value);
}
if (Array.isArray(value)) {
return value.map(resolveTokensDeep);
}
if (value && typeof value === "object") {
const entries = Object.entries(value as Record<string, unknown>);
return Object.fromEntries(
entries.map(([k, v]) => [k, resolveTokensDeep(v)]),
);
}
return value;
}
type LocaleRuntimeGlobals = {
unpackBase64Deflate?: (value: string) => string;
};
function loadLocale(lang: string): Partial<typeof en> {
if (lang === "zh") {
lang = "zh-cn";
} //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2247
if (!Object.prototype.hasOwnProperty.call(PLUGIN_LANGUAGES, lang)) {
return en;
}
try {
const compressed = PLUGIN_LANGUAGES[lang];
const decompressed = LZString.decompressFromBase64(compressed);
if (!decompressed) {
const runtimeGlobals = window as Window & LocaleRuntimeGlobals;
const unpack = runtimeGlobals.unpackBase64Deflate;
if (typeof unpack !== "function") {
return en;
}
const decompressed = unpack(compressed);
const parsed = JSON.parse(decompressed) as Partial<typeof en>;
return resolveTokensDeep(parsed) as Partial<typeof en>;
} catch {
// Construct a factory function string.
// This allows safeEval (which runs in the global scope) to access our imported variables
// because we pass them explicitly as arguments to this function.
const factoryCode = `(function(
DEVICE, FRONTMATTER_KEYS, CJK_FONTS,
TAG_AUTOEXPORT, TAG_MDREADINGMODE, TAG_PDFEXPORT,
URLs,
labelALT, labelCTRL, labelMETA, labelSHIFT,
PLUGIN_VERSION
) {
let x = {};
${decompressed}
return x;
})`;
// Evaluate the function declaration using your ErrorHandler
const factoryResult = errorHandler.safeEval<unknown>(
factoryCode,
"loadLocale - parsing language pack",
window,
);
if (typeof factoryResult !== "function") {
return en;
}
const factory = factoryResult as LocaleFactory;
// Execute the evaluated function, injecting the actual imported dependencies
const x = factory(
DEVICE,
FRONTMATTER_KEYS,
CJK_FONTS,
TAG_AUTOEXPORT,
TAG_MDREADINGMODE,
TAG_PDFEXPORT,
URLs,
labelALT,
labelCTRL,
labelMETA,
labelSHIFT,
PLUGIN_VERSION,
);
return x || en;
} catch (error) {
console.error("Error loading locale", loadLocale, error);
return en;
}
}
+135 -108
View File
@@ -19,9 +19,9 @@ export default {
// Sugester
SELECT_FILE_TO_INSERT: "Select a file to insert",
// main.ts
ERROR_INITIALIZING_EA: "Error initializing Excalidraw Automate",
CONVERT_URL_TO_FILE: "Save image from URL to local file",
UNZIP_CURRENT_FILE: "Decompress current Excalidraw file",
ZIP_CURRENT_FILE: "Compress current Excalidraw file",
PUBLISH_SVG_CHECK:
"Obsidian Publish: Find SVG and PNG exports that are out of date",
EMBEDDABLE_PROPERTIES: "Embeddable Properties",
@@ -66,6 +66,7 @@ export default {
"Create new drawing - IN A POPOUT WINDOW - and embed into active document",
TOGGLE_LOCK: "Toggle Text Element between edit RAW and PREVIEW",
DELETE_FILE: "Delete selected image or Markdown file from Obsidian Vault",
DELETE_IMAGE_NOTICE: "Please select an image or embedded markdown document",
MARKER_FRAME_SHOW: "Marker Frames Visible",
MARKER_FRAME_TITLE_SHOW: "Marker Frame Titles Visible",
COPY_ELEMENT_LINK: "Copy [[link]] for selected element(s)",
@@ -94,7 +95,18 @@ export default {
INSERT_PDF: "Insert PDF file from vault",
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE: "Insert last active PDF page as image",
UNIVERSAL_ADD_FILE: "Insert ANY file",
// Compatibility keys consumed by upstream Excalidraw via ExcalidrawPlugin.getLabel().
// Keep this group in sync across maintained locales.
ABOUT_LIBRARIES: "How to load libraries",
INSERT_CARD: "Add back-of-note card",
COMP_IMG: "Image & Files",
COMP_IMG_FROM_SYSTEM: "Import from system",
COMP_IMG_ANY_FILE: "ANY file from Vault",
COMP_IMG_LaTeX: "LaTeX formula",
COMP_FRAME: "Frame Actions",
COMP_FRAME_HINT:
"Toggle Marker Frame. Guide-only frames to define slides/print areas/image references. " +
"Hidden in image exports; doesn't contain elements. Hide/show frames via canvas context menu.",
CONVERT_CARD_TO_FILE: "Move back-of-note card to File",
ERROR_TRY_AGAIN: "Please try again.",
PASTE_CODEBLOCK: "Paste code block",
@@ -106,6 +118,8 @@ export default {
ABOUT_EXCALIDRAW: "About Excalidraw",
RUN_OCR:
"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.",
RERUN_OCR:
"OCR full drawing re-run: Grab text from freedraw + images to clipboard and doc.props",
RUN_OCR_ELEMENTS:
@@ -115,6 +129,8 @@ export default {
CROP_PAGE: "Crop and mask selected page",
CROP_IMAGE: "Crop and mask image",
ANNOTATE_IMAGE: "Annotate image in Excalidraw",
ANNOTATE_IMAGE_ERROR:
"File not found. New Excalidraw drawing is taking too long to create. Please try again.",
INSERT_ACTIVE_PDF_PAGE_AS_IMAGE: "Insert active PDF page as image",
RESET_IMG_TO_100: "Set selected image element size to 100% of original",
RESET_IMG_ASPECT_RATIO: "Reset selected image element aspect ratio",
@@ -133,7 +149,6 @@ export default {
SELECT_LINK_TO_OPEN: "Select a link to open",
//ExcalidrawView.ts
ABOUT_LIBRARIES: "How to load libraries",
ERROR_CANT_READ_FILEPATH:
"Error, can't read file path. Importing file instead",
NO_SEARCH_RESULT: "Didn't find a matching element in the drawing",
@@ -177,9 +192,9 @@ export default {
INSTALL_SCRIPT_BUTTON: "Install or update Excalidraw Scripts",
OPEN_AS_MD: "Open as Markdown",
EXPORT_IMAGE: `Export Image`,
SHOW_TAB_TITLEBAR_BUTTONS: "Show tab titlebar buttons",
OPEN_LINK: "Open selected text as link\n(SHIFT+CLICK to open in a new pane)",
EXCALIDRAW_SIDEPANEL: "Excalidraw Sidepanel",
EXPORT_EXCALIDRAW: "Export to an .Excalidraw file",
LINK_BUTTON_CLICK_NO_TEXT:
"Select an element that contains an internal or external link.\n",
LINEAR_ELEMENT_LINK_CLICK_ERROR:
@@ -197,7 +212,6 @@ export default {
CONVERT_FILE: "Convert to new format",
BACKUP_AVAILABLE:
"We encountered an error while loading your drawing. This might have occurred if Obsidian unexpectedly closed during a save operation. For example, if you accidentally closed Obsidian on your mobile device while saving.<br><br><b>GOOD NEWS:</b> Fortunately, a local backup is available. However, please note that if you last modified this drawing on a different device (e.g., tablet) and you are now on your desktop, that other device likely has a more recent backup.<br><br>I recommend trying to open the drawing on your other device first and restore the backup from its local storage.<br><br>Would you like to load the backup?",
BACKUP_RESTORED: "Backup restored",
BACKUP_SAVE_AS_FILE:
"This drawing is empty. A non-empty backup is available. Would you like to restore it as a new file and open it in a new tab?",
BACKUP_SAVE: "Restore",
@@ -228,8 +242,6 @@ export default {
WELCOME_SYM_LINK: "Learn Excalidraw, Master PKM, Join the Community",
WELCOME_TWITTER_ARIA: "Follow me on Twitter",
WELCOME_TWITTER_LINK: "Follow me on Twitter",
WELCOME_LEARN_ARIA: "Learn Visual PKM",
WELCOME_LEARN_LINK: "Sign up for the Visual Thinking Workshop",
WELCOME_DONATE_ARIA: "Donate to support Excalidraw-Obsidian",
WELCOME_DONATE_LINK: 'Say "Thank You" & support the plugin.',
SAVE_IS_TAKING_LONG:
@@ -246,6 +258,33 @@ export default {
SEARCH_PREVIOUS: "Previous",
//settings.ts
FOLDER_PLACEHOLDER: "e.g.: Excalidraw",
CROP_FOLDER_PLACEHOLDER: "e.g.: Excalidraw/Cropped",
ANNOTATE_FOLDER_PLACEHOLDER: "e.g.: Excalidraw/Annotations",
TEMPLATE_PLACEHOLDER: "e.g.: Excalidraw/Template",
SCRIPT_FOLDER_PLACEHOLDER: "e.g.: Excalidraw/Scripts",
FILENAME_PREFIX_PLACEHOLDER: "e.g.: Drawing ",
CROP_PREFIX_PLACEHOLDER: "e.g.: cropped_",
CROP_SUFFIX_PLACEHOLDER: "e.g.: _cropped",
ANNOTATE_PREFIX_PLACEHOLDER: "e.g.: annotated_",
ANNOTATE_SUFFIX_PLACEHOLDER: "e.g.: _annotated",
DYNAMICSTYLE_OPTION_NONE: "Dynamic Styling OFF",
DYNAMICSTYLE_OPTION_COLORFUL: "Match color",
DYNAMICSTYLE_OPTION_GRAY: "Gray, match tone",
DEFAULT_OPEN_MODE_OPTION_NORMAL: "Always in normal-mode",
DEFAULT_OPEN_MODE_OPTION_ZEN: "Always in zen-mode",
DEFAULT_OPEN_MODE_OPTION_VIEW: "Always in view-mode",
DEFAULT_OPEN_MODE_OPTION_VIEW_MOBILE:
"Usually normal, but view-mode on Phone",
DEFAULT_PEN_MODE_OPTION_NEVER: "Never",
DEFAULT_PEN_MODE_OPTION_MOBILE: "On Obsidian Mobile",
DEFAULT_PEN_MODE_OPTION_ALWAYS: "Always",
EMBED_PREVIEW_IMAGETYPE_OPTION_PNG: "PNG Image",
EMBED_PREVIEW_IMAGETYPE_OPTION_SVG: "Native SVG",
EMBED_PREVIEW_IMAGETYPE_OPTION_SVGIMG: "SVG Image",
DEFAULT_COLOR_MD_DESC: "CSS Color-name|RGB-HEX",
MD_CSS_PLACEHOLDER: "Filename of CSS file in Vault",
CJK_ASSETS_FOLDER_PLACEHOLDER: "e.g.: Excalidraw/FontAssets",
DISABLE_CONTEXT_MENU_NAME: "Disable Excalidraw context menu",
DISABLE_CONTEXT_MENU_DESC:
"Disables the Excalidraw context menu. This can be useful on Mobile devices where the context menu pops up in unwanted moments.",
@@ -253,6 +292,7 @@ export default {
"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>`,
EXCALIDRAW_MASTERY_PROMO_SHOW: "Show",
@@ -267,9 +307,6 @@ export default {
"Learn Excalidraw, Master Visual Thinking, Join the Community",
LINKS_JOIN_SYM: "Learn Excalidraw",
LINKS_TWITTER: "Follow me",
LINKS_VTW_ARIA:
"Learn about Visual PKM, Excalidraw, Obsidian, ExcaliBrain and more",
LINKS_VTW: "Join a Workshop",
LINKS_BOOK_ARIA: "Read Sketch Your Mind, my book on Visual Thinking",
LINKS_BOOK: "Read the Book",
LINKS_WIKI: "Plugin Wiki",
@@ -361,76 +398,26 @@ export default {
AI_PROVIDER_OPTION_GOOGLE: "Google / Gemini",
AI_PROVIDER_OPTION_XAI: "xAI / Grok",
AI_PROVIDER_OPTION_OPENAI_COMPATIBLE: "OpenAI-compatible / local",
AI_PROVIDER_BASE_URL_EMPTY: "Derived from the provider type",
AI_PROVIDER_API_KEY_SET: "Configured",
AI_PROVIDER_API_KEY_NOT_SET: "Not set",
AI_PROVIDER_EDIT: "Edit provider",
AI_PROVIDER_ADD: "Add provider",
AI_PROVIDER_REMOVE: "Remove provider",
AI_PROVIDER_RESTORE_DEFAULTS: "Restore provider defaults",
AI_PROVIDER_API_KEY_NAME: "AI API key",
AI_PROVIDER_API_KEY_DESC:
"Primary API key used by the shared AI layer. The value is masked unless the field is focused.",
AI_PROVIDER_API_KEY_PLACEHOLDER: "Provider API key",
AI_PROVIDER_BASE_URL_NAME: "AI base URL",
AI_PROVIDER_BASE_URL_DESC:
"Optional provider base URL. Use this for local OpenAI-compatible servers or self-hosted gateways. You can enter either a base URL such as https://api.openai.com/v1 or a full chat endpoint such as https://api.openai.com/v1/chat/completions; Excalidraw will normalize known OpenAI-style endpoints automatically.",
AI_PROVIDER_BASE_URL_PLACEHOLDER: "e.g.: https://api.openai.com/v1",
AI_PROVIDER_TEXT_ENDPOINT_NAME: "AI text endpoint override",
AI_PROVIDER_TEXT_ENDPOINT_DESC:
"Optional full endpoint override for text and multimodal requests. Leave blank to derive it from the base URL and provider. Most users should keep this empty.",
AI_PROVIDER_TEXT_ENDPOINT_PLACEHOLDER: "Optional full text endpoint",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_NAME:
"AI image generation endpoint override",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_DESC:
"Optional full endpoint override for image generation requests. Leave blank unless your provider exposes image generation on a non-standard path.",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_PLACEHOLDER:
"Optional full image generation endpoint",
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_NAME: "AI image edits endpoint override",
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_DESC:
"Optional full endpoint override for image edit requests. Leave blank unless your provider exposes image edits on a non-standard path.",
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_PLACEHOLDER:
"Optional full image edits endpoint",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_NAME:
"AI image variations endpoint override",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_DESC:
"Optional full endpoint override for image variation requests. Leave blank unless your provider exposes image variations on a non-standard path.",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_PLACEHOLDER:
"Optional full image variations endpoint",
AI_PROVIDER_DEFAULT_TEXT_MODEL_NAME: "Text and multimodal model",
AI_PROVIDER_DEFAULT_TEXT_MODEL_DESC:
"Model used for text chat and image-aware requests such as Mermaid chat, diagram-to-code, and wireframe analysis.<br>Provider: {{provider}} ({{providerType}})<br>API key: {{apiKey}}<br>Model name: {{model}}<br>Endpoint: {{endpoint}}<br>Multimodal support: {{multimodalSupport}}",
AI_PROVIDER_DEFAULT_TEXT_MODEL_PLACEHOLDER:
"e.g.: gpt-5-mini, claude-sonnet, gemini-2.5-pro",
AI_PROVIDER_DEFAULT_VISION_MODEL_NAME: "Vision model",
AI_PROVIDER_DEFAULT_VISION_MODEL_DESC:
"Model used for image understanding tasks such as diagram-to-code or image-plus-text prompts.<br>Provider: {{provider}} ({{providerType}})<br>API key: {{apiKey}}<br>Model name: {{model}}<br>Endpoint: {{endpoint}}",
AI_PROVIDER_DEFAULT_VISION_MODEL_PLACEHOLDER:
"e.g.: gpt-5-mini, claude-sonnet, gemini-2.5-flash",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_NAME: "Image model",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_DESC:
"Model used for image generation, prompt-based transforms, and mask edits. Use the Edit, Add, and Remove buttons to modify the list.<br>Provider: {{provider}} ({{providerType}})<br>API key: {{apiKey}}<br>Model name: {{model}}<br>Supported resolutions: {{sizes}}<br>Prompt transforms: {{supportsPromptImageTransforms}}<br>Mask edits: {{supportsMaskImageEdits}}",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "e.g.: gpt-image-1",
AI_MODEL_CONFIG_DERIVED_ENDPOINT: "Derived from the selected provider",
AI_MODEL_EDIT: "Edit model",
AI_MODEL_ADD: "Add model",
AI_MODEL_REMOVE: "Remove model",
AI_MODEL_RESTORE_DEFAULTS: "Restore model defaults",
AI_IMAGE_MODEL_CAPABILITIES_NAME: "Image model capabilities",
AI_IMAGE_MODEL_CAPABILITIES_DESC: `Manage stored image model metadata such as supported resolutions, prompt-transform support, and mask-edit support. Example: see the <a href="${URLs.PLATFORM_OPENAI_COM_DOCS_GUIDES_IMAGE_GENERATION}" target="_blank" rel="noopener noreferrer">OpenAI image generation docs</a> to look up supported sizes.`,
AI_IMAGE_MODEL_CAPABILITIES_LOAD_DEFAULTS: "Restore known defaults",
AI_IMAGE_MODEL_CAPABILITIES_ADD_MODEL: "Add",
AI_IMAGE_MODEL_CAPABILITIES_EDIT_MODEL: "Edit",
AI_IMAGE_MODEL_CAPABILITIES_REMOVE_MODEL: "Remove entry",
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_NAME: "Selected model entry",
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_DESC:
"<b>{{model}}</b><br>Supported resolutions: {{sizes}}<br>Prompt transforms: {{supportsPromptImageTransforms}}<br>Mask edits: {{supportsMaskImageEdits}}",
AI_IMAGE_MODEL_CAPABILITIES_SIZES_NAME: "Supported resolutions",
AI_IMAGE_MODEL_CAPABILITIES_SIZES_PLACEHOLDER:
"1024x1024, 1536x1024, 1024x1536",
AI_IMAGE_MODEL_CAPABILITIES_EDITS_NAME: "Supports image edits",
AI_IMAGE_MODEL_CAPABILITIES_EDITS_DESC:
"Disable this when the model can generate images but does not support image edits or masks.",
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_NAME: "Prompt image transforms",
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_DESC:
"Enable this when the model accepts an input image plus a text prompt for non-masked edits.",
@@ -472,7 +459,7 @@ export default {
AI_PROVIDER_PROFILE_MODAL_BASE_URL_DESC:
"Base URL used to derive the provider endpoints.",
AI_PROVIDER_PROFILE_MODAL_BASE_URL_PLACEHOLDER:
"e.g.: https://api.openai.com/v1",
"e.g.: http" + "s://api.openai" + ".com/v1",
AI_PROVIDER_PROFILE_MODAL_OPENAI_COMPATIBLE_HINT:
"For local OpenAI-compatible LLMs, enter a dummy API key if no real key is required so Excalidraw recognizes the profile as configured.",
AI_PROVIDER_PROFILE_MODAL_NAME_REQUIRED: "Provider profile name is required.",
@@ -515,6 +502,27 @@ export default {
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_DESC:
"Default value for AIRequest.maxTokens. This limits text or multimodal responses returned by the model. It does not affect direct image generation or image edit endpoints.",
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_PLACEHOLDER: "e.g.: 4096",
// AI Usage Metering - AIUsageModal
AI_USAGE_MODAL_TITLE: "AI Usage (this session)",
AI_USAGE_MODAL_TEXT_MODELS_HEADING: "Text / multimodal models",
AI_USAGE_MODAL_IMAGE_MODELS_HEADING: "Image generation models",
AI_USAGE_MODAL_TABLE_COL_MODEL: "Model",
AI_USAGE_MODAL_TABLE_COL_INPUT: "Input tokens",
AI_USAGE_MODAL_TABLE_COL_OUTPUT: "Output tokens",
AI_USAGE_MODAL_TABLE_COL_IMAGE_MODEL: "Model",
AI_USAGE_MODAL_TABLE_COL_GENERATIONS: "Images generated",
AI_USAGE_MODAL_TABLE_TOTAL: "Total",
AI_USAGE_MODAL_NO_USAGE: "No AI requests have been made this session.",
AI_USAGE_MODAL_SESSION_NOTE:
"Usage is accumulated for the current Obsidian session only and is not persisted between restarts.",
AI_USAGE_MODAL_COPY_MARKDOWN: "Copy as Markdown",
AI_USAGE_MODAL_COPY_SUCCESS: "Usage table copied to clipboard.",
AI_USAGE_MODAL_COPY_FAILURE: "Failed to copy to clipboard.",
AI_USAGE_MODAL_TABLE_MARKDOWN_TITLE: "## AI Usage (this session)",
// AI Usage button - Settings
AI_USAGE_SETTINGS_BUTTON_NAME: "Session token usage",
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_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. ",
@@ -663,14 +671,6 @@ export default {
MODE_TRAY: "Tray-mode",
MODE_PHONE: "Phone-mode",
REAPPLY_UI_MODE_BUTTON: "Reapply UI mode now",
TRAY_MODE_NAME: "Enable tray-mode",
PREFER_COMPACT_MODE_DESKTOP_NAME: "Prefer compact-mode on Desktop",
PREFER_COMPACT_MODE_DESKTOP_DESC:
"When toggling tray-mode on a desktop, if this option is enabled, Excalidraw will toggle between compact-mode and tray-mode. " +
"If this setting is off, it will toggle betweeen full-mode and tray-mode.",
COMPACT_MODE_NAME: "Prefer compact-mode on Tablets",
COMPACT_MODE_DESC:
"This setting allows you to have a different default mode on tablets, then on desktops. You can default to compact mode on tablets, and to tray-mode on desktops with the help of this setting.",
HOTKEY_OVERRIDE_HEAD: "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 ` +
@@ -737,7 +737,8 @@ export default {
LINKS_DESC:
`${labelCTRL()}+CLICK on <code>[[Text Elements]]</code> to open them as links. ` +
"If the selected text has more than one <code>[[valid Obsidian links]]</code>, only the first will be opened. " +
"If the text starts as a valid web link (i.e. <code>https://</code> or <code>http://</code>), then " +
"If the text starts as a valid web link (i.e. <code>http" +
"s://</code> or <code>http://</code>), then " +
"the plugin will open it in a browser. " +
"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>.",
@@ -786,12 +787,6 @@ export default {
"In PREVIEW mode, when parsing Text Elements, place brackets around links. " +
"You can override this setting for a specific drawing by adding <code>"
}${FRONTMATTER_KEYS["link-brackets"].name}: true/false</code> to the file's frontmatter.`,
/*LINK_DETECTION_NAME: "Do not auto-create element link from text",
LINK_DETECTION_DESC: "By default, Excalidraw will automatically create an element link when you type or paste a valid " +
"[[Obsidian link]] or a (web link) into a Text Element. This link overrides whatever element link you may have set previously. " +
"Even if you delete the element link, if the text element contains a valid link, Excalidraw will recreate the element link. " +
"If you turn this setting on, Excalidraw will not auto-create element links from text. You can still manually set element links " +
`Links in the text will still be navigable when you ${labelCTRL()} + CLICK the element.`,*/
LINK_PREFIX_NAME: "Link prefix",
LINK_PREFIX_DESC: `${
"In PREVIEW mode, if the Text Element contains a link, precede the text with these characters. " +
@@ -840,9 +835,11 @@ export default {
QUOTE_TRANSCLUSION_REMOVE_DESC:
"Remove the leading '> ' from each line of the transclusion. This will improve readability of quotes in text only transclusions<br>" +
"<b><u>Toggle ON:</u></b> Remove leading '> '<br><b><u>Toggle OFF:</u></b> Do not remove leading '> ' (note it will still be removed from the first row due to Obsidian API functionality)",
GET_URL_TITLE_NAME: "Use iframely to resolve page title",
GET_URL_TITLE_NAME: "Use oEmbed to resolve page title",
GET_URL_TITLE_DESC:
"Use the <code>http://iframely.server.crestify.com/iframely?url=</code> to get title of page when dropping a link into Excalidraw",
"Use the <code>http" +
"s://noembed" +
".com/embed?url=</code> to get title of page when dropping an HTTPS link into Excalidraw",
PDF_TO_IMAGE: "PDF to Image",
PDF_TO_IMAGE_SCALE_NAME: "PDF to Image conversion scale",
PDF_TO_IMAGE_SCALE_DESC:
@@ -974,6 +971,9 @@ export default {
EMBED_WIKILINK_NAME: "Embed Drawing using Wiki link",
EMBED_WIKILINK_DESC:
"<b><u>Toggle ON:</u></b> Excalidraw will embed a [[wiki link]].<br><b><u>Toggle OFF:</u></b> Excalidraw will embed a [markdown](link).",
EMBED_PLACEHOLDER_NAME: "Embed placeholder image",
EMBED_PLACEHOLDER_DESC:
"If enabled, embeds a placeholder image when no drawing is present. If disabled, no image is embedded.",
EXPORT_PNG_SCALE_NAME: "PNG export image scale",
EXPORT_PNG_SCALE_DESC: "The size-scale of the exported PNG image",
EXPORT_BACKGROUND_NAME: "Export image with background",
@@ -1027,10 +1027,6 @@ export default {
PRESERVE_TEXT_AFTER_DRAWING_NAME: "Zotero and Footnotes compatibility",
PRESERVE_TEXT_AFTER_DRAWING_DESC:
"Preserve text after the ## Drawing section of the markdown file. This may have a very slight performance impact when saving very large drawings.",
DEBUGMODE_NAME: "Enable debug messages",
DEBUGMODE_DESC:
"I recommend restarting Obsidian after enabling/disabling this setting. This enable debug messages in the console. This is useful for troubleshooting issues. " +
`If you are experiencing problems with the plugin, please enable this setting, reproduce the issue, and include the console log in the issue you raise on <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}">GitHub</a>`,
SLIDING_PANES_NAME: "Sliding panes plugin support",
SLIDING_PANES_DESC:
"Need to restart Obsidian for this change to take effect.<br>" +
@@ -1051,11 +1047,6 @@ export default {
"By enabling this feature drawings you create with the ribbon icon, the command palette actions, " +
"and the file explorer are going to be all legacy *.excalidraw files. This setting will also turn off the reminder message " +
"when you open a legacy file for editing.",
MATHJAX_NAME: "MathJax (LaTeX) javascript library host",
MATHJAX_DESC:
"If you are using LaTeX equations in Excalidraw, then the plugin needs to load a javascript library for that. " +
"Some users are unable to access certain host servers. If you are experiencing issues, try changing the host here. You may need to " +
"restart Obsidian after closing settings, for this change to take effect.",
LATEX_DEFAULT_NAME: "Default LaTeX formula for new equations",
LATEX_DEFAULT_DESC:
"Leave empty if you don't want a default formula. You can add default formatting here such as <code>\\color{white}</code>.",
@@ -1097,13 +1088,21 @@ 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.",
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?",
ENABLE_COMMAND_LINKS_CONFIRM_ENABLE: "Enable command links",
ENABLE_COMMAND_LINKS_CONFIRM_DENY: "Do not allow",
ENABLE_COMMAND_LINKS_DESC:
"If enabled, Excalidraw will allow links starting with <code>cmd://</code> to execute Obsidian command palette actions in drawings you open from now on, until you disable this setting. " +
"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_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.",
STARTUP_SCRIPT_BUTTON_CREATE: "Create startup script",
STARTUP_SCRIPT_BUTTON_OPEN: "Open startup script",
STARTUP_SCRIPT_EXISTS: "Startup script file already exists",
FILETYPE_NAME: "Display type (✏️) for excalidraw.md files in File Explorer",
FILETYPE_DESC:
"Excalidraw files will receive an indicator using the emoji or text defined in the next setting.",
@@ -1197,9 +1196,6 @@ export default {
"Select existing drawing or type name of a new drawing then press Enter.",
SELECT_TO_EMBED: "Select the drawing to insert into active document.",
SELECT_MD: "Select the markdown document you want to insert",
SELECT_PDF: "Select the PDF document you want to insert",
PDF_PAGES_HEADER: "Pages to load?",
PDF_PAGES_DESC: "Format: 1, 3-5, 7, 9-11",
//SelectCard.ts
TYPE_SECTION: "Type section name to select.",
@@ -1217,13 +1213,19 @@ export default {
SCRIPT_EXECUTION_ERROR:
"Script execution error. Please find error message on the developer console.",
//ScriptInstallPrompt.ts
SCRIPT_INSTALL_PROMPT_FETCH_ERROR:
"Error opening the Excalidraw Script Store page. " +
"Please double check that you can access the website. " +
"I've logged the link in developer console (press CTRL+SHIFT+i)",
SCRIPT_INSTALL_PROMPT_OPEN_ERROR: "Could not open ScriptEngine repository",
//ExcalidrawViewUtils.ts
MARKER_FRAME_RENDERING_DISABLED_NOTICE:
"There are hidden marker-frames in the scene.",
//DRAWING_HAS_BACK_OF_THE_CARD: "There are notes on the back of this drawing.",
//ExcalidrawData.ts
LOAD_FROM_BACKUP: "Excalidraw file was corrupted. Loading from backup file.",
FONT_LOAD_SLOW:
"Loading Fonts...\n\n This is taking longer than expected. If this delay occurs regularly then you may download the fonts locally to your Vault. \n\n" +
"(click=dismiss, right-click=Info)",
@@ -1492,9 +1494,6 @@ export default {
EXPORTDIALOG_SCREENSHOT_DESC:
"Screenshots will include embeddables such as markdown pages, YouTube, websites, etc. They are only available on desktop, cannot be automatically exported, and only support PNG format.",
SCREENSHOT_DESKTOP_ONLY: "Screenshot feature is only available on desktop",
SCREENSHOT_FILE_SUCCESS: "Screenshot saved to vault",
SCREENSHOT_CLIPBOARD_SUCCESS: "Screenshot copied to clipboard",
SCREENSHOT_CLIPBOARD_ERROR: "Failed to copy screenshot to clipboard: ",
SCREENSHOT_ERROR: "Error capturing screenshot - see console log",
//exportUtils.ts
@@ -1516,14 +1515,14 @@ export default {
The Excalidraw Obsidian plugin is much more than "just" a drawing tool. Because it integrates deeply with Obsidian, it opens up a whole new paradigm for Visual Personal Knowledge Management.
<div style="text-align:center;margin-top:10px;">
<a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EE}" target="_blank"><img "src="${URLs.SKETCH_YOUR_MIND_COM_IMAGES_LOGO_EE_PNG}" style="width:50%;"></a>
<a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EE}" target="_blank"><img src="${URLs.SKETCH_YOUR_MIND_COM_IMAGES_LOGO_EE_PNG}" style="width:50%;"></a>
</div>
To help you get started without the overwhelm, I highly recommend taking the free **[Excalidraw Essentials](" + URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EE + ")** mini-course. It cuts through the noise and teaches you the fundamentals in a fast, structured way.
To help you get started without the overwhelm, I highly recommend taking the free **[Excalidraw Essentials](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EE})** mini-course. It cuts through the noise and teaches you the fundamentals in a fast, structured way.
You also don't have to figure it all out alone! Come join the **[Sketch Your Mind Community](" + URLs.COMMUNITY_SKETCH_YOUR_MIND_COM + ")** to connect with fellow visual thinkers, share your workflows, and build a frictionless PKM system together.
You also don't have to figure it all out alone! Come join the **[Sketch Your Mind Community](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM})** to connect with fellow visual thinkers, share your workflows, and build a frictionless PKM system together.
If you'd like to see what's possible right now, here is a showcase of the key features. To keep abreast of the latest updates and to explore visual PKM, please subscribe to my YouTube channel: [Visual PKM](" + URLs.WWW_YOUTUBE_COM_VISUALPKM + ").
If you'd like to see what's possible right now, here is a showcase of the key features. To keep abreast of the latest updates and to explore visual PKM, please subscribe to my YouTube channel: [Visual PKM](${URLs.WWW_YOUTUBE_COM_VISUALPKM}).
Thank you & Enjoy!
@@ -1532,16 +1531,6 @@ Thank you & Enjoy!
</div>
`,
//Excalidraw component
COMP_IMG: "Image & Files",
COMP_IMG_FROM_SYSTEM: "Import from system",
COMP_IMG_ANY_FILE: "ANY file from Vault",
COMP_IMG_LaTeX: "LaTeX formula",
COMP_FRAME: "Frame Actions",
COMP_FRAME_HINT:
"Toggle Marker Frame. Guide-only frames to define slides/print areas/image references. " +
"Hidden in image exports; doesn't contain elements. Hide/show frames via canvas context menu.",
//CustomEmbeddable.tsx
NOTICE_PDF_THEME:
"PDF theme overridden.\n" +
@@ -1574,4 +1563,42 @@ Thank you & Enjoy!
//SuggestionModal.ts
SUGGESTION_NOMATCH: "No matches found",
// Excalidraw Extras Gateway Components
EXTRAS_GATEWAY_COMP_MATHJAX: "MathJax (LaTeX)",
EXTRAS_GATEWAY_COMP_MERMAID: "Mermaid to Excalidraw",
EXTRAS_GATEWAY_COMP_PDF: "PDF Export",
EXTRAS_GATEWAY_COMP_FILESYSTEM: "Local File System Access",
// Gateway Modals & Texts
EXTRAS_GATEWAY_TITLE: "Excalidraw Extras Required",
EXTRAS_GATEWAY_DESC:
"The '{component}' feature has been moved to the Excalidraw Extras companion plugin to keep Excalidraw lightweight, stay within Obsidian Sync Basic size restrictions, and give you explicit control over the additional libraries and elevated-permission functionality it requires.",
EXTRAS_GATEWAY_INSTALL_BTN: "Install from Community Plugins",
EXTRAS_GATEWAY_ENABLE_PERM_BTN: "Enable Plugin Permanently",
EXTRAS_GATEWAY_ENABLE_FEATURE_PERM_BTN: "Enable {component} Permanently",
EXTRAS_GATEWAY_TEMP_ENABLE_TITLE: "Enable Temporarily",
EXTRAS_GATEWAY_TEMP_ENABLE_DESC:
"Turn on the feature temporarily. It will automatically turn off when the timer expires.",
EXTRAS_GATEWAY_SESSION_ENABLE_DESC:
"Enable this feature for the current Obsidian session only.",
EXTRAS_GATEWAY_ENABLE_CURRENT_SESSION: "Enable for this session",
EXTRAS_GATEWAY_TIMER_EXPIRED:
"Excalidraw Extras temporary timer expired. Plugin disabled.",
EXTRAS_GATEWAY_FEATURE_TIMER_EXPIRED:
"Excalidraw Extras: {component} timer expired. Feature disabled.",
EXTRAS_GATEWAY_API_MISSING:
"Excalidraw Extras is enabled, but the API failed to load. Please update the plugin.",
EXTRAS_GATEWAY_FEATURE_TITLE: "Feature Disabled",
EXTRAS_GATEWAY_FEATURE_DESC:
"The '{component}' feature is currently disabled in your Excalidraw Extras settings.",
EXTRAS_GATEWAY_IGNORE_SESSION: "Ignore for this session",
EXTRAS_GATEWAY_UPDATE_EXACT:
"Excalidraw Extras Update Required. {component} requires EXACTLY v{reqVersion} (Found v{currentVersion})",
EXTRAS_GATEWAY_UPDATE_MIN:
"Excalidraw Extras Update Required. {component} requires >= v{reqVersion} (Found v{currentVersion})",
EXTRAS_GATEWAY_COMP_PLUGIN: "Excalidraw Extras Plugin",
EXTRAS_GATEWAY_UPDATE_TITLE:
"Excalidraw requires a new version of the Extras plugin",
EXTRAS_GATEWAY_UPDATE_BTN: "Open Community Plugins",
};
+67 -95
View File
@@ -21,7 +21,6 @@ export default {
// main.ts
CONVERT_URL_TO_FILE: "Guardar imagen desde el URL en un archivo local",
UNZIP_CURRENT_FILE: "Descomprimir el archivo Excalidraw actual",
ZIP_CURRENT_FILE: "Comprimir el archivo Excalidraw actual",
PUBLISH_SVG_CHECK:
"Obsidian Publish: Buscar exportaciones SVG y PNG desactualizadas",
EMBEDDABLE_PROPERTIES: "Propiedades de Elementos Incrustados",
@@ -100,7 +99,17 @@ export default {
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE:
"Insertar última página PDF activa como imagen",
UNIVERSAL_ADD_FILE: "Insertar CUALQUIER archivo",
// Claves de compatibilidad consumidas por Excalidraw upstream vía ExcalidrawPlugin.getLabel().
// Mantén este grupo sincronizado en los idiomas mantenidos.
INSERT_CARD: "Agregar tarjeta al reverso-de-la-nota",
COMP_IMG: "Imágenes y archivos",
COMP_IMG_FROM_SYSTEM: "Importar desde el sistema",
COMP_IMG_ANY_FILE: "Cualquier archivo de la bóveda",
COMP_IMG_LaTeX: "Fórmula de LaTeX",
COMP_FRAME: "Acciones de Frame(marco)",
COMP_FRAME_HINT:
"Activar/desactivar Marker-Frame (marco de marcador). Marcos de guía para definir diapositivas/áreas de impresión/referencias de imagen. " +
"Se ocultan en las exportaciones de imágenes y no contienen elementos. Oculta/muestra los marcos desde el menú contextual del lienzo.",
CONVERT_CARD_TO_FILE: "Mover tarjeta del reverso-de-la-nota a un Archivo",
ERROR_TRY_AGAIN: "Por favor, inténtalo de nuevo.",
PASTE_CODEBLOCK: "Pegar un Bloque de Código",
@@ -181,7 +190,6 @@ export default {
EXPORT_IMAGE: `Exportar imagen`,
OPEN_LINK:
"Abrir texto seleccionado como enlace\n(SHIFT+CLICK para abrir en un nuevo panel)",
EXPORT_EXCALIDRAW: "Exportar a un archivo .Excalidraw",
LINK_BUTTON_CLICK_NO_TEXT:
"Selecciona un elemento que contenga un enlace interno o externo.\n",
LINEAR_ELEMENT_LINK_CLICK_ERROR:
@@ -199,7 +207,6 @@ export default {
CONVERT_FILE: "Convertir a nuevo formato",
BACKUP_AVAILABLE:
"Encontramos un error al cargar tu bosquejo. Esto pudo haber ocurrido si Obsidian se cerró inesperadamente durante una operación de guardado. Por ejemplo, si cerraste accidentalmente Obsidian en tu dispositivo móvil mientras guardabas.<br><br><b>BUENAS NOTICIAS:</b> Afortunadamente, hay una copia de seguridad local disponible. Sin embargo, ten en cuenta que si modificaste este bosquejo por última vez en un dispositivo diferente (ej. tablet) y ahora estás en tu computadora de escritorio, es probable que ese otro dispositivo tenga una copia de seguridad más reciente.<br><br>Recomiendo intentar abrir el bosquejo en tu otro dispositivo primero y restaurar la copia de seguridad desde su almacenamiento local.<br><br>¿Te gustaría cargar la copia de seguridad?",
BACKUP_RESTORED: "Copia de seguridad restaurada",
BACKUP_SAVE_AS_FILE:
"Este bosquejo está vacío. Hay una copia de seguridad no vacía disponible. ¿Te gustaría restaurarla como un nuevo archivo y abrirla en una nueva pestaña?",
BACKUP_SAVE: "Restaurar",
@@ -233,8 +240,6 @@ export default {
WELCOME_DISCORD_LINK: "Únete al servidor de Discord",
WELCOME_TWITTER_ARIA: "Sígueme en Twitter",
WELCOME_TWITTER_LINK: "Sígueme en Twitter",
WELCOME_LEARN_ARIA: "Aprende PKM Visual",
WELCOME_LEARN_LINK: "Inscríbete en el Taller de Pensamiento Visual",
WELCOME_DONATE_ARIA: "Dona para apoyar Excalidraw-Obsidian",
WELCOME_DONATE_LINK: 'Di "Gracias" y apoya el complemento.',
SAVE_IS_TAKING_LONG:
@@ -265,9 +270,6 @@ export default {
"Únete al servidor de Discord del Taller de Pensamiento Visual",
LINKS_DISCORD: "Únete a la Comunidad",
LINKS_TWITTER: "Sígueme",
LINKS_VTW_ARIA:
"Aprende sobre PKM Visual, Excalidraw, Obsidian, ExcaliBrain y más",
LINKS_VTW: "Únete a un Taller",
LINKS_BOOK_ARIA: "Lee Sketch Your Mind, mi libro sobre Pensamiento Visual",
LINKS_BOOK: "Lee el Libro",
LINKS_WIKI: "Wiki del Complemento",
@@ -366,78 +368,26 @@ export default {
AI_PROVIDER_OPTION_OPENAI_COMPATIBLE: "Compatible con OpenAI / local",
AI_PROVIDER_PROFILE_MODAL_OPENAI_COMPATIBLE_HINT:
"Para LLM locales compatibles con OpenAI, usa una API key ficticia si no hace falta una real, para que Excalidraw marque el perfil como configurado.",
AI_PROVIDER_BASE_URL_EMPTY: "Derivada del tipo de proveedor",
AI_PROVIDER_API_KEY_SET: "Configurada",
AI_PROVIDER_API_KEY_NOT_SET: "Sin configurar",
AI_PROVIDER_EDIT: "Editar proveedor",
AI_PROVIDER_ADD: "Agregar proveedor",
AI_PROVIDER_REMOVE: "Eliminar proveedor",
AI_PROVIDER_RESTORE_DEFAULTS: "Restaurar proveedores predeterminados",
AI_PROVIDER_API_KEY_NAME: "Clave API de IA",
AI_PROVIDER_API_KEY_DESC:
"Clave API principal usada por la capa compartida de IA. El valor permanece oculto salvo cuando el campo tiene el foco.",
AI_PROVIDER_API_KEY_PLACEHOLDER: "Clave API del proveedor",
AI_PROVIDER_BASE_URL_NAME: "URL base de IA",
AI_PROVIDER_BASE_URL_DESC:
"URL base opcional del proveedor. Úsala para servidores locales compatibles con OpenAI o pasarelas autoalojadas. Puedes introducir una URL base como https://api.openai.com/v1 o un endpoint completo de chat como https://api.openai.com/v1/chat/completions; Excalidraw normalizará automáticamente los endpoints conocidos con formato OpenAI.",
AI_PROVIDER_BASE_URL_PLACEHOLDER: "p. ej.: https://api.openai.com/v1",
AI_PROVIDER_TEXT_ENDPOINT_NAME: "Anulación del endpoint de texto de IA",
AI_PROVIDER_TEXT_ENDPOINT_DESC:
"Anulación opcional del endpoint completo para solicitudes de texto y multimodales. Déjalo vacío para derivarlo de la URL base y el proveedor. La mayoría de usuarios no necesita rellenarlo.",
AI_PROVIDER_TEXT_ENDPOINT_PLACEHOLDER: "Endpoint completo opcional de texto",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_NAME:
"Anulación del endpoint de generación de imágenes de IA",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_DESC:
"Anulación opcional del endpoint completo para solicitudes de generación de imágenes. Déjalo vacío salvo que tu proveedor exponga esta función en una ruta no estándar.",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_PLACEHOLDER:
"Endpoint completo opcional de generación de imágenes",
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_NAME:
"Anulación del endpoint de edición de imágenes de IA",
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_DESC:
"Anulación opcional del endpoint completo para solicitudes de edición de imágenes. Déjalo vacío salvo que tu proveedor exponga esta función en una ruta no estándar.",
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_PLACEHOLDER:
"Endpoint completo opcional de edición de imágenes",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_NAME:
"Anulación del endpoint de variaciones de imágenes de IA",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_DESC:
"Anulación opcional del endpoint completo para solicitudes de variaciones de imágenes. Déjalo vacío salvo que tu proveedor exponga esta función en una ruta no estándar.",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_PLACEHOLDER:
"Endpoint completo opcional de variaciones de imágenes",
AI_PROVIDER_DEFAULT_TEXT_MODEL_NAME: "Modelo de texto y multimodal",
AI_PROVIDER_DEFAULT_TEXT_MODEL_DESC:
"Modelo usado para chat de texto y solicitudes con imágenes, como Mermaid chat, diagram-to-code y análisis de wireframes.<br>Proveedor: {{provider}} ({{providerType}})<br>Clave API: {{apiKey}}<br>Nombre del modelo: {{model}}<br>Endpoint: {{endpoint}}<br>Compatibilidad multimodal: {{multimodalSupport}}",
AI_PROVIDER_DEFAULT_TEXT_MODEL_PLACEHOLDER:
"p. ej.: gpt-5-mini, claude-sonnet, gemini-2.5-pro",
AI_PROVIDER_DEFAULT_VISION_MODEL_NAME: "Modelo de visión",
AI_PROVIDER_DEFAULT_VISION_MODEL_DESC:
"Modelo usado para tareas de comprensión de imágenes, como diagram-to-code o solicitudes con imagen y texto.<br>Proveedor: {{provider}} ({{providerType}})<br>Clave API: {{apiKey}}<br>Nombre del modelo: {{model}}<br>Endpoint: {{endpoint}}",
AI_PROVIDER_DEFAULT_VISION_MODEL_PLACEHOLDER:
"p. ej.: gpt-5-mini, claude-sonnet, gemini-2.5-flash",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_NAME: "Modelo de imagen",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_DESC:
"Modelo usado para generación de imágenes, transformaciones guiadas por prompt y ediciones con máscara. Usa los botones Editar, Agregar y Eliminar para modificar la lista.<br>Proveedor: {{provider}} ({{providerType}})<br>Clave API: {{apiKey}}<br>Nombre del modelo: {{model}}<br>Resoluciones compatibles: {{sizes}}<br>Transformaciones por prompt: {{supportsPromptImageTransforms}}<br>Ediciones con máscara: {{supportsMaskImageEdits}}",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "p. ej.: gpt-image-1",
AI_MODEL_CONFIG_DERIVED_ENDPOINT: "Derivado del proveedor seleccionado",
AI_MODEL_EDIT: "Editar modelo",
AI_MODEL_ADD: "Agregar modelo",
AI_MODEL_REMOVE: "Eliminar modelo",
AI_MODEL_RESTORE_DEFAULTS: "Restaurar modelos predeterminados",
AI_IMAGE_MODEL_CAPABILITIES_NAME: "Capacidades del modelo de imagen",
AI_IMAGE_MODEL_CAPABILITIES_DESC: `Administra aquí los metadatos de los modelos de imagen, como resoluciones compatibles, soporte para transformaciones por prompt y soporte para ediciones con máscara. Por ejemplo, puedes consultar los tamaños compatibles en la <a href="${URLs.PLATFORM_OPENAI_COM_DOCS_GUIDES_IMAGE_GENERATION}" target="_blank" rel="noopener noreferrer">documentación de generación de imágenes de OpenAI</a>.`,
AI_IMAGE_MODEL_CAPABILITIES_LOAD_DEFAULTS: "Restaurar valores conocidos",
AI_IMAGE_MODEL_CAPABILITIES_ADD_MODEL: "Agregar",
AI_IMAGE_MODEL_CAPABILITIES_EDIT_MODEL: "Editar",
AI_IMAGE_MODEL_CAPABILITIES_REMOVE_MODEL: "Eliminar entrada",
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_NAME:
"Entrada de modelo seleccionada",
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_DESC:
"<b>{{model}}</b><br>Resoluciones compatibles: {{sizes}}<br>Transformaciones por prompt: {{supportsPromptImageTransforms}}<br>Ediciones con máscara: {{supportsMaskImageEdits}}",
AI_IMAGE_MODEL_CAPABILITIES_SIZES_NAME: "Resoluciones compatibles",
AI_IMAGE_MODEL_CAPABILITIES_SIZES_PLACEHOLDER:
"1024x1024, 1536x1024, 1024x1536",
AI_IMAGE_MODEL_CAPABILITIES_EDITS_NAME: "Admite edición de imágenes",
AI_IMAGE_MODEL_CAPABILITIES_EDITS_DESC:
"Desactiva esta opción si el modelo puede generar imágenes pero no admite edición de imágenes ni máscaras.",
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_NAME:
"Transformaciones de imagen por prompt",
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_DESC:
@@ -480,6 +430,28 @@ export default {
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_DESC:
"Valor predeterminado para AIRequest.maxTokens. Limita las respuestas de texto o multimodales devueltas por el modelo. No afecta a los endpoints directos de generación o edición de imágenes.",
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_PLACEHOLDER: "p. ej.: 4096",
// AI Usage Metering - AIUsageModal
AI_USAGE_MODAL_TITLE: "Uso de IA (esta sesión)",
AI_USAGE_MODAL_TEXT_MODELS_HEADING: "Modelos de texto / multimodal",
AI_USAGE_MODAL_IMAGE_MODELS_HEADING: "Modelos de generación de imágenes",
AI_USAGE_MODAL_TABLE_COL_MODEL: "Modelo",
AI_USAGE_MODAL_TABLE_COL_INPUT: "Tokens de entrada",
AI_USAGE_MODAL_TABLE_COL_OUTPUT: "Tokens de salida",
AI_USAGE_MODAL_TABLE_COL_IMAGE_MODEL: "Modelo",
AI_USAGE_MODAL_TABLE_COL_GENERATIONS: "Imágenes generadas",
AI_USAGE_MODAL_TABLE_TOTAL: "Total",
AI_USAGE_MODAL_NO_USAGE:
"No se han realizado solicitudes de IA en esta sesión.",
AI_USAGE_MODAL_SESSION_NOTE:
"El uso se acumula solo para la sesión actual de Obsidian y no se conserva entre reinicios.",
AI_USAGE_MODAL_COPY_MARKDOWN: "Copiar como Markdown",
AI_USAGE_MODAL_COPY_SUCCESS: "Tabla de uso copiada al portapapeles.",
AI_USAGE_MODAL_COPY_FAILURE: "Error al copiar al portapapeles.",
AI_USAGE_MODAL_TABLE_MARKDOWN_TITLE: "## Uso de IA (esta sesión)",
// AI Usage button - Settings
AI_USAGE_SETTINGS_BUTTON_NAME: "Uso de tokens en la sesión",
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_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. ",
@@ -622,10 +594,6 @@ 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",
TRAY_MODE_NAME: "Habilitar modo de bandeja (tray-mode)",
COMPACT_MODE_NAME: "Modo compacto en tablets",
COMPACT_MODE_DESC:
"Anula el modo de bandeja en tablets, permitiendo que se use en su lugar el modo compacto nativo de Excalidraw.",
HOTKEY_OVERRIDE_HEAD: "Anulaciones de atajos de teclado",
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 ` +
@@ -694,7 +662,8 @@ export default {
LINKS_DESC:
`${labelCTRL()}+CLICK on <code>[[Elementos de Texto]]</code> para abrirlos como enlaces. ` +
"Si el texto seleccionado tiene más de un <code>[[enlace válido de Obsidian]]</code>, solo se abrirá el primero. " +
"Si el texto comienza como un enlace web válido (es decir, <code>https://</code> o <code>http://</code>), entonces " +
"Si el texto comienza como un enlace web válido (es decir, <code>http" +
"s://</code> o <code>http://</code>), entonces " +
"el complemento lo abrirá en un navegador. " +
"Cuando los archivos de Obsidian cambian, el <code>[[enlace]]</code> coincidente en tus bosquejos también cambiará. " +
"Si no quieres que el texto cambie accidentalmente en tus bosquejos, usa <code>[[enlaces|con alias]]</code>.",
@@ -793,9 +762,11 @@ export default {
QUOTE_TRANSCLUSION_REMOVE_DESC:
"Elimina el '> ' inicial de cada línea de la transclusión. Esto mejorará la legibilidad de las citas en transclusiones de solo texto.<br>" +
"<b><u>Activado:</u></b> Elimina el '> ' inicial<br><b><u>Desactivado:</u></b> No elimina el '> ' inicial (tenga en cuenta que se seguirá eliminando de la primera línea debido a la funcionalidad de la API de Obsidian).",
GET_URL_TITLE_NAME: "Usar iframely para resolver el título de la página",
GET_URL_TITLE_NAME: "Usar oEmbed para resolver el título de la página",
GET_URL_TITLE_DESC:
"Usa <code>http://iframely.server.crestify.com/iframely?url=</code> para obtener el título de la página al soltar un enlace en Excalidraw.",
"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.",
PDF_TO_IMAGE: "PDF a Image",
PDF_TO_IMAGE_SCALE_NAME: "Escala de conversión de PDF a imagen",
PDF_TO_IMAGE_SCALE_DESC:
@@ -927,6 +898,9 @@ export default {
EMBED_WIKILINK_NAME: "Incrustar bosquejo usando un enlace Wiki",
EMBED_WIKILINK_DESC:
"<b><u>Activado:</u></b> Excalidraw incrustará un [[enlace wiki]].<br><b><u>Desactivado:</u></b> Excalidraw incrustará un [markdown](enlace).",
EMBED_PLACEHOLDER_NAME: "Incrustar imagen de marcador de posición",
EMBED_PLACEHOLDER_DESC:
"Si está activado, incrusta una imagen de marcador de posición cuando no hay ningún dibujo. Si está desactivado, no se incrusta ninguna imagen.",
EXPORT_PNG_SCALE_NAME: "Escala de la imagen exportada en PNG",
EXPORT_PNG_SCALE_DESC: "La escala de tamaño de la imagen PNG exportada.",
EXPORT_BACKGROUND_NAME: "Exportar imagen con fondo",
@@ -980,10 +954,6 @@ export default {
PRESERVE_TEXT_AFTER_DRAWING_NAME: "Compatibilidad con Zotero y notas al pie",
PRESERVE_TEXT_AFTER_DRAWING_DESC:
"Preserva el texto después de la sección ## Bosquejo del archivo Markdown. Esto puede tener un impacto muy leve en el rendimiento al guardar bosquejos muy grandes.",
DEBUGMODE_NAME: "Habilitar mensajes de depuración",
DEBUGMODE_DESC:
"Recomiendo reiniciar Obsidian después de habilitar o deshabilitar esta configuración. Esto habilita los mensajes de depuración en la consola. Esto es útil para solucionar problemas. " +
`Si estás experimentando problemas con el complemento, por favor, habilita esta configuración, reproduce el problema e incluye el registro de la consola en el problema que reportes en <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}">GitHub</a>`,
SLIDING_PANES_NAME: "Soporte para el complemento Sliding Panes",
SLIDING_PANES_DESC:
"Necesitas reiniciar Obsidian para que este cambio surta efecto.<br>" +
@@ -1005,11 +975,6 @@ export default {
"Al habilitar esta función, los bosquejos que crees con el icono de la barra, las acciones de la paleta de comandos " +
"y el explorador de archivos serán todos archivos heredados *.excalidraw . Esta configuración también desactivará el mensaje de recordatorio " +
"cuando abras un archivo heredado para editar.",
MATHJAX_NAME: "Host(Servidor) de la librería Javascript MathJax(LaTeX)",
MATHJAX_DESC:
"Si estás usando ecuaciones LaTeX en Excalidraw, el complemento necesita cargar una librería de Javascript para ello. " +
"Algunos usuarios no pueden acceder a ciertos servidores. Si tienes problemas, intenta cambiar el servidor aquí. Es posible que necesites" +
"reiniciar Obsidian después de cerrar la configuración para que este cambio surta efecto.",
LATEX_DEFAULT_NAME: "Fórmula LaTeX predeterminada para nuevas ecuaciones",
LATEX_DEFAULT_DESC:
"Deja vacío si no quieres una fórmula predeterminada. Puedes añadir formato predeterminado aquí, como <code>\\color{white}</code>.",
@@ -1052,13 +1017,21 @@ 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.",
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?",
ENABLE_COMMAND_LINKS_CONFIRM_ENABLE: "Habilitar enlaces de comandos",
ENABLE_COMMAND_LINKS_CONFIRM_DENY: "No permitir",
ENABLE_COMMAND_LINKS_DESC:
"Si está habilitado, Excalidraw permitirá que los enlaces que comienzan con <code>cmd://</code> ejecuten acciones del Command Palette de Obsidian en los dibujos que abras a partir de ahora, hasta que desactives esta opción. " +
"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_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",
STARTUP_SCRIPT_BUTTON_CREATE: "Crear script de inicio",
STARTUP_SCRIPT_BUTTON_OPEN: "Abrir script de inicio",
STARTUP_SCRIPT_EXISTS: "El archivo del script de inicio ya existe",
FILETYPE_NAME:
"Muestra el indicador de tipo (✏️) para archivos excalidraw.md en el Explorador de archivos",
FILETYPE_DESC:
@@ -1160,9 +1133,6 @@ export default {
SELECT_TO_EMBED:
"Selecciona el bosquejo para insertar en el documento activo.",
SELECT_MD: "Selecciona el documento Markdown que quieres insertar",
SELECT_PDF: "Selecciona el documento PDF que quieres insertar.",
PDF_PAGES_HEADER: "¿Páginas a cargar?",
PDF_PAGES_DESC: "Formato: 1, 3-5, 7, 9-11",
//SelectCard.ts
TYPE_SECTION: "Escribe el nombre de la sección para seleccionar.",
@@ -1186,8 +1156,6 @@ export default {
//DRAWING_HAS_BACK_OF_THE_CARD: "Hay notas en el reverso de este dibujo.",
//ExcalidrawData.ts
LOAD_FROM_BACKUP:
"El archivo de Excalidraw estaba dañado. Cargando desde el archivo de backup(copia de seguridad).",
FONT_LOAD_SLOW:
"Cargando fuentes...\n\n Esto está tomando más tiempo de lo esperado. Si este retraso ocurre regularmente, puedes descargar las fuentes de forma local en tu Bóveda. \n\n" +
"(Click_izquierdo=para-descartar,Click_derecho=para-más-información).",
@@ -1464,10 +1432,6 @@ export default {
"Las capturas de pantalla incluirán elementos incrustables como páginas de Markdown, YouTube, sitios web, etc. Solo están disponibles en la versión de escritorio, no se pueden exportar automáticamente y solo admiten el formato PNG.",
SCREENSHOT_DESKTOP_ONLY:
"La función de captura de pantalla solo está disponible en escritorio.",
SCREENSHOT_FILE_SUCCESS: "Captura de pantalla guardada en la bóveda",
SCREENSHOT_CLIPBOARD_SUCCESS: "Captura de pantalla copiada al portapapeles",
SCREENSHOT_CLIPBOARD_ERROR:
"Error al copiar la captura de pantalla al portapapeles: ",
SCREENSHOT_ERROR:
"Error al capturar la pantalla - consulta el console log(registro de la consola)",
@@ -1487,16 +1451,24 @@ export default {
//ReleaseNotes.ts
RN_WELCOME: "Bienvenido a Excalidraw",
FIRST_RUN: `
El plugin Excalidraw para Obsidian es mucho más que “solo” una herramienta de dibujo. Gracias a su profunda integración con Obsidian, abre un paradigma completamente nuevo para la Gestión Visual del Conocimiento Personal (PKM).
//Excalidraw component
COMP_IMG: "Imágenes y archivos",
COMP_IMG_FROM_SYSTEM: "Importar desde el sistema",
COMP_IMG_ANY_FILE: "Cualquier archivo de la bóveda",
COMP_IMG_LaTeX: "Fórmula de LaTeX",
COMP_FRAME: "Acciones de Frame(marco)",
COMP_FRAME_HINT:
"Activar/desactivar Marker-Frame (marco de marcador). Marcos de guía para definir diapositivas/áreas de impresión/referencias de imagen. " +
"Se ocultan en las exportaciones de imágenes y no contienen elementos. Oculta/muestra los marcos desde el menú contextual del lienzo.",
<div style="text-align:center;margin-top:10px;">
<a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EE}" target="_blank"><img src="${URLs.SKETCH_YOUR_MIND_COM_IMAGES_LOGO_EE_PNG}" style="width:50%;"></a>
</div>
Para ayudarte a comenzar sin sentirte abrumado, te recomiendo mucho tomar el mini curso gratuito **[Excalidraw Essentials](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EE})**. Va directo al grano y te enseña los fundamentos de forma rápida y estructurada.
¡Tampoco tienes que resolverlo todo por tu cuenta! Únete a la **[Comunidad Sketch Your Mind](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM})** para conectar con otros pensadores visuales, compartir tus flujos de trabajo y construir juntos un sistema PKM sin fricción.
Si quieres ver lo que ya es posible hoy, aquí tienes una presentación de las funciones principales. Para mantenerte al día con las últimas novedades y explorar el PKM visual, suscríbete a mi canal de YouTube: [Visual PKM](${URLs.WWW_YOUTUBE_COM_VISUALPKM}).
¡Gracias y disfrútalo!
<div class="excalidraw-videoWrapper">
<a href="${URLs.WWW_YOUTUBE_COM_WATCH}" target="_blank"><img src="${URLs.I_YTIMG_COM_VI_P_Q6AVJGOWI_MAXRESDEFAULT_JPG}" style="width:100%;"></a>
</div>`,
//CustomEmbeddable.tsx
NOTICE_PDF_THEME:
+44 -81
View File
@@ -17,7 +17,6 @@ export default {
// main.ts
CONVERT_URL_TO_FILE: "Сохранить изображение из URL в локальный файл",
UNZIP_CURRENT_FILE: "Распаковать текущий файл Excalidraw",
ZIP_CURRENT_FILE: "Сжать текущий файл Excalidraw",
PUBLISH_SVG_CHECK:
"Obsidian Publish: Поиск устаревших экспортированных SVG и PNG-файлов",
EMBEDDABLE_PROPERTIES: "Свойства встраиваемых элементов",
@@ -89,6 +88,7 @@ export default {
INSERT_MD: "Вставка файла markdown из хранилища",
INSERT_PDF: "Вставить PDF-файл из хранилища",
UNIVERSAL_ADD_FILE: "Вставка ЛЮБОГО файла",
// Ключ совместимости, который запрашивает upstream Excalidraw через ExcalidrawPlugin.getLabel().
INSERT_CARD: "Добавить сноски",
CONVERT_CARD_TO_FILE: "Переместить сноску в файл",
ERROR_TRY_AGAIN: "Пожалуйста, попробуйте еще раз.",
@@ -127,11 +127,11 @@ export default {
<a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EE}" target="_blank"><img src="${URLs.SKETCH_YOUR_MIND_COM_IMAGES_LOGO_EE_PNG}" style="width:50%;"></a>
</div>
Чтобы начать без перегруза, очень рекомендую бесплатный мини-курс **[Excalidraw Essentials](" + URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EE + ")**. Он помогает быстро разобраться в главном и освоить базовые принципы в структурированном формате.
Чтобы начать без перегруза, очень рекомендую бесплатный мини-курс **[Excalidraw Essentials](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EE})**. Он помогает быстро разобраться в главном и освоить базовые принципы в структурированном формате.
Вам не обязательно разбираться во всем в одиночку. Присоединяйтесь к **[сообществу Sketch Your Mind](" + URLs.COMMUNITY_SKETCH_YOUR_MIND_COM + ")**, чтобы общаться с другими визуально мыслящими людьми, делиться своими рабочими процессами и выстраивать более плавную систему PKM.
Вам не обязательно разбираться во всем в одиночку. Присоединяйтесь к **[сообществу Sketch Your Mind](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM})**, чтобы общаться с другими визуально мыслящими людьми, делиться своими рабочими процессами и выстраивать более плавную систему PKM.
Если хотите увидеть, что уже возможно прямо сейчас, ниже есть обзор ключевых возможностей. А чтобы следить за новыми обновлениями и идеями по Visual PKM, подписывайтесь на мой YouTube-канал: [Visual PKM](" + URLs.WWW_YOUTUBE_COM_VISUALPKM + ").
Если хотите увидеть, что уже возможно прямо сейчас, ниже есть обзор ключевых возможностей. А чтобы следить за новыми обновлениями и идеями по Visual PKM, подписывайтесь на мой YouTube-канал: [Visual PKM](${URLs.WWW_YOUTUBE_COM_VISUALPKM}).
Спасибо и приятной работы!
@@ -178,7 +178,6 @@ export default {
EXPORT_IMAGE: `Экспорт изображения`,
OPEN_LINK:
"Открыть выделенный текст как ссылку\n(SHIFT+CLICK для открытия в новой панели)",
EXPORT_EXCALIDRAW: "Экспорт в файл .Excalidraw",
LINK_BUTTON_CLICK_NO_TEXT:
"Выберите элемент, содержащий внутреннюю или внешнюю ссылку.\n",
LINEAR_ELEMENT_LINK_CLICK_ERROR:
@@ -196,7 +195,6 @@ export default {
CONVERT_FILE: "Преобразование в новый формат",
BACKUP_AVAILABLE:
"Мы столкнулись с ошибкой при загрузке вашего рисунка. Это могло произойти, если Obsidian неожиданно закрылся во время операции сохранения. Например, если вы случайно закрыли Obsidian на своем мобильном устройстве во время сохранения.<br><br><b>ХОРОШАЯ НОВОСТЬ:</b> К счастью, доступна локальная резервная копия. Однако учтите, что если вы последний раз изменяли этот рисунок на другом устройстве (например, на планшете), а сейчас находитесь на рабочем столе, то на другом устройстве, скорее всего, имеется более свежая резервная копия.<br><br>Я рекомендую сначала попробовать открыть рисунок на другом устройстве и восстановить резервную копию из его локального хранилища.<br><br>Хотите загрузить резервную копию?",
BACKUP_RESTORED: "Резервная копия восстановлена",
CACHE_NOT_READY:
"Приношу извинения за неудобства, но при загрузке вашего файла произошла ошибка.<br><br><mark>Немного терпения может сэкономить вам массу времени...</mark><br><br>Плагин имеет резервный кэш, но похоже, что вы только что запустили Obsidian. Инициализация резервного кэша может занять некоторое время, обычно до минуты или больше, в зависимости от производительности вашего устройства. Вы получите уведомление в правом верхнем углу, когда инициализация кэша будет завершена.<br><br>Нажмите OK, чтобы попытаться загрузить файл снова и проверить, завершилась ли инициализация кэша. Если за этим сообщением вы видите абсолютно пустой файл, я рекомендую подождать, пока кэш резервного копирования будет готов, прежде чем продолжать. Кроме того, вы можете выбрать «Отмена», чтобы вручную исправить файл.<br>",
OBSIDIAN_TOOLS_PANEL: "Панель инструментов Obsidian",
@@ -223,8 +221,6 @@ export default {
WELCOME_DISCORD_LINK: "Присоединяйтесь к серверу Discord",
WELCOME_TWITTER_ARIA: "Следите за мной в Twitter",
WELCOME_TWITTER_LINK: "Следите за мной в Twitter",
WELCOME_LEARN_ARIA: "Изучение Visual PKM",
WELCOME_LEARN_LINK: "Запишитесь на семинар по визуальному мышлению",
WELCOME_DONATE_ARIA: "Пожертвовать на поддержку Excalidraw-Obsidian",
WELCOME_DONATE_LINK: "Скажите «Спасибо» и поддержите плагин.",
SAVE_IS_TAKING_LONG:
@@ -314,79 +310,26 @@ export default {
AI_PROVIDER_OPTION_OPENAI_COMPATIBLE: "Совместимый с OpenAI / локальный",
AI_PROVIDER_PROFILE_MODAL_OPENAI_COMPATIBLE_HINT:
"Для локальных LLM, совместимых с OpenAI, укажите фиктивный API key, если реальный не нужен, чтобы Excalidraw считал профиль настроенным.",
AI_PROVIDER_BASE_URL_EMPTY: "Определяется типом провайдера",
AI_PROVIDER_API_KEY_SET: "Настроено",
AI_PROVIDER_API_KEY_NOT_SET: "Не настроено",
AI_PROVIDER_EDIT: "Изменить провайдера",
AI_PROVIDER_ADD: "Добавить провайдера",
AI_PROVIDER_REMOVE: "Удалить провайдера",
AI_PROVIDER_RESTORE_DEFAULTS: "Восстановить провайдеров по умолчанию",
AI_PROVIDER_API_KEY_NAME: "API-ключ ИИ",
AI_PROVIDER_API_KEY_DESC:
"Основной API-ключ, используемый общим слоем ИИ. Значение скрыто, пока поле не находится в фокусе.",
AI_PROVIDER_API_KEY_PLACEHOLDER: "API-ключ провайдера",
AI_PROVIDER_BASE_URL_NAME: "Базовый URL ИИ",
AI_PROVIDER_BASE_URL_DESC:
"Необязательный базовый URL провайдера. Используйте его для локальных OpenAI-совместимых серверов или собственных шлюзов. Можно указать как базовый URL, например https://api.openai.com/v1, так и полный endpoint чата, например https://api.openai.com/v1/chat/completions; Excalidraw автоматически нормализует известные OpenAI-подобные endpoints.",
AI_PROVIDER_BASE_URL_PLACEHOLDER: "например: https://api.openai.com/v1",
AI_PROVIDER_TEXT_ENDPOINT_NAME: "Переопределение endpoint текста ИИ",
AI_PROVIDER_TEXT_ENDPOINT_DESC:
"Необязательное полное переопределение endpoint для текстовых и мультимодальных запросов. Оставьте пустым, чтобы он вычислялся из базового URL и провайдера. Большинству пользователей это поле не нужно.",
AI_PROVIDER_TEXT_ENDPOINT_PLACEHOLDER:
"Необязательный полный endpoint текста",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_NAME:
"Переопределение endpoint генерации изображений ИИ",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_DESC:
"Необязательное полное переопределение endpoint для запросов генерации изображений. Оставьте пустым, если только ваш провайдер не использует нестандартный путь.",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_PLACEHOLDER:
"Необязательный полный endpoint генерации изображений",
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_NAME:
"Переопределение endpoint редактирования изображений ИИ",
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_DESC:
"Необязательное полное переопределение endpoint для запросов редактирования изображений. Оставьте пустым, если только ваш провайдер не использует нестандартный путь.",
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_PLACEHOLDER:
"Необязательный полный endpoint редактирования изображений",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_NAME:
"Переопределение endpoint вариаций изображений ИИ",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_DESC:
"Необязательное полное переопределение endpoint для запросов вариаций изображений. Оставьте пустым, если только ваш провайдер не использует нестандартный путь.",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_PLACEHOLDER:
"Необязательный полный endpoint вариаций изображений",
AI_PROVIDER_DEFAULT_TEXT_MODEL_NAME: "Текстовая и мультимодальная модель",
AI_PROVIDER_DEFAULT_TEXT_MODEL_DESC:
"Модель для текстового чата и запросов с изображениями, например Mermaid chat, diagram-to-code и анализа вайрфреймов.<br>Провайдер: {{provider}} ({{providerType}})<br>API key: {{apiKey}}<br>Имя модели: {{model}}<br>Endpoint: {{endpoint}}<br>Мультимодальная поддержка: {{multimodalSupport}}",
AI_PROVIDER_DEFAULT_TEXT_MODEL_PLACEHOLDER:
"например: gpt-5-mini, claude-sonnet, gemini-2.5-pro",
AI_PROVIDER_DEFAULT_VISION_MODEL_NAME: "Vision-модель",
AI_PROVIDER_DEFAULT_VISION_MODEL_DESC:
"Модель для понимания изображений, например diagram-to-code или запросов с изображением и текстом.<br>Провайдер: {{provider}} ({{providerType}})<br>API key: {{apiKey}}<br>Имя модели: {{model}}<br>Endpoint: {{endpoint}}",
AI_PROVIDER_DEFAULT_VISION_MODEL_PLACEHOLDER:
"например: gpt-5-mini, claude-sonnet, gemini-2.5-flash",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_NAME: "Модель изображений",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_DESC:
"Модель для генерации изображений, prompt-редактирования и редактирования с маской. Используйте кнопки редактирования, добавления и удаления, чтобы менять список.<br>Провайдер: {{provider}} ({{providerType}})<br>API key: {{apiKey}}<br>Имя модели: {{model}}<br>Поддерживаемые разрешения: {{sizes}}<br>Prompt-редактирование: {{supportsPromptImageTransforms}}<br>Редактирование с маской: {{supportsMaskImageEdits}}",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "например: gpt-image-1",
AI_MODEL_CONFIG_DERIVED_ENDPOINT: "Определяется выбранным провайдером",
AI_MODEL_EDIT: "Изменить модель",
AI_MODEL_ADD: "Добавить модель",
AI_MODEL_REMOVE: "Удалить модель",
AI_MODEL_RESTORE_DEFAULTS: "Восстановить модели по умолчанию",
AI_IMAGE_MODEL_CAPABILITIES_NAME: "Возможности моделей изображений",
AI_IMAGE_MODEL_CAPABILITIES_DESC: `Здесь настраиваются метаданные моделей изображений: поддерживаемые разрешения, поддержка prompt-редактирования и поддержка масок. Например, поддерживаемые размеры можно посмотреть в <a href="${URLs.PLATFORM_OPENAI_COM_DOCS_GUIDES_IMAGE_GENERATION}" target="_blank" rel="noopener noreferrer">документации OpenAI по генерации изображений</a>.`,
AI_IMAGE_MODEL_CAPABILITIES_LOAD_DEFAULTS: "Восстановить известные значения",
AI_IMAGE_MODEL_CAPABILITIES_ADD_MODEL: "Добавить",
AI_IMAGE_MODEL_CAPABILITIES_EDIT_MODEL: "Изменить",
AI_IMAGE_MODEL_CAPABILITIES_REMOVE_MODEL: "Удалить запись",
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_NAME: "Выбранная запись модели",
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_DESC:
"<b>{{model}}</b><br>Поддерживаемые разрешения: {{sizes}}<br>Prompt-редактирование: {{supportsPromptImageTransforms}}<br>Редактирование с маской: {{supportsMaskImageEdits}}",
AI_IMAGE_MODEL_CAPABILITIES_SIZES_NAME: "Поддерживаемые разрешения",
AI_IMAGE_MODEL_CAPABILITIES_SIZES_PLACEHOLDER:
"1024x1024, 1536x1024, 1024x1536",
AI_IMAGE_MODEL_CAPABILITIES_EDITS_NAME:
"Поддерживает редактирование изображений",
AI_IMAGE_MODEL_CAPABILITIES_EDITS_DESC:
"Отключите, если модель умеет только генерировать изображения, но не поддерживает редактирование или маски.",
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_NAME:
"Prompt-редактирование изображений",
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_DESC:
@@ -428,6 +371,28 @@ export default {
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_DESC:
"Значение по умолчанию для AIRequest.maxTokens. Ограничивает текстовые и мультимодальные ответы модели. Не влияет на прямые endpoint'ы генерации и редактирования изображений.",
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_PLACEHOLDER: "например: 4096",
// AI Usage Metering - AIUsageModal
AI_USAGE_MODAL_TITLE: "Использование ИИ (текущая сессия)",
AI_USAGE_MODAL_TEXT_MODELS_HEADING: "Текстовые / мультимодальные модели",
AI_USAGE_MODAL_IMAGE_MODELS_HEADING: "Модели генерации изображений",
AI_USAGE_MODAL_TABLE_COL_MODEL: "Модель",
AI_USAGE_MODAL_TABLE_COL_INPUT: "Входящие токены",
AI_USAGE_MODAL_TABLE_COL_OUTPUT: "Исходящие токены",
AI_USAGE_MODAL_TABLE_COL_IMAGE_MODEL: "Модель",
AI_USAGE_MODAL_TABLE_COL_GENERATIONS: "Сгенерировано изображений",
AI_USAGE_MODAL_TABLE_TOTAL: "Итого",
AI_USAGE_MODAL_NO_USAGE: "В этой сессии запросы к ИИ не выполнялись.",
AI_USAGE_MODAL_SESSION_NOTE:
"Статистика накапливается только для текущей сессии Obsidian и не сохраняется между перезапусками.",
AI_USAGE_MODAL_COPY_MARKDOWN: "Копировать как Markdown",
AI_USAGE_MODAL_COPY_SUCCESS:
"Таблица использования скопирована в буфер обмена.",
AI_USAGE_MODAL_COPY_FAILURE: "Не удалось скопировать в буфер обмена.",
AI_USAGE_MODAL_TABLE_MARKDOWN_TITLE: "## Использование ИИ (текущая сессия)",
// AI Usage button - Settings
AI_USAGE_SETTINGS_BUTTON_NAME: "Использование токенов в сессии",
AI_USAGE_SETTINGS_BUTTON_DESC:
"Просмотр потребления токенов ИИ в текущей сессии Obsidian с разбивкой по моделям. Данные сбрасываются при перезапуске.",
SAVING_HEAD: "Сохранение",
SAVING_DESC:
"В разделе 'Сохранение' раздела Настройки Excalidraw вы можете настроить способ сохранения ваших чертежей. Сюда входят опции сжатия Excalidraw JSON в Markdown, установки интервалов автосохранения для настольных и мобильных компьютеров, определения форматов имен файлов, а также выбора расширения файла .excalidraw.md или .md. ",
@@ -607,7 +572,8 @@ export default {
LINKS_DESC:
`${labelCTRL()}+КЛИКНИТЕ на <code>[[Text Elements]]</code> чтобы открыть их как ссылки. ` +
"Если выделенный текст имеет более одного <code>[[valid Obsidian links]]</code>, только первый будет открыт. " +
"Если текст начинается как правильная веб-ссылка (то есть <code>https://</code> или <code>http://</code>), потом " +
"Если текст начинается как правильная веб-ссылка (то есть <code>http" +
"s://</code> или <code>http://</code>), потом " +
"плагин откроет его в браузере. " +
"Когда файлы Obsidian изменяются, соответствующие <code>[[link]]</code> в ваших чертежах также изменится. " +
"Если вы не хотите, чтобы текст случайно менялся в ваших чертежах, используйте <code>[[links|with aliases]]</code>.",
@@ -703,9 +669,11 @@ export default {
"Удалите начальный '>' из каждой строки включения. Это улучшит читаемость цитат в текстовых включениях <br>" +
"<b><u>Переключатель ВКЛ:</u></b> Удалить ведущие '> '<br><b><u>Переключатель ВЫКЛ:</u></b> Не удалить ведущие '> ' (обратите внимание, что он все равно будет удален из первой строки из-за функциональности API Obsidian.)",
GET_URL_TITLE_NAME:
"Используйте iframely для преобразования заголовка страницы",
"Используйте oEmbed для преобразования заголовка страницы",
GET_URL_TITLE_DESC:
"Используйте <code>http://iframely.server.crestify.com/iframely?url=</code> для получения заголовка страницы при переходе по ссылке в Excalidraw",
"Используйте <code>http" +
"s://noembed" +
".com/embed?url=</code> для получения заголовка страницы при переходе по HTTPS-ссылке в Excalidraw",
PDF_TO_IMAGE: "PDF в изображение",
PDF_TO_IMAGE_SCALE_NAME: "Шкала преобразования PDF в изображения",
PDF_TO_IMAGE_SCALE_DESC:
@@ -837,6 +805,9 @@ export default {
EMBED_WIKILINK_NAME: "Встраивание рисунка с помощью ссылки Wiki",
EMBED_WIKILINK_DESC:
"<b><u>Переключатель ВКЛ:</u></b> Excalidraw будет встраивать [[wiki link]].<br><b><u>Переключатель ВЫКЛ:</u></b> Excalidraw будет встраивать [markdown](link).",
EMBED_PLACEHOLDER_NAME: "Встраивать изображение-заглушку",
EMBED_PLACEHOLDER_DESC:
"Если включено, встраивает изображение-заглушку при отсутствии рисунка. Если отключено, изображение не встраивается.",
EXPORT_PNG_SCALE_NAME: "Масштаб экспортируемого изображения PNG",
EXPORT_PNG_SCALE_DESC: "Масштаб экспортируемого PNG-изображения",
EXPORT_BACKGROUND_NAME: "Экспорт изображения с фоном",
@@ -890,10 +861,6 @@ export default {
PRESERVE_TEXT_AFTER_DRAWING_NAME: "Совместимость Zotero и Footnotes",
PRESERVE_TEXT_AFTER_DRAWING_DESC:
"Сохраните текст после раздела ## Чертеж в файле Markdown. Это может незначительно повлиять на производительность при сохранении очень больших рисунков.",
DEBUGMODE_NAME: "Включить отладочные сообщения",
DEBUGMODE_DESC:
"Я рекомендую перезапустить Obsidian после включения/выключения этой настройки. Это позволяет выводить отладочные сообщения в консоль. Это полезно для устранения неполадок. " +
`Если у вас возникли проблемы с плагином, пожалуйста, включите эту настройку, воспроизведите проблему и включите журнал консоли в проблему, которую вы поднимаете на <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}">GitHub</a>`,
SLIDING_PANES_NAME:
"Поддержка плагина раздвижных областей окна (Sliding Panes plugin)",
SLIDING_PANES_DESC:
@@ -915,11 +882,6 @@ export default {
"При включении этой функции рисунки, которые вы создаете с помощью значка ленты, действий палитры команд, " +
"и в файловом проводнике, будут все старые файлы *.excalidraw. Эта настройка также отключит напоминание" +
"при открытии устаревшего файла для редактирования.",
MATHJAX_NAME: "Хост библиотеки javascript MathJax (LaTeX)",
MATHJAX_DESC:
"Если вы используете уравнения LaTeX в Excalidraw, то плагину необходимо загрузить библиотеку javascript для этого. " +
"Некоторые пользователи не могут получить доступ к определенным хост-серверам. Если у вас возникли проблемы, попробуйте сменить хост здесь. " +
"Возможно, вам придется перезапустить Obsidian после закрытия настроек, чтобы это изменение вступило в силу.",
LATEX_DEFAULT_NAME: "Формула LaTeX по умолчанию для новых уравнений",
LATEX_DEFAULT_DESC:
"Оставьте пустым, если вам не нужна формула по умолчанию. Здесь можно добавить форматирование по умолчанию, например <code>\\color{white}</code>.",
@@ -958,13 +920,21 @@ export default {
"Если эта настройка включена, Excalidraw будет выполнять <code>excalidraw-onload-script</code> на уровне файла во всех рисунках, которые вы откроете далее, пока вы не отключите эту настройку. " +
"Это создаёт риск, если вы загружаете Markdown-файлы из неизвестных источников: злоумышленник может использовать <code>excalidraw-onload-script</code> " +
"для запуска любой команды в Obsidian и потенциальной передачи данных в интернет. Включайте это только если доверяете файлу и его источнику.",
ENABLE_COMMAND_LINKS_NAME: "Включить ссылки-команды (cmd://)",
ENABLE_COMMAND_LINKS_CONFIRMATION:
"Эта ссылка запускает команду Obsidian через <code>cmd://</code>. Включить ссылки-команды?",
ENABLE_COMMAND_LINKS_CONFIRM_ENABLE: "Включить ссылки-команды",
ENABLE_COMMAND_LINKS_CONFIRM_DENY: "Не разрешать",
ENABLE_COMMAND_LINKS_DESC:
"Если настройка включена, Excalidraw позволит ссылкам, начинающимся с <code>cmd://</code>, выполнять команды Obsidian в рисунках, которые вы открываете, пока вы не отключите эту настройку. " +
"Это создаёт риск при открытии рисунков из неизвестных источников: вредоносный рисунок может превратить обычный клик в запуск привилегированной команды. " +
"Включайте это только если доверяете файлу и его источнику.",
STARTUP_SCRIPT_NAME: "Сценарий запуска",
STARTUP_SCRIPT_DESC:
"Если этот параметр установлен, excalidraw будет выполнять скрипт при запуске плагина. Это полезно, если вы хотите установить какой-либо из крючков Excalidraw Automate. " +
"Скрипт запуска - это файл в формате markdown, который должен содержать код javascript, который вы хотите выполнять при запуске Excalidraw.",
STARTUP_SCRIPT_BUTTON_CREATE: "Создание сценария запуска",
STARTUP_SCRIPT_BUTTON_OPEN: "Открыть сценарий запуска",
STARTUP_SCRIPT_EXISTS: "Файл сценария запуска уже существует",
FILETYPE_NAME:
"Тип отображения (✏️) для файлов excalidraw.md в Файловом Проводнике",
FILETYPE_DESC:
@@ -1045,9 +1015,6 @@ export default {
"Выберите существующий чертеж или введите имя нового чертежа, затем нажмите Enter.",
SELECT_TO_EMBED: "Выберите чертеж для вставки в активный документ.",
SELECT_MD: "Выберите документ в формате markdown для вставки.",
SELECT_PDF: "Выберите документ PDF для вставки.",
PDF_PAGES_HEADER: "Страницы для загрузки?",
PDF_PAGES_DESC: "Формат: 1, 3-5, 7, 9-11",
//SelectCard.ts
TYPE_SECTION: "Введите название раздела для выбора.",
@@ -1066,10 +1033,6 @@ export default {
"Ошибка выполнения сценария. Пожалуйста, найдите сообщение об ошибке в консоли разработчика.",
//ExcalidrawData.ts
LOAD_FROM_BACKUP:
"Файл Excalidraw был поврежден. Загрузка из резервного файла.",
//ObsidianMenu.tsx
GOTO_FULLSCREEN: "Переход в полноэкранный режим",
EXIT_FULLSCREEN: "Выход из полноэкранного режима",
TOGGLE_FULLSCREEN: "Переключить полноэкранный режим",
+53 -102
View File
@@ -16,7 +16,6 @@ export default {
// main.ts
CONVERT_URL_TO_FILE: "从 URL 下载图片到本地",
UNZIP_CURRENT_FILE: "解压当前 Excalidraw 文件",
ZIP_CURRENT_FILE: "压缩当前 Excalidraw 文件",
PUBLISH_SVG_CHECK: "Obsidian Publish:搜索过期的 SVG 和 PNG 导出文件",
EMBEDDABLE_PROPERTIES: "Embeddable 元素设置",
EMBEDDABLE_RELATIVE_ZOOM: "使元素的缩放级别等于当前绘图的缩放级别",
@@ -80,7 +79,18 @@ export default {
INSERT_PDF: "以图像形式嵌入 PDF 到当前绘图中",
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE: "以图像形式嵌入最后激活的 PDF 页面",
UNIVERSAL_ADD_FILE: "嵌入文件 (Insert ANY file)",
// 兼容性键:由 Excalidraw 上游通过 ExcalidrawPlugin.getLabel() 请求。
// 请在所有维护中的语言文件中保持这一组键同步。
ABOUT_LIBRARIES: "如何加载素材库",
INSERT_CARD: "插入“背景笔记”卡片",
COMP_IMG: "图片 & 文件",
COMP_IMG_FROM_SYSTEM: "从系统导入",
COMP_IMG_ANY_FILE: "仓库中任意文件",
COMP_IMG_LaTeX: "LaTeX 公式",
COMP_FRAME: "画框操作",
COMP_FRAME_HINT:
"切换标记画框。标记画框仅用于引导,用于定义幻灯片/打印区域/[[file#^frame=id]]," +
"导出时会隐藏;也不会包含元素。通过上下文菜单显示/隐藏标记画框。",
CONVERT_CARD_TO_FILE: "将“背景笔记”卡片保存到文件",
ERROR_TRY_AGAIN: "请重试。",
PASTE_CODEBLOCK: "粘贴代码块",
@@ -115,7 +125,6 @@ export default {
SELECT_LINK_TO_OPEN: "选择要打开的链接",
//ExcalidrawView.ts
ABOUT_LIBRARIES: "如何加载素材库",
ERROR_CANT_READ_FILEPATH: "错误,无法读取文件路径。正在改为导入文件",
NO_SEARCH_RESULT: "在绘图中未找到匹配的元素",
FORCE_SAVE_ABORTED: "自动保存被中止,因为文件正在保存中",
@@ -158,7 +167,6 @@ export default {
EXPORT_IMAGE: `导出为图片`,
OPEN_LINK: "打开所选元素里的链接 \n(按住 Shift 在新面板打开)",
EXCALIDRAW_SIDEPANEL: "Excalidraw 侧边面板",
EXPORT_EXCALIDRAW: "导出为 .excalidraw 文件(旧版绘图文件格式)",
LINK_BUTTON_CLICK_NO_TEXT: "请选择一个包含内部或外部链接的元素。\n",
LINEAR_ELEMENT_LINK_CLICK_ERROR:
`箭头和线条元素的链接无法通过 ${labelCTRL()} + 点击元素来跳转,因为这也会激活线条编辑器。\n` +
@@ -173,7 +181,6 @@ export default {
CONVERT_FILE: "转换为新格式",
BACKUP_AVAILABLE:
"加载绘图文件时出错,可能是由于 Obsidian 在上次保存时意外退出了(移动设备上更容易发生这种意外)。<br><br><b>好消息:</b>这台设备上存在备份。您是否想要恢复本设备上的备份?<br><br>(我建议您先尝试在最近使用过的其他设备上打开该绘图,以检查是否有更新的备份。)",
BACKUP_RESTORED: "已恢复备份",
BACKUP_SAVE_AS_FILE:
"此绘图为空。但有一个非空的备份可用。您想将其恢复为新文件并在新标签页中打开吗?",
BACKUP_SAVE: "恢复",
@@ -203,8 +210,6 @@ export default {
WELCOME_DISCORD_LINK: "加入 Discord 服务器",
WELCOME_TWITTER_ARIA: "在 Twitter 上关注我",
WELCOME_TWITTER_LINK: "在 Twitter 上关注我",
WELCOME_LEARN_ARIA: "学习 Visual PKM(可视化个人知识管理)",
WELCOME_LEARN_LINK: "报名加入视觉思维研讨会",
WELCOME_DONATE_ARIA: "捐赠以支持 Excalidraw-Obsidian",
WELCOME_DONATE_LINK: "感谢并支持此插件。",
SAVE_IS_TAKING_LONG: "保存您之前的文件花费的时间较长,请稍候…",
@@ -237,8 +242,6 @@ export default {
LINKS_DISCORD_ARIA: "加入视觉思维研讨会 Discord 服务器",
LINKS_DISCORD: "加入社区",
LINKS_TWITTER: "关注我",
LINKS_VTW_ARIA: "学习 Visual PKM、Excalidraw、Obsidian、ExcaliBrain 等内容",
LINKS_VTW: "加入研讨会",
LINKS_BOOK_ARIA: "阅读我的视觉思维著作《Sketch Your Mind》",
LINKS_BOOK: "阅读书籍",
LINKS_WIKI: "插件维基",
@@ -325,73 +328,26 @@ export default {
AI_PROVIDER_OPTION_OPENAI_COMPATIBLE: "OpenAI 兼容 / 本地",
AI_PROVIDER_PROFILE_MODAL_OPENAI_COMPATIBLE_HINT:
"对于本地的 OpenAI 兼容 LLM,如果不需要真实 API key,请填写一个虚拟 key,否则 Excalidraw 不会把该配置识别为已配置。",
AI_PROVIDER_BASE_URL_EMPTY: "由提供商类型推导",
AI_PROVIDER_API_KEY_SET: "已配置",
AI_PROVIDER_API_KEY_NOT_SET: "未配置",
AI_PROVIDER_EDIT: "编辑提供商",
AI_PROVIDER_ADD: "添加提供商",
AI_PROVIDER_REMOVE: "删除提供商",
AI_PROVIDER_RESTORE_DEFAULTS: "恢复默认提供商",
AI_PROVIDER_API_KEY_NAME: "AI API key",
AI_PROVIDER_API_KEY_DESC:
"共享 AI 层使用的主 API key。除非输入框获得焦点,否则该值会被隐藏。",
AI_PROVIDER_API_KEY_PLACEHOLDER: "提供商 API key",
AI_PROVIDER_BASE_URL_NAME: "AI 基础 URL",
AI_PROVIDER_BASE_URL_DESC:
"可选的提供商基础 URL。可用于本地 OpenAI 兼容服务器或自托管网关。您既可以填写类似 https://api.openai.com/v1 的基础 URL,也可以填写类似 https://api.openai.com/v1/chat/completions 的完整聊天 endpoint;Excalidraw 会自动规范化已知的 OpenAI 风格 endpoint。",
AI_PROVIDER_BASE_URL_PLACEHOLDER: "例如:https://api.openai.com/v1",
AI_PROVIDER_TEXT_ENDPOINT_NAME: "AI 文本 endpoint 覆盖",
AI_PROVIDER_TEXT_ENDPOINT_DESC:
"可选的完整 endpoint 覆盖,用于文本和多模态请求。留空时会根据基础 URL 和提供商自动推导。大多数用户无需填写。",
AI_PROVIDER_TEXT_ENDPOINT_PLACEHOLDER: "可选的完整文本 endpoint",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_NAME: "AI 图像生成 endpoint 覆盖",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_DESC:
"可选的完整 endpoint 覆盖,用于图像生成请求。除非您的提供商使用非标准路径,否则请留空。",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_PLACEHOLDER:
"可选的完整图像生成 endpoint",
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_NAME: "AI 图像编辑 endpoint 覆盖",
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_DESC:
"可选的完整 endpoint 覆盖,用于图像编辑请求。除非您的提供商使用非标准路径,否则请留空。",
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_PLACEHOLDER: "可选的完整图像编辑 endpoint",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_NAME: "AI 图像变体 endpoint 覆盖",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_DESC:
"可选的完整 endpoint 覆盖,用于图像变体请求。除非您的提供商使用非标准路径,否则请留空。",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_PLACEHOLDER:
"可选的完整图像变体 endpoint",
AI_PROVIDER_DEFAULT_TEXT_MODEL_NAME: "文本与多模态模型",
AI_PROVIDER_DEFAULT_TEXT_MODEL_DESC:
"用于文本聊天和图像理解请求的模型,例如 Mermaid chat、diagram-to-code 和线框图分析。<br>提供商:{{provider}}({{providerType}})<br>API key:{{apiKey}}<br>模型名称:{{model}}<br>Endpoint:{{endpoint}}<br>多模态支持:{{multimodalSupport}}",
AI_PROVIDER_DEFAULT_TEXT_MODEL_PLACEHOLDER:
"例如:gpt-5-mini、claude-sonnet、gemini-2.5-pro",
AI_PROVIDER_DEFAULT_VISION_MODEL_NAME: "视觉模型",
AI_PROVIDER_DEFAULT_VISION_MODEL_DESC:
"用于 diagram-to-code 或图文混合提示等图像理解任务的模型。<br>提供商:{{provider}}({{providerType}})<br>API key:{{apiKey}}<br>模型名称:{{model}}<br>Endpoint:{{endpoint}}",
AI_PROVIDER_DEFAULT_VISION_MODEL_PLACEHOLDER:
"例如:gpt-5-mini、claude-sonnet、gemini-2.5-flash",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_NAME: "图像模型",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_DESC:
"用于图像生成、基于提示词的图像变换和蒙版编辑的模型。使用“编辑”“添加”“删除”按钮修改列表。<br>提供商:{{provider}}({{providerType}})<br>API key:{{apiKey}}<br>模型名称:{{model}}<br>支持的分辨率:{{sizes}}<br>提示词图像变换:{{supportsPromptImageTransforms}}<br>蒙版编辑:{{supportsMaskImageEdits}}",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "例如:gpt-image-1",
AI_MODEL_CONFIG_DERIVED_ENDPOINT: "由所选提供商推导",
AI_MODEL_EDIT: "编辑模型",
AI_MODEL_ADD: "添加模型",
AI_MODEL_REMOVE: "删除模型",
AI_MODEL_RESTORE_DEFAULTS: "恢复默认模型",
AI_IMAGE_MODEL_CAPABILITIES_NAME: "图像模型能力",
AI_IMAGE_MODEL_CAPABILITIES_DESC: `在这里管理图像模型元数据,例如支持的分辨率、是否支持提示词图像变换以及是否支持蒙版编辑。例如,你可以在 <a href="${URLs.PLATFORM_OPENAI_COM_DOCS_GUIDES_IMAGE_GENERATION}" target="_blank" rel="noopener noreferrer">OpenAI 图像生成文档</a> 中查询支持的尺寸。`,
AI_IMAGE_MODEL_CAPABILITIES_LOAD_DEFAULTS: "恢复已知默认值",
AI_IMAGE_MODEL_CAPABILITIES_ADD_MODEL: "添加",
AI_IMAGE_MODEL_CAPABILITIES_EDIT_MODEL: "编辑",
AI_IMAGE_MODEL_CAPABILITIES_REMOVE_MODEL: "删除条目",
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_NAME: "当前选中的模型条目",
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_DESC:
"<b>{{model}}</b><br>支持的分辨率:{{sizes}}<br>提示词图像变换:{{supportsPromptImageTransforms}}<br>蒙版编辑:{{supportsMaskImageEdits}}",
AI_IMAGE_MODEL_CAPABILITIES_SIZES_NAME: "支持的分辨率",
AI_IMAGE_MODEL_CAPABILITIES_SIZES_PLACEHOLDER:
"1024x1024, 1536x1024, 1024x1536",
AI_IMAGE_MODEL_CAPABILITIES_EDITS_NAME: "支持图像编辑",
AI_IMAGE_MODEL_CAPABILITIES_EDITS_DESC:
"如果该模型只能生成图像但不支持图像编辑或蒙版,请关闭此项。",
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_NAME: "提示词图像变换",
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_DESC:
"当模型支持使用输入图像加文本提示词进行无蒙版编辑时,请启用此项。",
@@ -424,6 +380,27 @@ export default {
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_DESC:
"AIRequest.maxTokens 的默认值。它限制模型返回的文本或多模态响应,不影响直接图像生成或图像编辑 endpoint。",
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_PLACEHOLDER: "例如:4096",
// AI Usage Metering - AIUsageModal
AI_USAGE_MODAL_TITLE: "AI 用量(本次会话)",
AI_USAGE_MODAL_TEXT_MODELS_HEADING: "文本 / 多模态模型",
AI_USAGE_MODAL_IMAGE_MODELS_HEADING: "图像生成模型",
AI_USAGE_MODAL_TABLE_COL_MODEL: "模型",
AI_USAGE_MODAL_TABLE_COL_INPUT: "输入 Token",
AI_USAGE_MODAL_TABLE_COL_OUTPUT: "输出 Token",
AI_USAGE_MODAL_TABLE_COL_IMAGE_MODEL: "模型",
AI_USAGE_MODAL_TABLE_COL_GENERATIONS: "已生成图像数",
AI_USAGE_MODAL_TABLE_TOTAL: "合计",
AI_USAGE_MODAL_NO_USAGE: "本次会话尚未发起任何 AI 请求。",
AI_USAGE_MODAL_SESSION_NOTE:
"用量仅在当前 Obsidian 会话内累积,重启后将重置。",
AI_USAGE_MODAL_COPY_MARKDOWN: "复制为 Markdown",
AI_USAGE_MODAL_COPY_SUCCESS: "用量表已复制到剪贴板。",
AI_USAGE_MODAL_COPY_FAILURE: "复制到剪贴板失败。",
AI_USAGE_MODAL_TABLE_MARKDOWN_TITLE: "## AI 用量(本次会话)",
// AI Usage button - Settings
AI_USAGE_SETTINGS_BUTTON_NAME: "会话 Token 用量",
AI_USAGE_SETTINGS_BUTTON_DESC:
"按模型查看当前 Obsidian 会话的 AI Token 消耗情况。重启后用量将重置。",
SAVING_HEAD: "保存",
SAVING_DESC: "包括:压缩,自动保存的时间间隔,文件的命名格式和扩展名等。",
COMPRESS_NAME: "压缩 Excalidraw JSON",
@@ -564,14 +541,6 @@ export default {
MODE_TRAY: "Tray-mode",
MODE_PHONE: "Phone-mode",
REAPPLY_UI_MODE_BUTTON: "重新应用 UI 模式",
TRAY_MODE_NAME: "启用托盘模式",
PREFER_COMPACT_MODE_DESKTOP_NAME: "在桌面端偏好紧凑模式",
PREFER_COMPACT_MODE_DESKTOP_DESC:
"切换托盘模式时,开启该项,Excalidraw 将在紧凑模式与托盘模式之间切换。" +
"关闭该项,则在完整模式与托盘模式之间切换。",
COMPACT_MODE_NAME: "在平板端偏好紧凑模式",
COMPACT_MODE_DESC:
"该项允许平板端和桌面端设置不同的默认模式。你可以在平板端默认使用紧凑模式,而在桌面端默认使用托盘模式。",
HOTKEY_OVERRIDE_HEAD: "热键覆盖",
HOTKEY_OVERRIDE_DESC:
`一些 Excalidraw 的热键,如 ${labelCTRL()}+Enter 用于编辑文本,或 ${labelCTRL()}+K 用于创建元素链接,` +
@@ -636,7 +605,8 @@ export default {
LINKS_DESC:
`按住 ${labelCTRL()} 并点击包含 <code>[[链接]]</code> 的文本元素可以打开其中的链接。<br>` +
"如果所选文本元素包含多个 <code>[[有效的内部链接]]</code> ,只会打开第一个链接;<br>" +
"如果所选文本元素包含有效的 URL 链接(如 <code>https://</code> 或 <code>http://</code>)," +
"如果所选文本元素包含有效的 URL 链接(如 <code>http" +
"s://</code> 或 <code>http://</code>)," +
"插件会在浏览器中打开链接。<br>" +
"链接的源文件被重命名时,绘图中相应的 <code>[[内部链接]]</code> 也会同步更新。" +
"若您不愿绘图中的链接外观因此而变化,可使用 <code>[[内部链接|别名]]</code>。",
@@ -684,12 +654,6 @@ export default {
"文本元素处于 PREVIEW 模式时,在内部链接的两侧显示中括号。<br>" +
"可为某个绘图单独设置该项,方法是在其 frontmatter 中添加如 <code>"
}${FRONTMATTER_KEYS["link-brackets"].name}: true/false</code> 的键值对。`,
/*LINK_DETECTION_NAME: "Do not auto-create element link from text",
LINK_DETECTION_DESC: "By default, Excalidraw will automatically create an element link when you type or paste a valid " +
"[[Obsidian link]] or a (web link) into a Text Element. This link overrides whatever element link you may have set previously. " +
"Even if you delete the element link, if the text element contains a valid link, Excalidraw will recreate the element link. " +
"If you turn this setting on, Excalidraw will not auto-create element links from text. You can still manually set element links " +
`Links in the text will still be navigable when you ${labelCTRL()} + CLICK the element.`,*/
LINK_PREFIX_NAME: "内部链接的前缀",
LINK_PREFIX_DESC: `${
"文本元素处于 PREVIEW 模式时,如果其中包含链接,则添加此前缀。<br>" +
@@ -737,9 +701,11 @@ export default {
QUOTE_TRANSCLUSION_REMOVE_DESC:
"不显示 MD-Transclusion 中每一行行首的 > 符号,以提高纯文本 MD-Transclusion 的可读性。<br>" +
"<b>开启:</b>隐藏 > 符号。<b>关闭:</b>不隐藏 > 符号。<br>注意,由于 Obsidian API 的原因,首行行首的 > 符号不会被隐藏。",
GET_URL_TITLE_NAME: "使用 iframly 获取页面标题",
GET_URL_TITLE_NAME: "使用 oEmbed 获取页面标题",
GET_URL_TITLE_DESC:
"拖动链接到 Excalidraw 时,使用 <code>http://iframely.server.crestify.com/iframely?url=</code> 来获取页面的标题。",
"拖动链接到 Excalidraw 时,使用 <code>http" +
"s://noembed" +
".com/embed?url=</code> 来获取 HTTPS 页面标题。",
PDF_TO_IMAGE: "以图像形式嵌入到绘图中的 PDF",
PDF_TO_IMAGE_SCALE_NAME: "分辨率",
PDF_TO_IMAGE_SCALE_DESC:
@@ -868,6 +834,9 @@ export default {
"“嵌入绘图到当前 Markdown 文档中”系列命令产生的内部链接类型",
EMBED_WIKILINK_DESC:
"<b>开启:</b>将产生 <code>![[Wiki 链接]]</code>。<b>关闭:</b>将产生 <code>![](Markdown 链接)</code>。",
EMBED_PLACEHOLDER_NAME: "嵌入占位图像",
EMBED_PLACEHOLDER_DESC:
"如果启用,当没有绘图时,将嵌入占位图像。如果禁用,则不嵌入任何图像。",
EXPORT_PNG_SCALE_NAME: "导出 PNG 图片的比例",
EXPORT_PNG_SCALE_DESC: "导出 PNG 图片的大小比例",
EXPORT_BACKGROUND_NAME: "导出图片包含背景",
@@ -919,10 +888,6 @@ export default {
PRESERVE_TEXT_AFTER_DRAWING_NAME: "兼容 Zotero 和脚注(footnotes)",
PRESERVE_TEXT_AFTER_DRAWING_DESC:
"保留 Excalidraw Markdown 中 <code>## Drawing</code> 部分之后的文本内容。保存非常大的绘图时,这可能会造成微小的性能影响。",
DEBUGMODE_NAME: "开启 debug 信息",
DEBUGMODE_DESC:
"我建议在启用/禁用该项后重新启动 Obsidian。这将在控制台中启用调试消息,有助于排查问题。" +
`如果您在使用插件时遇到问题,请启用该项,重现问题,并在 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}">GitHub</a> 上提出的问题中包含控制台日志。`,
SLIDING_PANES_NAME: "支持 Sliding Panes 插件",
SLIDING_PANES_DESC:
"该项需要重启 Obsidian 才能生效。<br>" +
@@ -943,11 +908,6 @@ export default {
"开启此功能后,您通过功能区按钮、命令面板、" +
"文件浏览器等创建的绘图都将是旧格式(*.excalidraw)。" +
"此外,您打开旧格式绘图文件时将不再收到警告消息。",
MATHJAX_NAME: "MathJax (LaTeX) 的 javascript 库服务器",
MATHJAX_DESC:
"如果您在绘图中使用 LaTeX,插件需要从服务器获取并加载一个 javascript 库。" +
"如果您的网络无法访问某些库服务器,可以尝试通过该项更换库服务器。" +
"该项可能需要重启 Obsidian 才能生效。",
LATEX_DEFAULT_NAME: "插入 LaTeX 时的默认公式",
LATEX_DEFAULT_DESC:
"允许留空。允许使用类似 <code>\\color{white}</code> 的格式化表达式。",
@@ -989,13 +949,21 @@ export default {
"启用后,Excalidraw 会在你之后打开的所有绘图中执行文件级别的 <code>excalidraw-onload-script</code>,直到你关闭此设置。 " +
"如果你从未知来源下载 Markdown 文件,这会带来风险:恶意行为者可以利用 <code>excalidraw-onload-script</code> " +
"在 Obsidian 中运行任意命令,并且有可能将数据传输到互联网。只有在你信任该文件及其来源时才启用此功能。",
ENABLE_COMMAND_LINKS_NAME: "启用命令链接(cmd://)",
ENABLE_COMMAND_LINKS_CONFIRMATION:
"此链接会通过 <code>cmd://</code> 触发 Obsidian 命令。是否启用命令链接?",
ENABLE_COMMAND_LINKS_CONFIRM_ENABLE: "启用命令链接",
ENABLE_COMMAND_LINKS_CONFIRM_DENY: "不允许",
ENABLE_COMMAND_LINKS_DESC:
"启用后,Excalidraw 将允许以 <code>cmd://</code> 开头的链接在你之后打开的绘图中执行 Obsidian 命令面板动作,直到你关闭此设置。 " +
"如果你打开来自未知来源的绘图,这会带来风险:恶意绘图可以让一次普通点击触发高权限命令。 " +
"只有在你信任该文件及其来源时才启用此功能。",
STARTUP_SCRIPT_NAME: "起动脚本",
STARTUP_SCRIPT_DESC:
"插件启动时将自动执行该脚本。可用于为您的 Excalidraw 自动化脚本设置钩子。" +
"起动脚本请用 javascript 代码编写,并保存为 Markdown 格式。",
STARTUP_SCRIPT_BUTTON_CREATE: "创建起动脚本",
STARTUP_SCRIPT_BUTTON_OPEN: "打开起动脚本",
STARTUP_SCRIPT_EXISTS: "起动脚本已存在",
FILETYPE_NAME: "在文件浏览器中为 excalidraw.md 文件添加类型标识符(如 ✏️)",
FILETYPE_DESC: "可通过下一选项来自定义类型标识符。",
FILETAG_NAME: "excalidraw.md 文件的类型标识符",
@@ -1085,9 +1053,6 @@ export default {
"选择已有绘图,或者输入新绘图文件的名称,然后按回车。",
SELECT_TO_EMBED: "选择要嵌入到当前 Markdown 文档中的绘图",
SELECT_MD: "选择要以图像形式嵌入到当前绘图中的 Markdown 文档",
SELECT_PDF: "选择要以图像形式嵌入到当前绘图中的 PDF",
PDF_PAGES_HEADER: "页码范围",
PDF_PAGES_DESC: "示例:1, 3-5, 7, 9-11",
//SelectCard.ts
TYPE_SECTION: "输入章节标题进行选择",
@@ -1108,7 +1073,6 @@ export default {
//DRAWING_HAS_BACK_OF_THE_CARD: "There are notes on the back of this drawing.",
//ExcalidrawData.ts
LOAD_FROM_BACKUP: "Excalidraw 文件已损坏。尝试从备份文件中加载。",
FONT_LOAD_SLOW:
"正在加载字体…\n\n这比预期花费的时间更长。如果这种延迟经常发生,您可以将字体下载到您的仓库中。\n\n" +
"(点击=忽略提示,右键=更多信息)",
@@ -1368,9 +1332,6 @@ export default {
EXPORTDIALOG_SCREENSHOT_DESC:
"截图将包含可嵌入的内容,如 Markdown 页面、YouTube、网站等。它们仅在桌面端可用,无法自动导出,并且仅支持 PNG 格式。",
SCREENSHOT_DESKTOP_ONLY: "截图功能仅在桌面端可用",
SCREENSHOT_FILE_SUCCESS: "截图已保存到仓库",
SCREENSHOT_CLIPBOARD_SUCCESS: "截图已复制到剪贴板",
SCREENSHOT_CLIPBOARD_ERROR: "无法复制截图到剪贴板:",
SCREENSHOT_ERROR: "截图出错 - 请查看控制台日志",
//exportUtils.ts
@@ -1395,11 +1356,11 @@ Obsidian 的 Excalidraw 插件远不只是一个“画图工具”。由于它
<a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EE}" target="_blank"><img src="${URLs.SKETCH_YOUR_MIND_COM_IMAGES_LOGO_EE_PNG}" style="width:50%;"></a>
</div>
如果你想顺利入门、避免一开始就被大量功能淹没,我非常推荐免费的 **[Excalidraw Essentials](" + URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EE + ")** 微课程。它能帮你快速抓住重点,用清晰的结构掌握核心基础。
如果你想顺利入门、避免一开始就被大量功能淹没,我非常推荐免费的 **[Excalidraw Essentials](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EE})** 微课程。它能帮你快速抓住重点,用清晰的结构掌握核心基础。
你也不必独自摸索。欢迎加入 **[Sketch Your Mind 社区](" + URLs.COMMUNITY_SKETCH_YOUR_MIND_COM + ")**,与其他视觉思考者交流、分享工作流,一起构建更顺滑的 PKM 系统。
你也不必独自摸索。欢迎加入 **[Sketch Your Mind 社区](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM})**,与其他视觉思考者交流、分享工作流,一起构建更顺滑的 PKM 系统。
如果你想先看看它现在都能做到什么,下面有一个核心功能展示。想持续了解最新更新,并进一步探索 Visual PKM,也欢迎订阅我的 YouTube 频道:[Visual PKM](" + URLs.WWW_YOUTUBE_COM_VISUALPKM + ")。
如果你想先看看它现在都能做到什么,下面有一个核心功能展示。想持续了解最新更新,并进一步探索 Visual PKM,也欢迎订阅我的 YouTube 频道:[Visual PKM](${URLs.WWW_YOUTUBE_COM_VISUALPKM})。
感谢使用,祝你玩得开心!
@@ -1408,16 +1369,6 @@ Obsidian 的 Excalidraw 插件远不只是一个“画图工具”。由于它
</div>
`,
//Excalidraw component
COMP_IMG: "图片 & 文件",
COMP_IMG_FROM_SYSTEM: "从系统导入",
COMP_IMG_ANY_FILE: "仓库中任意文件",
COMP_IMG_LaTeX: "LaTeX 公式",
COMP_FRAME: "画框操作",
COMP_FRAME_HINT:
"切换标记画框。标记画框仅用于引导,用于定义幻灯片/打印区域/[[file#^frame=id]]," +
"导出时会隐藏;也不会包含元素。通过上下文菜单显示/隐藏标记画框。",
//CustomEmbeddable.tsx
NOTICE_PDF_THEME:
"已覆盖 PDF 主题。\n" +
+53 -102
View File
@@ -16,7 +16,6 @@ export default {
// main.ts
CONVERT_URL_TO_FILE: "從 URL 下載圖片到本地",
UNZIP_CURRENT_FILE: "解壓當前 Excalidraw 檔案",
ZIP_CURRENT_FILE: "壓縮當前 Excalidraw 檔案",
PUBLISH_SVG_CHECK: "Obsidian Publish:搜尋過期的 SVG 和 PNG 匯出檔案",
EMBEDDABLE_PROPERTIES: "Embeddable 元素設定",
EMBEDDABLE_RELATIVE_ZOOM: "使元素的縮放級別等於當前繪圖的縮放級別",
@@ -80,7 +79,18 @@ export default {
INSERT_PDF: "以影像形式嵌入 PDF 到當前繪圖中",
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE: "以影像形式嵌入最後啟用的 PDF 頁面",
UNIVERSAL_ADD_FILE: "嵌入檔案 (Insert ANY file)",
// 相容性鍵:由 Excalidraw 上游透過 ExcalidrawPlugin.getLabel() 請求。
// 請在所有維護中的語言檔保持這一組鍵同步。
ABOUT_LIBRARIES: "如何載入素材庫",
INSERT_CARD: "插入“背景筆記”卡片",
COMP_IMG: "圖片 & 檔案",
COMP_IMG_FROM_SYSTEM: "從系統匯入",
COMP_IMG_ANY_FILE: "倉庫中任意檔案",
COMP_IMG_LaTeX: "LaTeX 公式",
COMP_FRAME: "畫框操作",
COMP_FRAME_HINT:
"切換標記畫框。標記畫框僅用於引導,用於定義幻燈片/列印區域/[[file#^frame=id]]," +
"匯出時會隱藏;也不會包含元素。透過上下文選單顯示/隱藏標記畫框。",
CONVERT_CARD_TO_FILE: "將“背景筆記”卡片儲存到檔案",
ERROR_TRY_AGAIN: "請重試。",
PASTE_CODEBLOCK: "貼上程式碼塊",
@@ -115,7 +125,6 @@ export default {
SELECT_LINK_TO_OPEN: "選擇要開啟的連結",
//ExcalidrawView.ts
ABOUT_LIBRARIES: "如何載入素材庫",
ERROR_CANT_READ_FILEPATH: "錯誤,無法讀取檔案路徑。正在改為匯入檔案",
NO_SEARCH_RESULT: "在繪圖中未找到匹配的元素",
FORCE_SAVE_ABORTED: "自動儲存被中止,因為檔案正在儲存中",
@@ -158,7 +167,6 @@ export default {
EXPORT_IMAGE: `匯出為圖片`,
OPEN_LINK: "開啟所選元素裡的連結 \n(按住 Shift 在新面板開啟)",
EXCALIDRAW_SIDEPANEL: "Excalidraw 側邊面板",
EXPORT_EXCALIDRAW: "匯出為 .excalidraw 檔案(舊版繪圖檔案格式)",
LINK_BUTTON_CLICK_NO_TEXT: "請選擇一個包含內部或外部連結的元素。\n",
LINEAR_ELEMENT_LINK_CLICK_ERROR:
`箭頭和線條元素的連結無法透過 ${labelCTRL()} + 點選元素來跳轉,因為這也會啟用線條編輯器。\n` +
@@ -173,7 +181,6 @@ export default {
CONVERT_FILE: "轉換為新格式",
BACKUP_AVAILABLE:
"載入繪圖檔案時出錯,可能是由於 Obsidian 在上次儲存時意外退出了(移動裝置上更容易發生這種意外)。<br><br><b>好訊息:</b>這臺裝置上存在備份。您是否想要恢復本裝置上的備份?<br><br>(我建議您先嚐試在最近使用過的其他裝置上開啟該繪圖,以檢查是否有更新的備份。)",
BACKUP_RESTORED: "已恢復備份",
BACKUP_SAVE_AS_FILE:
"此繪圖為空。但有一個非空的備份可用。您想將其恢復為新檔案並在新標籤頁中開啟嗎?",
BACKUP_SAVE: "恢復",
@@ -203,8 +210,6 @@ export default {
WELCOME_DISCORD_LINK: "加入 Discord 伺服器",
WELCOME_TWITTER_ARIA: "在 Twitter 上關注我",
WELCOME_TWITTER_LINK: "在 Twitter 上關注我",
WELCOME_LEARN_ARIA: "學習 Visual PKM(視覺化個人知識管理)",
WELCOME_LEARN_LINK: "報名加入視覺思維研討會",
WELCOME_DONATE_ARIA: "捐贈以支援 Excalidraw-Obsidian",
WELCOME_DONATE_LINK: "感謝並支援此外掛。",
SAVE_IS_TAKING_LONG: "儲存您之前的檔案花費的時間較長,請稍候…",
@@ -237,8 +242,6 @@ export default {
LINKS_DISCORD_ARIA: "加入視覺思維研討會 Discord 伺服器",
LINKS_DISCORD: "加入社群",
LINKS_TWITTER: "關注我",
LINKS_VTW_ARIA: "學習 Visual PKM、Excalidraw、Obsidian、ExcaliBrain 等內容",
LINKS_VTW: "加入研討會",
LINKS_BOOK_ARIA: "閱讀我的視覺思維著作《Sketch Your Mind》",
LINKS_BOOK: "閱讀書籍",
LINKS_WIKI: "外掛維基",
@@ -325,73 +328,26 @@ export default {
AI_PROVIDER_OPTION_OPENAI_COMPATIBLE: "OpenAI 相容 / 本地",
AI_PROVIDER_PROFILE_MODAL_OPENAI_COMPATIBLE_HINT:
"對於本機的 OpenAI 相容 LLM,如果不需要真正的 API key,請填入一個虛擬 key,否則 Excalidraw 不會將此設定識別為已設定。",
AI_PROVIDER_BASE_URL_EMPTY: "由供應商類型推導",
AI_PROVIDER_API_KEY_SET: "已設定",
AI_PROVIDER_API_KEY_NOT_SET: "未設定",
AI_PROVIDER_EDIT: "編輯供應商",
AI_PROVIDER_ADD: "新增供應商",
AI_PROVIDER_REMOVE: "刪除供應商",
AI_PROVIDER_RESTORE_DEFAULTS: "還原預設供應商",
AI_PROVIDER_API_KEY_NAME: "AI API key",
AI_PROVIDER_API_KEY_DESC:
"共享 AI 層使用的主要 API key。除非輸入欄位取得焦點,否則該值會被隱藏。",
AI_PROVIDER_API_KEY_PLACEHOLDER: "供應商 API key",
AI_PROVIDER_BASE_URL_NAME: "AI 基礎 URL",
AI_PROVIDER_BASE_URL_DESC:
"可選的供應商基礎 URL。可用於本地 OpenAI 相容伺服器或自架閘道。您可以填入像 https://api.openai.com/v1 這樣的基礎 URL,也可以填入像 https://api.openai.com/v1/chat/completions 這樣的完整聊天 endpoint;Excalidraw 會自動正規化已知的 OpenAI 風格 endpoint。",
AI_PROVIDER_BASE_URL_PLACEHOLDER: "例如:https://api.openai.com/v1",
AI_PROVIDER_TEXT_ENDPOINT_NAME: "AI 文字 endpoint 覆寫",
AI_PROVIDER_TEXT_ENDPOINT_DESC:
"可選的完整 endpoint 覆寫,用於文字與多模態請求。留空時會根據基礎 URL 和供應商自動推導。大多數使用者不需要填寫。",
AI_PROVIDER_TEXT_ENDPOINT_PLACEHOLDER: "可選的完整文字 endpoint",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_NAME: "AI 圖像生成 endpoint 覆寫",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_DESC:
"可選的完整 endpoint 覆寫,用於圖像生成請求。除非您的供應商使用非標準路徑,否則請留空。",
AI_PROVIDER_IMAGE_GENERATION_ENDPOINT_PLACEHOLDER:
"可選的完整圖像生成 endpoint",
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_NAME: "AI 圖像編輯 endpoint 覆寫",
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_DESC:
"可選的完整 endpoint 覆寫,用於圖像編輯請求。除非您的供應商使用非標準路徑,否則請留空。",
AI_PROVIDER_IMAGE_EDITS_ENDPOINT_PLACEHOLDER: "可選的完整圖像編輯 endpoint",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_NAME: "AI 圖像變體 endpoint 覆寫",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_DESC:
"可選的完整 endpoint 覆寫,用於圖像變體請求。除非您的供應商使用非標準路徑,否則請留空。",
AI_PROVIDER_IMAGE_VARIATIONS_ENDPOINT_PLACEHOLDER:
"可選的完整圖像變體 endpoint",
AI_PROVIDER_DEFAULT_TEXT_MODEL_NAME: "文字與多模態模型",
AI_PROVIDER_DEFAULT_TEXT_MODEL_DESC:
"用於文字聊天與圖像理解請求的模型,例如 Mermaid chat、diagram-to-code 與線框圖分析。<br>供應商:{{provider}}({{providerType}})<br>API key:{{apiKey}}<br>模型名稱:{{model}}<br>Endpoint:{{endpoint}}<br>多模態支援:{{multimodalSupport}}",
AI_PROVIDER_DEFAULT_TEXT_MODEL_PLACEHOLDER:
"例如:gpt-5-mini、claude-sonnet、gemini-2.5-pro",
AI_PROVIDER_DEFAULT_VISION_MODEL_NAME: "視覺模型",
AI_PROVIDER_DEFAULT_VISION_MODEL_DESC:
"用於 diagram-to-code 或圖文混合提示等圖像理解任務的模型。<br>供應商:{{provider}}({{providerType}})<br>API key:{{apiKey}}<br>模型名稱:{{model}}<br>Endpoint:{{endpoint}}",
AI_PROVIDER_DEFAULT_VISION_MODEL_PLACEHOLDER:
"例如:gpt-5-mini、claude-sonnet、gemini-2.5-flash",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_NAME: "圖像模型",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_DESC:
"用於圖像生成、提示詞驅動的圖像轉換與遮罩編輯的模型。使用「編輯」、「新增」、「刪除」按鈕修改列表。<br>供應商:{{provider}}({{providerType}})<br>API key:{{apiKey}}<br>模型名稱:{{model}}<br>支援的解析度:{{sizes}}<br>提示詞圖像轉換:{{supportsPromptImageTransforms}}<br>遮罩編輯:{{supportsMaskImageEdits}}",
AI_PROVIDER_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "例如:gpt-image-1",
AI_MODEL_CONFIG_DERIVED_ENDPOINT: "由所選供應商推導",
AI_MODEL_EDIT: "編輯模型",
AI_MODEL_ADD: "新增模型",
AI_MODEL_REMOVE: "刪除模型",
AI_MODEL_RESTORE_DEFAULTS: "還原預設模型",
AI_IMAGE_MODEL_CAPABILITIES_NAME: "圖像模型能力",
AI_IMAGE_MODEL_CAPABILITIES_DESC: `在這裡管理圖像模型中繼資料,例如支援的解析度、是否支援提示詞圖像轉換,以及是否支援遮罩編輯。舉例來說,你可以在 <a href="${URLs.PLATFORM_OPENAI_COM_DOCS_GUIDES_IMAGE_GENERATION}" target="_blank" rel="noopener noreferrer">OpenAI 圖像生成文件</a> 中查詢支援的尺寸。`,
AI_IMAGE_MODEL_CAPABILITIES_LOAD_DEFAULTS: "還原已知預設值",
AI_IMAGE_MODEL_CAPABILITIES_ADD_MODEL: "新增",
AI_IMAGE_MODEL_CAPABILITIES_EDIT_MODEL: "編輯",
AI_IMAGE_MODEL_CAPABILITIES_REMOVE_MODEL: "刪除項目",
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_NAME: "目前選取的模型項目",
AI_IMAGE_MODEL_CAPABILITIES_CURRENT_ENTRY_DESC:
"<b>{{model}}</b><br>支援的解析度:{{sizes}}<br>提示詞圖像轉換:{{supportsPromptImageTransforms}}<br>遮罩編輯:{{supportsMaskImageEdits}}",
AI_IMAGE_MODEL_CAPABILITIES_SIZES_NAME: "支援的解析度",
AI_IMAGE_MODEL_CAPABILITIES_SIZES_PLACEHOLDER:
"1024x1024, 1536x1024, 1024x1536",
AI_IMAGE_MODEL_CAPABILITIES_EDITS_NAME: "支援圖像編輯",
AI_IMAGE_MODEL_CAPABILITIES_EDITS_DESC:
"如果模型只能生成圖像但不支援圖像編輯或遮罩,請關閉此項。",
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_NAME: "提示詞圖像轉換",
AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_DESC:
"當模型支援使用輸入圖像與文字提示詞進行無遮罩編輯時,請啟用此項。",
@@ -424,6 +380,27 @@ export default {
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_DESC:
"AIRequest.maxTokens 的預設值。它限制模型回傳的文字或多模態回應,不影響直接圖像生成或圖像編輯 endpoint。",
AI_PROVIDER_DEFAULT_MAX_RESPONSE_TOKENS_PLACEHOLDER: "例如:4096",
// AI Usage Metering - AIUsageModal
AI_USAGE_MODAL_TITLE: "AI 用量(本次工作階段)",
AI_USAGE_MODAL_TEXT_MODELS_HEADING: "文字 / 多模態模型",
AI_USAGE_MODAL_IMAGE_MODELS_HEADING: "圖像生成模型",
AI_USAGE_MODAL_TABLE_COL_MODEL: "模型",
AI_USAGE_MODAL_TABLE_COL_INPUT: "輸入 Token",
AI_USAGE_MODAL_TABLE_COL_OUTPUT: "輸出 Token",
AI_USAGE_MODAL_TABLE_COL_IMAGE_MODEL: "模型",
AI_USAGE_MODAL_TABLE_COL_GENERATIONS: "已生成圖像數",
AI_USAGE_MODAL_TABLE_TOTAL: "合計",
AI_USAGE_MODAL_NO_USAGE: "本次工作階段尚未發起任何 AI 請求。",
AI_USAGE_MODAL_SESSION_NOTE:
"用量僅在當前 Obsidian 工作階段內累積,重新啟動後將重置。",
AI_USAGE_MODAL_COPY_MARKDOWN: "複製為 Markdown",
AI_USAGE_MODAL_COPY_SUCCESS: "用量表已複製到剪貼簿。",
AI_USAGE_MODAL_COPY_FAILURE: "複製到剪貼簿失敗。",
AI_USAGE_MODAL_TABLE_MARKDOWN_TITLE: "## AI 用量(本次工作階段)",
// AI Usage button - Settings
AI_USAGE_SETTINGS_BUTTON_NAME: "工作階段 Token 用量",
AI_USAGE_SETTINGS_BUTTON_DESC:
"按模型查看目前 Obsidian 工作階段的 AI Token 消耗情況。重新啟動後用量將重置。",
SAVING_HEAD: "儲存",
SAVING_DESC: "包括:壓縮,自動儲存的時間間隔,檔案的命名格式和副檔名等。",
COMPRESS_NAME: "壓縮 Excalidraw JSON",
@@ -564,14 +541,6 @@ export default {
MODE_TRAY: "Tray-mode",
MODE_PHONE: "Phone-mode",
REAPPLY_UI_MODE_BUTTON: "重新應用 UI 模式",
TRAY_MODE_NAME: "啟用托盤模式",
PREFER_COMPACT_MODE_DESKTOP_NAME: "在桌面端偏好緊湊模式",
PREFER_COMPACT_MODE_DESKTOP_DESC:
"切換托盤模式時,開啟該項,Excalidraw 將在緊湊模式與托盤模式之間切換。" +
"關閉該項,則在完整模式與托盤模式之間切換。",
COMPACT_MODE_NAME: "在平板端偏好緊湊模式",
COMPACT_MODE_DESC:
"該項允許平板端和桌面端設定不同的預設模式。你可以在平板端預設使用緊湊模式,而在桌面端預設使用托盤模式。",
HOTKEY_OVERRIDE_HEAD: "熱鍵覆蓋",
HOTKEY_OVERRIDE_DESC:
`一些 Excalidraw 的熱鍵,如 ${labelCTRL()}+Enter 用於編輯文字,或 ${labelCTRL()}+K 用於建立元素連結,` +
@@ -636,7 +605,8 @@ export default {
LINKS_DESC:
`按住 ${labelCTRL()} 並點選包含 <code>[[連結]]</code> 的文字元素可以開啟其中的連結。<br>` +
"如果所選文字元素包含多個 <code>[[有效的內部連結]]</code> ,只會開啟第一個連結;<br>" +
"如果所選文字元素包含有效的 URL 連結(如 <code>https://</code> 或 <code>http://</code>)," +
"如果所選文字元素包含有效的 URL 連結(如 <code>http" +
"s://</code> 或 <code>http://</code>)," +
"外掛會在瀏覽器中開啟連結。<br>" +
"連結的原始檔被重新命名時,繪圖中相應的 <code>[[內部連結]]</code> 也會同步更新。" +
"若您不願繪圖中的連結外觀因此而變化,可使用 <code>[[內部連結|別名]]</code>。",
@@ -684,12 +654,6 @@ export default {
"文字元素處於 PREVIEW 模式時,在內部連結的兩側顯示中括號。<br>" +
"可為某個繪圖單獨設定該項,方法是在其 frontmatter 中新增如 <code>"
}${FRONTMATTER_KEYS["link-brackets"].name}: true/false</code> 的鍵值對。`,
/*LINK_DETECTION_NAME: "Do not auto-create element link from text",
LINK_DETECTION_DESC: "By default, Excalidraw will automatically create an element link when you type or paste a valid " +
"[[Obsidian link]] or a (web link) into a Text Element. This link overrides whatever element link you may have set previously. " +
"Even if you delete the element link, if the text element contains a valid link, Excalidraw will recreate the element link. " +
"If you turn this setting on, Excalidraw will not auto-create element links from text. You can still manually set element links " +
`Links in the text will still be navigable when you ${labelCTRL()} + CLICK the element.`,*/
LINK_PREFIX_NAME: "內部連結的字首",
LINK_PREFIX_DESC: `${
"文字元素處於 PREVIEW 模式時,如果其中包含連結,則新增此字首。<br>" +
@@ -737,9 +701,11 @@ export default {
QUOTE_TRANSCLUSION_REMOVE_DESC:
"不顯示 MD-Transclusion 中每一行行首的 > 符號,以提高純文字 MD-Transclusion 的可讀性。<br>" +
"<b>開啟:</b>隱藏 > 符號。<b>關閉:</b>不隱藏 > 符號。<br>注意,由於 Obsidian API 的原因,首行行首的 > 符號不會被隱藏。",
GET_URL_TITLE_NAME: "使用 iframly 獲取頁面標題",
GET_URL_TITLE_NAME: "使用 oEmbed 獲取頁面標題",
GET_URL_TITLE_DESC:
"拖動連結到 Excalidraw 時,使用 <code>http://iframely.server.crestify.com/iframely?url=</code> 來獲取頁面的標題。",
"拖動連結到 Excalidraw 時,使用 <code>http" +
"s://noembed" +
".com/embed?url=</code> 來獲取 HTTPS 頁面標題。",
PDF_TO_IMAGE: "以影像形式嵌入到繪圖中的 PDF",
PDF_TO_IMAGE_SCALE_NAME: "解析度",
PDF_TO_IMAGE_SCALE_DESC:
@@ -868,6 +834,9 @@ export default {
"“嵌入繪圖到當前 Markdown 文件中”系列命令產生的內部連結型別",
EMBED_WIKILINK_DESC:
"<b>開啟:</b>將產生 <code>![[Wiki 連結]]</code>。<b>關閉:</b>將產生 <code>![](Markdown 連結)</code>。",
EMBED_PLACEHOLDER_NAME: "嵌入占位圖像",
EMBED_PLACEHOLDER_DESC:
"如果啟用,當沒有繪圖時,將嵌入占位圖像。如果禁用,則不嵌入任何圖像。",
EXPORT_PNG_SCALE_NAME: "匯出 PNG 圖片的比例",
EXPORT_PNG_SCALE_DESC: "匯出 PNG 圖片的大小比例",
EXPORT_BACKGROUND_NAME: "匯出圖片包含背景",
@@ -919,10 +888,6 @@ export default {
PRESERVE_TEXT_AFTER_DRAWING_NAME: "相容 Zotero 和腳註(footnotes)",
PRESERVE_TEXT_AFTER_DRAWING_DESC:
"保留 Excalidraw Markdown 中 <code>## Drawing</code> 部分之後的文字內容。儲存非常大的繪圖時,這可能會造成微小的效能影響。",
DEBUGMODE_NAME: "開啟 debug 資訊",
DEBUGMODE_DESC:
"我建議在啟用/停用該項後重新啟動 Obsidian。這將在控制檯中啟用除錯訊息,有助於排查問題。" +
`如果您在使用外掛時遇到問題,請啟用該項,重現問題,並在 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}">GitHub</a> 上提出的問題中包含控制檯日誌。`,
SLIDING_PANES_NAME: "支援 Sliding Panes 外掛",
SLIDING_PANES_DESC:
"該項需要重啟 Obsidian 才能生效。<br>" +
@@ -943,11 +908,6 @@ export default {
"開啟此功能後,您透過功能區按鈕、命令面板、" +
"檔案瀏覽器等建立的繪圖都將是舊格式(*.excalidraw)。" +
"此外,您開啟舊格式繪圖檔案時將不再收到警告訊息。",
MATHJAX_NAME: "MathJax (LaTeX) 的 javascript 庫伺服器",
MATHJAX_DESC:
"如果您在繪圖中使用 LaTeX,外掛需要從伺服器獲取並載入一個 javascript 庫。" +
"如果您的網路無法訪問某些庫伺服器,可以嘗試透過該項更換庫伺服器。" +
"該項可能需要重啟 Obsidian 才能生效。",
LATEX_DEFAULT_NAME: "插入 LaTeX 時的預設公式",
LATEX_DEFAULT_DESC:
"允許留空。允許使用類似 <code>\\color{white}</code> 的格式化表示式。",
@@ -989,13 +949,21 @@ export default {
"啟用後,Excalidraw 會在你之後開啟的所有繪圖中執行檔案層級的 <code>excalidraw-onload-script</code>,直到你關閉此設定。 " +
"如果你從未知來源下載 Markdown 檔案,這會帶來風險:惡意人士可以使用 <code>excalidraw-onload-script</code> " +
"在 Obsidian 中執行任何命令,並且有可能將資料傳送到網際網路。只有在你信任該檔案及其來源時才啟用此功能。",
ENABLE_COMMAND_LINKS_NAME: "啟用命令連結(cmd://)",
ENABLE_COMMAND_LINKS_CONFIRMATION:
"此連結會透過 <code>cmd://</code> 觸發 Obsidian 命令。是否啟用命令連結?",
ENABLE_COMMAND_LINKS_CONFIRM_ENABLE: "啟用命令連結",
ENABLE_COMMAND_LINKS_CONFIRM_DENY: "不允許",
ENABLE_COMMAND_LINKS_DESC:
"啟用後,Excalidraw 將允許以 <code>cmd://</code> 開頭的連結在你之後開啟的繪圖中執行 Obsidian 命令面板動作,直到你關閉此設定。 " +
"如果你開啟來自未知來源的繪圖,這會帶來風險:惡意繪圖可以讓一次普通點擊觸發高權限命令。 " +
"只有在你信任該檔案及其來源時才啟用此功能。",
STARTUP_SCRIPT_NAME: "起動指令碼",
STARTUP_SCRIPT_DESC:
"外掛啟動時將自動執行該指令碼。可用於為您的 Excalidraw 自動化指令碼設定鉤子。" +
"起動指令碼請用 javascript 程式碼編寫,並儲存為 Markdown 格式。",
STARTUP_SCRIPT_BUTTON_CREATE: "建立起動指令碼",
STARTUP_SCRIPT_BUTTON_OPEN: "開啟起動指令碼",
STARTUP_SCRIPT_EXISTS: "起動指令碼已存在",
FILETYPE_NAME: "在檔案瀏覽器中為 excalidraw.md 檔案新增型別識別符號(如 ✏️)",
FILETYPE_DESC: "可透過下一選項來自定義型別識別符號。",
FILETAG_NAME: "excalidraw.md 檔案的型別識別符號",
@@ -1085,9 +1053,6 @@ export default {
"選擇已有繪圖,或者輸入新繪圖檔案的名稱,然後按回車。",
SELECT_TO_EMBED: "選擇要嵌入到當前 Markdown 文件中的繪圖",
SELECT_MD: "選擇要以影像形式嵌入到當前繪圖中的 Markdown 文件",
SELECT_PDF: "選擇要以影像形式嵌入到當前繪圖中的 PDF",
PDF_PAGES_HEADER: "頁碼範圍",
PDF_PAGES_DESC: "示例:1, 3-5, 7, 9-11",
//SelectCard.ts
TYPE_SECTION: "輸入章節標題進行選擇",
@@ -1108,7 +1073,6 @@ export default {
//DRAWING_HAS_BACK_OF_THE_CARD: "There are notes on the back of this drawing.",
//ExcalidrawData.ts
LOAD_FROM_BACKUP: "Excalidraw 檔案已損壞。嘗試從備份檔案中載入。",
FONT_LOAD_SLOW:
"正在載入字型…\n\n這比預期花費的時間更長。如果這種延遲經常發生,您可以將字型下載到您的倉庫中。\n\n" +
"(點選=忽略提示,右鍵=更多資訊)",
@@ -1368,9 +1332,6 @@ export default {
EXPORTDIALOG_SCREENSHOT_DESC:
"截圖將包含可嵌入的內容,如 Markdown 頁面、YouTube、網站等。它們僅在桌面端可用,無法自動匯出,並且僅支援 PNG 格式。",
SCREENSHOT_DESKTOP_ONLY: "截圖功能僅在桌面端可用",
SCREENSHOT_FILE_SUCCESS: "截圖已儲存到倉庫",
SCREENSHOT_CLIPBOARD_SUCCESS: "截圖已複製到剪貼簿",
SCREENSHOT_CLIPBOARD_ERROR: "無法複製截圖到剪貼簿:",
SCREENSHOT_ERROR: "截圖出錯 - 請檢視控制檯日誌",
//exportUtils.ts
@@ -1395,11 +1356,11 @@ Obsidian 的 Excalidraw 外掛遠不只是「畫圖工具」。由於它與 Obsi
<a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EE}" target="_blank"><img src="${URLs.SKETCH_YOUR_MIND_COM_IMAGES_LOGO_EE_PNG}" style="width:50%;"></a>
</div>
如果你想順利上手、避免一開始就被大量功能淹沒,我非常推薦免費的 **[Excalidraw Essentials](" + URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EE + ")** 微課程。它能幫你快速抓住重點,用清楚的結構掌握核心基礎。
如果你想順利上手、避免一開始就被大量功能淹沒,我非常推薦免費的 **[Excalidraw Essentials](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EE})** 微課程。它能幫你快速抓住重點,用清楚的結構掌握核心基礎。
你也不必自己摸索。歡迎加入 **[Sketch Your Mind 社群](" + URLs.COMMUNITY_SKETCH_YOUR_MIND_COM + ")**,與其他視覺思考者交流、分享工作流程,一起打造更順暢的 PKM 系統。
你也不必自己摸索。歡迎加入 **[Sketch Your Mind 社群](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM})**,與其他視覺思考者交流、分享工作流程,一起打造更順暢的 PKM 系統。
如果你想先看看它現在能做到什麼,下面有一段核心功能展示。若想持續了解最新更新,並進一步探索 Visual PKM,也歡迎訂閱我的 YouTube 頻道:[Visual PKM](" + URLs.WWW_YOUTUBE_COM_VISUALPKM + ")。
如果你想先看看它現在能做到什麼,下面有一段核心功能展示。若想持續了解最新更新,並進一步探索 Visual PKM,也歡迎訂閱我的 YouTube 頻道:[Visual PKM](${URLs.WWW_YOUTUBE_COM_VISUALPKM})。
感謝使用,祝你玩得愉快!
@@ -1408,16 +1369,6 @@ Obsidian 的 Excalidraw 外掛遠不只是「畫圖工具」。由於它與 Obsi
</div>
`,
//Excalidraw component
COMP_IMG: "圖片 & 檔案",
COMP_IMG_FROM_SYSTEM: "從系統匯入",
COMP_IMG_ANY_FILE: "倉庫中任意檔案",
COMP_IMG_LaTeX: "LaTeX 公式",
COMP_FRAME: "畫框操作",
COMP_FRAME_HINT:
"切換標記畫框。標記畫框僅用於引導,用於定義幻燈片/列印區域/[[file#^frame=id]]," +
"匯出時會隱藏;也不會包含元素。透過上下文選單顯示/隱藏標記畫框。",
//CustomEmbeddable.tsx
NOTICE_PDF_THEME:
"已覆蓋 PDF 主題。\n" +
+12 -11
View File
@@ -3,13 +3,12 @@ import {
FileId,
} from "@zsviczian/excalidraw/types/element/src/types";
import { BinaryFileData } from "@zsviczian/excalidraw/types/excalidraw/types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { Notice } from "obsidian";
import { getEA } from "src/core";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { cloneElement } from "src/utils/excalidrawViewHelpers";
import { nanoid } from "src/constants/constants";
import { mainDocument, nanoid } from "src/constants/constants";
import { svgToBase64 } from "../utils/utils";
import { ExportSettings } from "src/types/exportUtilTypes";
@@ -58,7 +57,7 @@ export class CropImage {
this.setBoundingEl(maskEA, "white"); //the bbox should not mask the image. White lets everything through.
elements.forEach((el) => {
const newEl = cloneElement(el) as Mutable<ExcalidrawElement>;
const newEl = cloneElement(el);
if (el.type !== "image" && el.type !== "frame") {
newEl.opacity = 100;
maskEA.elementsDict[el.id] = newEl;
@@ -84,12 +83,14 @@ export class CropImage {
private setBoundingEl(ea: ExcalidrawAutomate, bgColor: string) {
const { topX, topY, width, height } = this.bbox;
ea.style.backgroundColor = bgColor;
ea.style.strokeColor = "transparent";
ea.style.strokeWidth = 0;
ea.style.strokeStyle = "solid";
ea.style.fillStyle = "solid";
ea.style.roughness = 0;
ea.setStyle({
backgroundColor: bgColor,
strokeColor: "transparent",
strokeWidth: 0,
strokeStyle: "solid",
fillStyle: "solid",
roughness: 0,
});
ea.addRect(topX, topY, width, height);
}
@@ -206,11 +207,11 @@ export class CropImage {
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2026
const svgData = svg.outerHTML;
//const svgData = new XMLSerializer().serializeToString(svg);
const canvas = document.createElement("canvas");
const canvas = mainDocument.createElement("canvas");
const context = canvas.getContext("2d");
if (!context) {
reject("Unable to get 2D context");
reject(new Error("Unable to get 2D context"));
return;
}
+68 -9
View File
@@ -1,7 +1,17 @@
import { App, Modal, Notice, Setting } from "obsidian";
import { t } from "src/lang/helpers";
import { AIImageModelConfig, AIModelConfig } from "src/types/AIUtilTypes";
import {
AIImageModelConfig,
AIModelConfig,
AIProviderProfile,
} from "src/types/AIUtilTypes";
import {
getGeminiSupportedSizes,
isGeminiImageModel,
} from "src/utils/geminiImageModelUtils";
import { isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
import { showElement } from "src/utils/styleUtils";
import { hideElement } from "src/utils/styleUtils";
type SaveHandler<TConfig extends AIModelConfig> = (
modelId: string,
@@ -12,6 +22,7 @@ type SaveHandler<TConfig extends AIModelConfig> = (
type AIModelConfigModalOptions<TConfig extends AIModelConfig> = {
kind: "text" | "vision" | "image";
providerIds: string[];
providerProfiles: Record<string, AIProviderProfile>;
previousModelId?: string;
initialModelId?: string;
initialConfig?: TConfig;
@@ -61,6 +72,8 @@ export class AIModelConfigModal<
}
: {}),
} as TConfig;
this.syncDerivedGeminiImageSizes();
}
onOpen(): void {
@@ -122,10 +135,36 @@ export class AIModelConfigModal<
}
}
private getCurrentProviderType() {
return this.options.providerProfiles[this.config.providerId]?.provider;
}
private isCurrentGeminiImageModel() {
return (
this.options.kind === "image" &&
isGeminiImageModel(this.getCurrentProviderType(), this.config.model)
);
}
private syncDerivedGeminiImageSizes() {
if (this.options.kind !== "image") {
return;
}
const supportedSizes = getGeminiSupportedSizes(
this.getCurrentProviderType(),
this.config.model,
);
if (supportedSizes.length > 0) {
(this.config as AIImageModelConfig).supportedSizes = [...supportedSizes];
}
}
private createForm() {
const contentEl = this.contentEl;
contentEl.empty();
contentEl.createEl("h1", { text: this.getTitle() });
let updateImageSizeControls = () => {};
new Setting(contentEl)
.setName(t("AI_MODEL_CONFIG_MODAL_NAME_NAME"))
@@ -143,11 +182,15 @@ export class AIModelConfigModal<
.setName(t("AI_MODEL_CONFIG_MODAL_PROVIDER_NAME"))
.setDesc(t("AI_MODEL_CONFIG_MODAL_PROVIDER_DESC"))
.addDropdown((dropdown) => {
this.options.providerIds.forEach((providerId) =>
dropdown.addOption(providerId, providerId),
this.options.providerIds.forEach(
(providerId) => void dropdown.addOption(providerId, providerId),
);
return dropdown.setValue(this.config.providerId).onChange((value) => {
this.config.providerId = value;
if (this.options.kind === "image") {
this.syncDerivedGeminiImageSizes();
updateImageSizeControls();
}
});
});
@@ -160,6 +203,10 @@ export class AIModelConfigModal<
.setValue(this.config.model)
.onChange((value) => {
this.config.model = value.trim();
if (this.options.kind === "image") {
this.syncDerivedGeminiImageSizes();
updateImageSizeControls();
}
}),
);
@@ -192,13 +239,14 @@ export class AIModelConfigModal<
if (this.options.kind === "image") {
const imageConfig = this.config as AIImageModelConfig;
contentEl.createEl("h3", {
const sizesSection = contentEl.createDiv();
sizesSection.createEl("h3", {
text: t("AI_IMAGE_MODEL_CAPABILITIES_SIZES_NAME"),
});
contentEl.createEl("p", {
sizesSection.createEl("p", {
text: t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_SIZES_DESC"),
});
const sizesContainer = contentEl.createDiv();
const sizesContainer = sizesSection.createDiv();
const renderSizes = () => {
sizesContainer.empty();
imageConfig.supportedSizes.forEach((size, index) => {
@@ -229,9 +277,16 @@ export class AIModelConfigModal<
);
});
};
renderSizes();
updateImageSizeControls = () => {
if (this.isCurrentGeminiImageModel()) {
hideElement(sizesSection);
} else {
showElement(sizesSection);
}
renderSizes();
};
new Setting(contentEl).addButton((button) =>
new Setting(sizesSection).addButton((button) =>
button
.setButtonText(t("AI_IMAGE_MODEL_CAPABILITIES_MODAL_ADD_SIZE"))
.onClick(() => {
@@ -239,6 +294,7 @@ export class AIModelConfigModal<
renderSizes();
}),
);
updateImageSizeControls();
new Setting(contentEl)
.setName(t("AI_IMAGE_MODEL_CAPABILITIES_TRANSFORMS_NAME"))
@@ -313,6 +369,9 @@ export class AIModelConfigModal<
if (this.options.kind === "image") {
const imageConfig = this.config as AIImageModelConfig;
if (this.isCurrentGeminiImageModel()) {
this.syncDerivedGeminiImageSizes();
}
imageConfig.supportedSizes = Array.from(
new Set(
imageConfig.supportedSizes.map((size) => size.trim()).filter(Boolean),
@@ -338,7 +397,7 @@ export class AIModelConfigModal<
...this.config,
model: this.config.model.trim(),
endpoint: this.config.endpoint?.trim() || "",
} as TConfig,
},
this.options.previousModelId,
);
this.close();
+235
View File
@@ -0,0 +1,235 @@
import { App, Modal, Notice, Setting } from "obsidian";
import { t } from "src/lang/helpers";
import { AIUsageData } from "src/types/AIUtilTypes";
/**
* Displays accumulated AI token usage for the current session.
* Provides a per-model breakdown table and a button to copy the data
* as a Markdown table.
*/
export class AIUsageModal extends Modal {
constructor(
app: App,
private readonly usage: AIUsageData,
) {
super(app);
}
onOpen(): void {
this.render();
}
onClose(): void {
this.contentEl.empty();
}
private formatTokens(n: number): string {
if (n === 0) {
return "0";
}
if (n >= 1_000_000) {
return `${(n / 1_000_000).toFixed(2)}M`;
}
if (n >= 1_000) {
return `${(n / 1_000).toFixed(1).replace(/\.0$/, "")}k`;
}
return String(n);
}
private buildMarkdownTable(): string {
const { textModels, imageModels } = this.usage;
const textEntries = Object.entries(textModels);
const imageEntries = Object.entries(imageModels);
const lines: string[] = [t("AI_USAGE_MODAL_TABLE_MARKDOWN_TITLE"), ""];
if (textEntries.length > 0) {
lines.push(
`| ${t("AI_USAGE_MODAL_TABLE_COL_MODEL")} | ${t("AI_USAGE_MODAL_TABLE_COL_INPUT")} | ${t("AI_USAGE_MODAL_TABLE_COL_OUTPUT")} |`,
`|---|---:|---:|`,
);
for (const [modelId, entry] of textEntries) {
lines.push(
`| ${modelId} | ${entry.inputTokens.toLocaleString()} | ${entry.outputTokens.toLocaleString()} |`,
);
}
lines.push(
`| **${t("AI_USAGE_MODAL_TABLE_TOTAL")}** | **${this.usage.totalInputTokens.toLocaleString()}** | **${this.usage.totalOutputTokens.toLocaleString()}** |`,
);
}
if (imageEntries.length > 0) {
if (textEntries.length > 0) {
lines.push("");
}
lines.push(
`| ${t("AI_USAGE_MODAL_TABLE_COL_IMAGE_MODEL")} | ${t("AI_USAGE_MODAL_TABLE_COL_GENERATIONS")} |`,
`|---|---:|`,
);
for (const [modelId, entry] of imageEntries) {
lines.push(`| ${modelId} | ${entry.generations} |`);
}
const totalImgs = this.usage.totalImageGenerations;
lines.push(
`| **${t("AI_USAGE_MODAL_TABLE_TOTAL")}** | **${totalImgs}** |`,
);
}
if (textEntries.length === 0 && imageEntries.length === 0) {
lines.push(t("AI_USAGE_MODAL_NO_USAGE"));
}
return lines.join("\n");
}
private render(): void {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl("h2", { text: t("AI_USAGE_MODAL_TITLE") });
const { textModels, imageModels } = this.usage;
const textEntries = Object.entries(textModels);
const imageEntries = Object.entries(imageModels);
const hasAnyUsage = textEntries.length > 0 || imageEntries.length > 0;
if (!hasAnyUsage) {
contentEl.createEl("p", { text: t("AI_USAGE_MODAL_NO_USAGE") });
} else {
// Text / multimodal model table
if (textEntries.length > 0) {
contentEl.createEl("h3", {
text: t("AI_USAGE_MODAL_TEXT_MODELS_HEADING"),
});
const table = contentEl.createEl("table", {
cls: "excalidraw-ai-usage-table",
});
const thead = table.createEl("thead");
const headerRow = thead.createEl("tr");
headerRow.createEl("th", {
text: t("AI_USAGE_MODAL_TABLE_COL_MODEL"),
});
headerRow.createEl("th", {
text: t("AI_USAGE_MODAL_TABLE_COL_INPUT"),
attr: { style: "text-align:right" },
});
headerRow.createEl("th", {
text: t("AI_USAGE_MODAL_TABLE_COL_OUTPUT"),
attr: { style: "text-align:right" },
});
const tbody = table.createEl("tbody");
for (const [modelId, entry] of textEntries) {
const row = tbody.createEl("tr");
row.createEl("td", { text: modelId });
row.createEl("td", {
text: this.formatTokens(entry.inputTokens),
attr: {
style: "text-align:right; font-variant-numeric: tabular-nums",
},
});
row.createEl("td", {
text: this.formatTokens(entry.outputTokens),
attr: {
style: "text-align:right; font-variant-numeric: tabular-nums",
},
});
}
// Totals row
const tfoot = table.createEl("tfoot");
const totalRow = tfoot.createEl("tr");
totalRow.createEl("td", {
text: t("AI_USAGE_MODAL_TABLE_TOTAL"),
attr: { style: "font-weight:bold" },
});
totalRow.createEl("td", {
text: this.formatTokens(this.usage.totalInputTokens),
attr: {
style:
"text-align:right; font-weight:bold; font-variant-numeric: tabular-nums",
},
});
totalRow.createEl("td", {
text: this.formatTokens(this.usage.totalOutputTokens),
attr: {
style:
"text-align:right; font-weight:bold; font-variant-numeric: tabular-nums",
},
});
}
// Image generation table
if (imageEntries.length > 0) {
contentEl.createEl("h3", {
text: t("AI_USAGE_MODAL_IMAGE_MODELS_HEADING"),
});
const table = contentEl.createEl("table", {
cls: "excalidraw-ai-usage-table",
});
const thead = table.createEl("thead");
const headerRow = thead.createEl("tr");
headerRow.createEl("th", {
text: t("AI_USAGE_MODAL_TABLE_COL_IMAGE_MODEL"),
});
headerRow.createEl("th", {
text: t("AI_USAGE_MODAL_TABLE_COL_GENERATIONS"),
attr: { style: "text-align:right" },
});
const tbody = table.createEl("tbody");
for (const [modelId, entry] of imageEntries) {
const row = tbody.createEl("tr");
row.createEl("td", { text: modelId });
row.createEl("td", {
text: String(entry.generations),
attr: {
style: "text-align:right; font-variant-numeric: tabular-nums",
},
});
}
// Totals row
const tfoot = table.createEl("tfoot");
const totalRow = tfoot.createEl("tr");
totalRow.createEl("td", {
text: t("AI_USAGE_MODAL_TABLE_TOTAL"),
attr: { style: "font-weight:bold" },
});
totalRow.createEl("td", {
text: String(this.usage.totalImageGenerations),
attr: {
style:
"text-align:right; font-weight:bold; font-variant-numeric: tabular-nums",
},
});
}
}
// Session note
contentEl.createEl("p", {
text: t("AI_USAGE_MODAL_SESSION_NOTE"),
cls: "setting-item-description",
attr: { style: "margin-top: 0.75em" },
});
// Buttons
new Setting(contentEl)
.addButton((button) =>
button.setButtonText(t("AI_USAGE_MODAL_COPY_MARKDOWN")).onClick(() => {
const md = this.buildMarkdownTable();
navigator.clipboard.writeText(md).then(
() => new Notice(t("AI_USAGE_MODAL_COPY_SUCCESS")),
() => new Notice(t("AI_USAGE_MODAL_COPY_FAILURE")),
);
}),
)
.addButton((button) =>
button
.setButtonText(t("PROMPT_BUTTON_OK"))
.setCta()
.onClick(() => this.close()),
);
}
}
+15 -13
View File
@@ -1,5 +1,6 @@
import ExcalidrawView from "src/view/ExcalidrawView";
import { getViewColorPalette } from "src/utils/excalidrawViewUtils";
import { setStyle } from "src/utils/styleUtils";
type PaletteName = "canvasBackground" | "elementBackground" | "elementStroke";
@@ -51,8 +52,7 @@ const positionPopup = (popup: HTMLElement, anchor: HTMLElement) => {
top = Math.max(8, rect.top - popupHeight - 8);
}
popup.style.left = `${left}px`;
popup.style.top = `${top}px`;
setStyle(popup, { left: `${left}px`, top: `${top}px` });
};
const attachOutsideHandlers = (
@@ -72,14 +72,14 @@ const attachOutsideHandlers = (
const onOverlayClick = () => cleanup(null);
const cleanup = (color: string | null) => {
document.removeEventListener("keydown", onKeyDown, true);
activeDocument.removeEventListener("keydown", onKeyDown, true);
overlay.removeEventListener("click", onOverlayClick);
popup.removeEventListener("click", stopPropagation);
overlay.remove();
resolve(color);
};
document.addEventListener("keydown", onKeyDown, true);
activeDocument.addEventListener("keydown", onKeyDown, true);
overlay.addEventListener("click", onOverlayClick);
popup.addEventListener("click", stopPropagation);
@@ -99,31 +99,33 @@ export const showColorPicker = async (
}
return new Promise((resolve) => {
const overlay = document.createElement("div");
const overlay = activeDocument.createElement("div");
overlay.classList.add("excalidraw-colorpicker-overlay");
const popup = document.createElement("div");
const popup = activeDocument.createElement("div");
popup.classList.add("excalidraw-colorpicker-popup");
const grid = document.createElement("div");
const grid = activeDocument.createElement("div");
grid.classList.add("excalidraw-colorpicker-grid");
grid.style.gridTemplateColumns = `repeat(${GRID_COLUMNS}, ${CELL_SIZE}px)`;
grid.style.gap = `${CELL_GAP}px`;
grid.style.maxHeight = `${MAX_HEIGHT}px`;
setStyle(grid, {
gridTemplateColumns: `repeat(${GRID_COLUMNS}, ${CELL_SIZE}px)`,
gap: `${CELL_GAP}px`,
maxHeight: `${MAX_HEIGHT}px`,
});
colors.forEach((color) => {
const swatch = document.createElement("button");
const swatch = activeDocument.createElement("button");
swatch.type = "button";
swatch.ariaLabel = color;
swatch.classList.add("excalidraw-colorpicker-swatch");
swatch.style.backgroundColor = color;
setStyle(swatch, { backgroundColor: color });
swatch.addEventListener("click", () => cleanup(color));
grid.appendChild(swatch);
});
popup.appendChild(grid);
overlay.appendChild(popup);
document.body.appendChild(overlay);
activeDocument.body.appendChild(overlay);
positionPopup(popup, anchorElement);
@@ -2,6 +2,7 @@ import { Setting, ToggleComponent } from "obsidian";
import { EmbeddableMDCustomProps } from "./EmbeddableSettings";
import { fragWithHTML } from "src/utils/utils";
import { t } from "src/lang/helpers";
import { hideElement, showElement } from "src/utils/styleUtils";
export class EmbeddalbeMDFileCustomDataSettingsComponent {
constructor(
@@ -23,7 +24,11 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
.setValue(this.mdCustomData.useObsidianDefaults)
.onChange((value) => {
this.mdCustomData.useObsidianDefaults = value;
detailsDIV.style.display = value ? "none" : "block";
if (value) {
hideElement(detailsDIV);
} else {
showElement(detailsDIV);
}
this.update();
}),
);
@@ -31,9 +36,11 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
this.contentEl.createEl("hr", { cls: "excalidraw-setting-hr" });
const detailsDIV = this.contentEl.createDiv();
detailsDIV.style.display = this.mdCustomData.useObsidianDefaults
? "none"
: "block";
if (this.mdCustomData.useObsidianDefaults) {
hideElement(detailsDIV);
} else {
showElement(detailsDIV);
}
const contentEl = detailsDIV;
if (this.isMDFile) {
@@ -70,12 +77,12 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
.onChange((value) => {
this.mdCustomData.backgroundMatchElement = value;
if (value) {
bgSetting.settingEl.style.display = "none";
hideElement(bgSetting.settingEl);
if (this.mdCustomData.backgroundMatchCanvas) {
bgMatchCanvasToggle.setValue(false);
}
} else if (!this.mdCustomData.backgroundMatchCanvas) {
bgSetting.settingEl.style.display = "";
showElement(bgSetting.settingEl);
}
this.update();
});
@@ -90,12 +97,12 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
.onChange((value) => {
this.mdCustomData.backgroundMatchCanvas = value;
if (value) {
bgSetting.settingEl.style.display = "none";
hideElement(bgSetting.settingEl);
if (this.mdCustomData.backgroundMatchElement) {
bgMatchElementToggle.setValue(false);
}
} else if (!this.mdCustomData.backgroundMatchElement) {
bgSetting.settingEl.style.display = "";
showElement(bgSetting.settingEl);
}
this.update();
});
@@ -119,11 +126,14 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
}),
);
bgSetting.settingEl.style.display =
if (
this.mdCustomData.backgroundMatchElement ||
this.mdCustomData.backgroundMatchCanvas
? "none"
: "";
) {
hideElement(bgSetting.settingEl);
} else {
showElement(bgSetting.settingEl);
}
const opacity = (value: number): DocumentFragment => {
return fragWithHTML(`Current opacity is <b>${value}%</b>`);
};
@@ -153,9 +163,9 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
.onChange((value) => {
this.mdCustomData.borderMatchElement = value;
if (value) {
borderSetting.settingEl.style.display = "none";
hideElement(borderSetting.settingEl);
} else {
borderSetting.settingEl.style.display = "";
showElement(borderSetting.settingEl);
}
this.update();
}),
@@ -172,10 +182,11 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
}),
);
borderSetting.settingEl.style.display = this.mdCustomData
.borderMatchElement
? "none"
: "";
if (this.mdCustomData?.borderMatchElement) {
hideElement(borderSetting.settingEl);
} else {
showElement(borderSetting.settingEl);
}
const borderOpacitySetting = new Setting(contentEl)
.setName(t("ES_BORDER_OPACITY"))
+4 -4
View File
@@ -19,7 +19,7 @@ import {
updateYouTubeStartTime,
} from "src/utils/YoutTubeUtils";
import { EmbeddalbeMDFileCustomDataSettingsComponent } from "./EmbeddableMDFileCustomDataSettingsComponent";
import { isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
import { isWinCTRLorMacCMD, labelCTRL } from "src/utils/modifierkeyHelper";
import { CaptureUpdateAction } from "src/constants/constants";
export type EmbeddableMDCustomProps = {
@@ -164,14 +164,14 @@ export class EmbeddableSettings extends Modal {
button
.setButtonText(t("PROMPT_BUTTON_CANCEL"))
.setTooltip("ESC")
.onClick(this.close.bind(this)),
.onClick(() => this.close()),
)
.addButton((button) =>
button
.setButtonText(t("PROMPT_BUTTON_OK"))
.setTooltip("CTRL/Opt+Enter")
.setTooltip(labelCTRL() + "Enter")
.setCta()
.onClick(this.applySettings.bind(this)),
.onClick(() => this.applySettings()),
);
const onKeyDown = (ev: KeyboardEvent) => {
+47 -40
View File
@@ -32,6 +32,7 @@ import {
} from "./PDFExportSettingsComponent";
import { captureScreenshot } from "src/utils/screenshot";
import { exportImageToFile, getIMGFilename } from "src/utils/fileUtils";
import { setStyle } from "src/utils/styleUtils";
export class ExportDialog extends Modal {
private ea: ExcalidrawAutomate;
@@ -80,7 +81,7 @@ export class ExportDialog extends Modal {
this.theme = getExportTheme(
this.plugin,
this.file,
this.api.getAppState().theme,
this.api.getAppState().theme as string,
);
this.boundingBox = this.ea.getBoundingBox(this.ea.getViewElements());
this.embedScene = shouldEmbedScene(this.plugin, this.file);
@@ -126,7 +127,7 @@ export class ExportDialog extends Modal {
} else {
this.boundingBox = this.ea.getBoundingBox(this.ea.getViewElements());
}
if (this.scaleSetting) {
if (this.scaleSetting !== null) {
this.scaleSetting.setDesc(this.size());
}
}
@@ -139,7 +140,7 @@ export class ExportDialog extends Modal {
this.updateBoundingBox();
}
async onClose() {
onClose() {
this.dirty = this.saveSettings;
}
@@ -196,7 +197,7 @@ export class ExportDialog extends Modal {
this.buttonContainerRow2 = this.contentEl.createDiv({
cls: "excalidraw-export-buttons-div",
});
this.buttonContainerRow2.style.marginTop = "10px";
setStyle(this.buttonContainerRow2, { marginTop: "10px" });
this.renderContent();
}
@@ -426,16 +427,18 @@ export class ExportDialog extends Modal {
bPNG.onclick = () => {
if (isScreenshot) {
//allow dialog to close before taking screenshot
window.setTimeout(async () => {
const png = await captureScreenshot(this.view, {
zoom: this.scale,
margin: this.padding,
selectedOnly: this.isSelectedOnly,
theme: this.theme,
});
if (png) {
exportPNG(png, this.view.file.basename);
}
window.setTimeout(() => {
void (async () => {
const png = await captureScreenshot(this.view, {
zoom: this.scale,
margin: this.padding,
selectedOnly: this.isSelectedOnly,
theme: this.theme,
});
if (png) {
exportPNG(png, this.view.file.basename);
}
})();
});
} else {
void this.view.exportPNG(this.embedScene, this.isSelectedOnly);
@@ -451,22 +454,24 @@ export class ExportDialog extends Modal {
bPNGVault.onclick = () => {
if (isScreenshot) {
//allow dialog to close before taking screenshot
window.setTimeout(async () => {
const png = await captureScreenshot(this.view, {
zoom: this.scale,
margin: this.padding,
selectedOnly: this.isSelectedOnly,
theme: this.theme,
});
if (png) {
void exportImageToFile(
this.view,
getIMGFilename(this.view.file.path, "png"),
png,
".png",
);
}
});
window.setTimeout(() => {
void (async () => {
const png = await captureScreenshot(this.view, {
zoom: this.scale,
margin: this.padding,
selectedOnly: this.isSelectedOnly,
theme: this.theme,
});
if (png) {
void exportImageToFile(
this.view,
getIMGFilename(this.view.file.path, "png"),
png,
".png",
);
}
})();
}, 0);
} else {
void this.view.savePNG({
scene: this.view.getScene(this.isSelectedOnly),
@@ -482,16 +487,18 @@ export class ExportDialog extends Modal {
bPNGClipboard.onclick = async () => {
if (isScreenshot) {
//allow dialog to close before taking screenshot
window.setTimeout(async () => {
const png = await captureScreenshot(this.view, {
zoom: this.scale,
margin: this.padding,
selectedOnly: this.isSelectedOnly,
theme: this.theme,
});
if (png) {
await exportPNGToClipboard(png);
}
window.setTimeout(() => {
void (async () => {
const png = await captureScreenshot(this.view, {
zoom: this.scale,
margin: this.padding,
selectedOnly: this.isSelectedOnly,
theme: this.theme,
});
if (png) {
await exportPNGToClipboard(png);
}
})();
});
} else {
await this.view.exportPNGToClipboard(
+59 -46
View File
@@ -1,5 +1,13 @@
import { App, Modal } from "obsidian";
import { clamp } from "@radix-ui/number";
import { mainDocument } from "src/constants/constants";
import { setStyle } from "src/utils/styleUtils";
import {
isInstanceOfHTMLButtonElement,
isInstanceOfHTMLInputElement,
isInstanceOfHTMLSelectElement,
isInstanceOfHTMLTextAreaElement,
} from "src/utils/typechecks";
function getClientPoint(e: PointerEvent | TouchEvent) {
if (e.type.startsWith("touch")) {
@@ -92,14 +100,14 @@ export class FloatingModal extends Modal {
private previousActive?: HTMLElement = null; // stores element focused before opening
private readonly modalKeydownStopHandler: (e: KeyboardEvent) => void; // store handler so we can remove it
private ownerWindow: Window = window;
private ownerDocument: Document = document;
private ownerDocument: Document = mainDocument;
constructor(app: App) {
super(app);
// Initialize event handlers with proper binding
this.pointerDownHandler = this.handlePointerDown.bind(this);
this.pointerMoveHandler = this.handlePointerMove.bind(this);
this.pointerUpHandler = this.handlePointerUp.bind(this);
this.pointerDownHandler = (e) => this.handlePointerDown(e);
this.pointerMoveHandler = (e) => this.handlePointerMove(e);
this.pointerUpHandler = () => this.handlePointerUp();
this.modalKeydownStopHandler = (ev: KeyboardEvent) => ev.stopPropagation();
this.setDimBackground(false);
@@ -110,10 +118,10 @@ export class FloatingModal extends Modal {
event: PointerEvent | TouchEvent,
): boolean {
return Boolean(
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement ||
target instanceof HTMLSelectElement ||
target instanceof HTMLButtonElement ||
isInstanceOfHTMLInputElement(target) ||
isInstanceOfHTMLTextAreaElement(target) ||
isInstanceOfHTMLSelectElement(target) ||
isInstanceOfHTMLButtonElement(target) ||
isPointOnText(event, this.ownerDocument) ||
target.closest(".clickable-icon") ||
// ensure close button never starts drag
@@ -144,12 +152,14 @@ export class FloatingModal extends Modal {
const { modalEl } = this;
this.offsetX = touch.clientX - modalEl.getBoundingClientRect().left;
this.offsetY = touch.clientY - modalEl.getBoundingClientRect().top;
modalEl.style.height = "fit-content";
setStyle(modalEl, {
height: "fit-content",
});
// Add touch-specific event listeners
this.ownerDocument.addEventListener(
"touchmove",
this.pointerMoveHandler as (e: TouchEvent) => void,
this.pointerMoveHandler,
{
passive: false,
},
@@ -168,7 +178,7 @@ export class FloatingModal extends Modal {
// Add pointer-specific event listeners
this.ownerDocument.addEventListener(
"pointermove",
this.pointerMoveHandler as (e: PointerEvent) => void,
this.pointerMoveHandler,
);
this.ownerDocument.addEventListener("pointerup", this.pointerUpHandler);
// Capture the pointer to ensure we get events even when outside the target
@@ -206,8 +216,10 @@ export class FloatingModal extends Modal {
]);
// Position the modal element
modalEl.style.left = `${x}px`;
modalEl.style.top = `${y}px`;
setStyle(modalEl, {
left: `${x}px`,
top: `${y}px`,
});
}
private handlePointerUp(): void {
@@ -215,12 +227,12 @@ export class FloatingModal extends Modal {
// Remove all event listeners
this.ownerDocument.removeEventListener(
"pointermove",
this.pointerMoveHandler as (e: PointerEvent) => void,
this.pointerMoveHandler,
);
this.ownerDocument.removeEventListener("pointerup", this.pointerUpHandler);
this.ownerDocument.removeEventListener(
"touchmove",
this.pointerMoveHandler as (e: TouchEvent) => void,
this.pointerMoveHandler,
);
this.ownerDocument.removeEventListener("touchend", this.pointerUpHandler);
this.ownerDocument.removeEventListener(
@@ -231,7 +243,7 @@ export class FloatingModal extends Modal {
open(): void {
super.open();
this.ownerDocument = this.modalEl.ownerDocument ?? document;
this.ownerDocument = this.modalEl.ownerDocument ?? mainDocument;
this.ownerWindow = this.ownerDocument.defaultView ?? window;
// NEW: capture previously focused element & release Obsidian modal key trapping
if (this.disableKeyCapture) {
@@ -240,7 +252,9 @@ export class FloatingModal extends Modal {
try {
// Release modal scope so focus and key handling can return to the workspace.
this.app.keymap.popScope(this.scope);
} catch {}
} catch (error) {
console.log(error);
}
// prevent automatic selection / focus restoration
this.shouldRestoreSelection = false;
}
@@ -250,31 +264,28 @@ export class FloatingModal extends Modal {
// Set initial position and make modal draggable
if (modalEl) {
modalEl.style.pointerEvents = "auto";
// Position absolute is needed for custom positioning
modalEl.style.position = "absolute";
setStyle(modalEl, {
pointerEvents: "auto",
// Position absolute is needed for custom positioning
position: "absolute",
});
// Center the modal initially
const rect = modalEl.getBoundingClientRect();
const centerX = this.ownerWindow.innerWidth / 2 - rect.width / 2;
const centerY = this.ownerWindow.innerHeight / 2 - rect.height / 2;
modalEl.style.left = `${centerX}px`;
modalEl.style.top = `${centerY}px`;
modalEl.style.transform = "none";
setStyle(modalEl, {
left: `${centerX}px`,
top: `${centerY}px`,
transform: "none",
});
// Add event listeners for both pointer and touch events
modalEl.addEventListener(
"pointerdown",
this.pointerDownHandler as (e: PointerEvent) => void,
);
modalEl.addEventListener(
"touchstart",
this.pointerDownHandler as (e: TouchEvent) => void,
{
passive: false,
},
);
modalEl.addEventListener("pointerdown", this.pointerDownHandler);
modalEl.addEventListener("touchstart", this.pointerDownHandler, {
passive: false,
});
if (this.disableKeyCapture) {
// Prevent the modal from stealing focus
@@ -282,9 +293,13 @@ export class FloatingModal extends Modal {
// In order to propagate keypresses, modal container and backdrop
// need to ignore (and thus propagate) any pointerEvents.
containerEl.style.pointerEvents = "none";
setStyle(containerEl, {
pointerEvents: "none",
});
if (bgEl) {
bgEl.style.pointerEvents = "none";
setStyle(bgEl, {
pointerEvents: "none",
});
}
// Refocus previous element (if still in DOM)
@@ -300,7 +315,9 @@ export class FloatingModal extends Modal {
// NEW: re-enable pointer events on the close button so it is tappable on mobile
const closeBtn = containerEl.querySelector(".modal-close-button");
if (closeBtn) {
(closeBtn as HTMLElement).style.pointerEvents = "auto";
setStyle(closeBtn as HTMLElement, {
pointerEvents: "auto",
});
}
}
});
@@ -315,19 +332,15 @@ export class FloatingModal extends Modal {
) {
try {
this.previousActive.focus({ preventScroll: true });
} catch {}
} catch (error) {
console.log(error);
}
}
const { modalEl } = this;
// Clean up event listeners
if (modalEl) {
modalEl.removeEventListener(
"pointerdown",
this.pointerDownHandler as (e: PointerEvent) => void,
);
modalEl.removeEventListener(
"touchstart",
this.pointerDownHandler as (e: TouchEvent) => void,
);
modalEl.removeEventListener("pointerdown", this.pointerDownHandler);
modalEl.removeEventListener("touchstart", this.pointerDownHandler);
// Remove the capturing keydown stopper if it was added
modalEl.removeEventListener("keydown", this.modalKeydownStopHandler, {
capture: true,
+7 -11
View File
@@ -3,6 +3,7 @@ import { CaptureUpdateAction } from "src/constants/constants";
import { FloatingModal } from "./FloatingModal";
import ExcalidrawView from "src/view/ExcalidrawView";
import { Setting } from "obsidian";
import { setComponentVisibility } from "src/utils/styleUtils";
export const showFrameSettings = (view: ExcalidrawView) => {
const { enabled, clip, name, outline, markerName, markerEnabled } =
@@ -31,9 +32,9 @@ export const showFrameSettings = (view: ExcalidrawView) => {
.addToggle((toggle) =>
toggle.setValue(settings.enabled).onChange((value) => {
settings.enabled = value;
hideComponent(displayFrameNameSetting, !value);
hideComponent(displayFrameOutlineSetting, !value);
hideComponent(enableFrameClippingSetting, !value);
setComponentVisibility(displayFrameNameSetting, value);
setComponentVisibility(displayFrameOutlineSetting, value);
setComponentVisibility(enableFrameClippingSetting, value);
}),
);
@@ -62,9 +63,9 @@ export const showFrameSettings = (view: ExcalidrawView) => {
);
// Hide or show components based on initial state
hideComponent(displayFrameNameSetting, !settings.enabled);
hideComponent(displayFrameOutlineSetting, !settings.enabled);
hideComponent(enableFrameClippingSetting, !settings.enabled);
setComponentVisibility(displayFrameNameSetting, settings.enabled);
setComponentVisibility(displayFrameOutlineSetting, settings.enabled);
setComponentVisibility(enableFrameClippingSetting, settings.enabled);
// Add OK button
new Setting(contentEl).addButton((button) =>
@@ -83,8 +84,3 @@ export const showFrameSettings = (view: ExcalidrawView) => {
frameSettingsModal.open();
};
// Function to hide or show a component
function hideComponent(comp: Setting, value: boolean) {
comp.settingEl.style.display = value ? "none" : "";
}
+9 -4
View File
@@ -4,6 +4,7 @@ import { t } from "src/lang/helpers";
import { ExcalidrawSettings } from "src/core/settings";
import { modifierLabel } from "src/utils/modifierkeyHelper";
import { fragWithHTML } from "src/utils/utils";
import { setStyle } from "src/utils/styleUtils";
export class HotkeyEditor extends BaseComponent {
private settings: ExcalidrawSettings;
@@ -66,10 +67,14 @@ export class HotkeyEditor extends BaseComponent {
// Render Add New Override or Capture Instruction
if (this.capturing) {
new Setting(this.containerEl)
.setName(t("HOTKEY_PRESS_COMBO_NANE"))
.setDesc(t("HOTKEY_PRESS_COMBO_DESC")).controlEl.style.cursor =
"pointer";
setStyle(
new Setting(this.containerEl)
.setName(t("HOTKEY_PRESS_COMBO_NANE"))
.setDesc(t("HOTKEY_PRESS_COMBO_DESC")).controlEl,
{
cursor: "pointer",
},
);
} else {
new Setting(this.containerEl).addButton((button) =>
button
+12 -11
View File
@@ -4,7 +4,6 @@ import ExcalidrawView from "../../view/ExcalidrawView";
import { t } from "../../lang/helpers";
import ExcalidrawPlugin from "../../core/main";
import { getEA } from "src/core";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
export class ImportSVGDialog extends FuzzySuggestModal<TFile> {
public plugin: ExcalidrawPlugin;
@@ -44,19 +43,21 @@ export class ImportSVGDialog extends FuzzySuggestModal<TFile> {
return item.path;
}
async onChooseItem(item: TFile, _: KeyboardEvent): Promise<void> {
onChooseItem(item: TFile, _: KeyboardEvent): void {
if (!item) {
return;
}
const ea = getEA(this.view);
const svg = await this.app.vault.read(item);
if (!svg || svg === "") {
return;
}
ea.importSVG(svg);
ea.addToGroup(ea.getElements().map((el) => el.id));
await ea.addElementsToView(true, true, true, true);
ea.destroy();
void (async () => {
const ea = getEA(this.view);
const svg = await this.app.vault.read(item);
if (!svg || svg === "") {
return;
}
ea.importSVG(svg);
ea.addToGroup(ea.getElements().map((el) => el.id));
await ea.addElementsToView(true, true, true, true);
ea.destroy();
})();
}
onClose(): void {
+44 -36
View File
@@ -1,3 +1,8 @@
import {
ExcalidrawElement,
ExcalidrawImageElement,
} from "@zsviczian/excalidraw/types/element/src/types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { ButtonComponent, TFile, ToggleComponent } from "obsidian";
import ExcalidrawView from "../../view/ExcalidrawView";
import ExcalidrawPlugin from "../../core/main";
@@ -5,9 +10,11 @@ import { getPDFDoc } from "src/utils/fileUtils";
import { Modal, Setting, TextComponent } from "obsidian";
import { FileSuggestionModal } from "../Suggesters/FileSuggestionModal";
import { getEA } from "src/core";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { t } from "src/lang/helpers";
import { NamedExcalidrawFrameElement } from "src/types/excalidrawElementTypes";
import type { PdfJsDocumentProxy } from "src/types/pdfJsTypes";
import { setSanitizedHtml } from "src/utils/htmlUtils";
import { hideElement, setStyle, showElement } from "src/utils/styleUtils";
export class InsertPDFModal extends Modal {
private borderBox: boolean = true;
@@ -19,15 +26,11 @@ export class InsertPDFModal extends Modal {
private numRows: number = 1;
private lockAfterImport: boolean = true;
private pagesToImport: number[] = [];
private pageDimensions: { width: number; height: number } = {
width: 0,
height: 0,
};
private pageDimensionsByPage: Map<number, { width: number; height: number }> =
new Map();
private importScale = 0.3;
private imageSizeMessage: HTMLElement;
private pdfDoc: any;
private pdfDoc: PdfJsDocumentProxy | null = null;
private pdfFile: TFile;
private dirty: boolean = false;
@@ -51,7 +54,7 @@ export class InsertPDFModal extends Modal {
void this.createForm();
}
async onClose() {
onClose() {
if (this.dirty) {
this.plugin.settings.pdfImportScale = this.importScale;
this.plugin.settings.pdfBorderBox = this.borderBox;
@@ -62,7 +65,7 @@ export class InsertPDFModal extends Modal {
this.plugin.settings.pdfNumRows = this.numRows;
this.plugin.settings.pdfDirection = this.direction;
this.plugin.settings.pdfLockAfterImport = this.lockAfterImport;
await this.plugin.saveSettings();
void this.plugin.saveSettings();
}
if (this.pdfDoc) {
this.pdfDoc.destroy();
@@ -97,7 +100,6 @@ export class InsertPDFModal extends Modal {
console.log(e);
}
}
this.pageDimensions = this.getMaxSelectedPageDimensions();
this.setImageSizeMessage();
}
@@ -140,7 +142,9 @@ export class InsertPDFModal extends Modal {
const pageRangeArray = pageRange.split("-");
if (pageRangeArray.length === 1) {
const page = parseInt(cleanNonDigits(pageRangeArray[0]));
!isNaN(page) && this.pagesToImport.push(page);
if (!isNaN(page)) {
this.pagesToImport.push(page);
}
} else if (pageRangeArray.length === 2) {
const start = parseInt(cleanNonDigits(pageRangeArray[0]));
const end = parseInt(cleanNonDigits(pageRangeArray[1]));
@@ -183,19 +187,19 @@ export class InsertPDFModal extends Modal {
const importButtonMessages = () => {
if (!this.pdfDoc) {
importMessage.innerText = t("IPM_SELECT_PDF");
importButton.buttonEl.style.display = "none";
hideElement(importButton.buttonEl);
return;
}
if (this.pagesToImport.length === 0) {
importButton.buttonEl.style.display = "none";
hideElement(importButton.buttonEl);
importMessage.innerText = t("IPM_SELECT_PAGES_TO_IMPORT");
return;
}
if (Math.max(...this.pagesToImport) <= this.pdfDoc.numPages) {
importButton.buttonEl.style.display = "block";
showElement(importButton.buttonEl);
importMessage.innerText = "";
} else {
importButton.buttonEl.style.display = "none";
hideElement(importButton.buttonEl);
importMessage.innerText = `The selected document has ${this.pdfDoc.numPages} pages. Please select pages between 1 and ${this.pdfDoc.numPages}`;
}
};
@@ -219,7 +223,6 @@ export class InsertPDFModal extends Modal {
await this.loadPageDimensions(pages);
} else {
this.pageDimensionsByPage.clear();
this.pageDimensions = { width: 0, height: 0 };
this.setImageSizeMessage();
}
if (pages.length > 15) {
@@ -238,11 +241,10 @@ export class InsertPDFModal extends Modal {
const setFile = async (file: TFile) => {
if (this.pdfDoc) {
await this.pdfDoc.destroy();
this.pdfDoc.destroy();
}
this.pdfDoc = null;
this.pageDimensionsByPage.clear();
this.pageDimensions = { width: 0, height: 0 };
numPages = 0;
this.setImageSizeMessage();
@@ -265,7 +267,9 @@ export class InsertPDFModal extends Modal {
};
const search = new TextComponent(ce);
search.inputEl.style.width = "100%";
setStyle(search.inputEl, {
width: "100%",
});
const suggester = new FileSuggestionModal(
this.app,
search,
@@ -289,7 +293,9 @@ export class InsertPDFModal extends Modal {
text.setValue("").onChange(async (value) => {
await rangeOnChange(value);
});
text.inputEl.style.width = "100%";
setStyle(text.inputEl, {
width: "100%",
});
});
const importPagesMessage = ce.createEl("p", { text: "" });
@@ -355,12 +361,12 @@ export class InsertPDFModal extends Modal {
const colRowVisibility = () => {
switch (this.direction) {
case "down":
numColumnsSetting.settingEl.style.display = "none";
numRowsSetting.settingEl.style.display = "";
hideElement(numColumnsSetting.settingEl);
showElement(numRowsSetting.settingEl);
break;
case "right":
numColumnsSetting.settingEl.style.display = "";
numRowsSetting.settingEl.style.display = "none";
showElement(numColumnsSetting.settingEl);
hideElement(numRowsSetting.settingEl);
break;
}
};
@@ -395,8 +401,7 @@ export class InsertPDFModal extends Modal {
)
.settingEl.createDiv("", (el) => {
columnsText = el;
el.style.minWidth = "2.3em";
el.style.textAlign = "right";
el.addClass("excalidraw-insertpdf-infolabel");
el.innerText = ` ${this.numColumns.toString()}`;
});
@@ -416,8 +421,7 @@ export class InsertPDFModal extends Modal {
)
.settingEl.createDiv("", (el) => {
rowsText = el;
el.style.minWidth = "2.3em";
el.style.textAlign = "right";
el.addClass("excalidraw-insertpdf-infolabel");
el.innerText = ` ${this.numRows.toString()}`;
});
colRowVisibility();
@@ -437,8 +441,7 @@ export class InsertPDFModal extends Modal {
)
.settingEl.createDiv("", (el) => {
gapSizeText = el;
el.style.minWidth = "2.3em";
el.style.textAlign = "right";
el.addClass("excalidraw-insertpdf-infolabel");
el.innerText = ` ${this.gapSize.toString()}`;
});
@@ -496,9 +499,11 @@ export class InsertPDFModal extends Modal {
);
const topY = Math.round(cellHeight * row + this.gapSize * row);
ea.style.strokeColor = this.borderBox ? "#000000" : "transparent";
ea.setStyle({
strokeColor: this.borderBox ? "#000000" : "transparent",
});
const boxID = ea.addRect(topX, topY, imgWidth, imgHeight);
const boxEl = ea.getElement(boxID) as any;
const boxEl = ea.getElement(boxID) as Mutable<ExcalidrawElement>;
if (this.lockAfterImport) {
boxEl.locked = true;
}
@@ -510,7 +515,9 @@ export class InsertPDFModal extends Modal {
false,
false,
);
const imgEl = ea.getElement(imageID) as any;
const imgEl = ea.getElement(
imageID,
) as Mutable<ExcalidrawImageElement>;
imgEl.width = imgWidth;
imgEl.height = imgHeight;
if (this.lockAfterImport) {
@@ -527,12 +534,13 @@ export class InsertPDFModal extends Modal {
imgHeight,
`${page}`,
);
const frameEl = ea.getElement(frameID) as any;
const frameEl = ea.getElement(
frameID,
) as Mutable<NamedExcalidrawFrameElement>;
frameEl.frameRole = "marker";
frameEl.link = `${this.pdfFile.path}#page=${page}`;
ea.addToGroup([frameID, boxID, imageID]);
//ea.addElementsToFrame(frameID, [boxID,imageID]);
ea.getElement(frameID).link =
`${this.pdfFile.path}#page=${page}`;
}
switch (this.direction) {
@@ -569,7 +577,7 @@ export class InsertPDFModal extends Modal {
this.close();
});
importButton = button;
importButton.buttonEl.style.display = "none";
hideElement(importButton.buttonEl);
});
const importMessage = actionButton.descEl;
importMessage.addClass("mod-warning");
+207 -53
View File
@@ -1,20 +1,180 @@
import { URLs } from "src/constants/safeUrls";
import {
getYouTubeThumbnailUrl,
getYouTubeUrl,
URLs,
} from "src/constants/safeUrls";
const getYouTubeDiv = (videoId: string) => `
<div class="excalidraw-videoWrapper">
<a href="${getYouTubeUrl(videoId)}" target="_blank"><img src="${getYouTubeThumbnailUrl(videoId)}" style="width:100%;"></a>
</div>
`;
export const RELEASE_NOTES: { [k: string]: string } = {
Intro: `After each update, you'll see these release notes (you can turn this off in the plugin settings).
I build this plugin as a labor of love. Curious about the philosophy behind it? Check out [📕 Sketch Your Mind](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_SYM}). Want to master Excalidraw? Join [Excalidraw Mastery](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}). If you find it valuable, say THANK YOU or…
I build this plugin as a labor of love. Curious about the philosophy behind it? Check out [📕 Sketch Your Mind](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_SYM}). Want to master Excalidraw? Join [Excalidraw Mastery](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}). If you find it valuable, say "Thank you", and
<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.23.1": `
"2.24.0": `
To keep Excalidraw lightweight, improve startup performance, reduce plugin size, and address Obsidian's high-risk code scanner findings, several advanced features have been moved to the new **Excalidraw Extras** companion plugin.
The first time you use one of these features, Excalidraw will automatically prompt you to install Excalidraw Extras:
- LaTeX formulas (MathJax)
- Mermaid diagrams
- PDF printing
- Direct file system access (files outside your vault)
This change reduces Excalidraw's size to under 5 MB, allowing even Obsidian Sync Basic users to sync the plugin across all devices while keeping the core plugin lighter.
## Fixed
- Keep runtime custom pen settings per custom pen index instead of sharing one active pen object. Switching between custom pens restores each pen's last adjusted stroke width, colors, fill style, and roughness. 🙏[@arias007](${URLs.GITHUB_COM}/arias007) [#2801](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2801)
- Insert ANY file: Typing “p” in the search field opens the PDF selection [#2791](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2791)
- Blurry arrows in PNG export when arrows have a text label [#2793](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2793), [#11492](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11492)
`,
"2.23.12": `
## Fixed
- Code scanner error
`,
"2.23.11": `
## Fixed
- Print to PDF sometimes displayed a scrollbar on prinouts on MacOS.
- Scenes that contain \`![[text#^block]] transclusions\` did not render in markdown nor in image previews.
- Addressed further Obsidian code scanner findings
`,
"2.23.10": `
## Fixed
- 2.23.9 regression: Toolbar sizing issue in desktop and compact UI modes [#2789](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2789)
`,
"2.23.9": `
## New
- Excalidraw now updates nested image embeds in the scene triggered by Obsidian window/tab changes even if those changes affect deep nested images (i.e. excalidraw images nested inside the nested drawings)
- Added the Color Scheme Manager script. 🙏[@iwanhoogendoorn](${URLs.GITHUB_COM}/iwanhoogendoorn)
- Iwan will demonstrate the script and host a Q&A session for [Sketch Your Mind Community Members](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_SYM}) on Friday, 12 June.
## Fixed
- Clicking Excalidraw links now correctly jumps to the targeted element, group, or frame when the destination is another Excalidraw drawing, including links chosen through the multi-link picker and links triggered from nested embeds.
- In some cases the image cache did not update when nested drawings were modified
- Horizontal and Vertical arrow lines are not always displayed correctly when exporting to SVG or embedding SVG to a markdown note [#1454](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/1454)
- Updated vulnerable package dependency lodash-es and nanoid based on Obsidian code scanner findings.
`,
"2.23.8": `
${getYouTubeDiv("y3sDfH30ApU")}
## New
- Embeddable links now support adding ontology to links, e.g. \`(ontology:: [[file#section]])\` and \`(ontology:: [Video Title](link-to-youtube-video))\`. This allows you to add custom metadata to links that will be picked up as dataview tags and rendered with tools such as ExcaliBrain.
## Fixed
- Regression from security fixes: embed markdown as image failed in some cases
- Plugin settings now includes all available fonts when setting the default font when embedding markdown as image.
## New in ExcalidrawAutomate
- \`ea.zoomToElements()\` now accepts an optional margin parameter to control the amount of whitespace around the zoomed elements. The default margin is 0.05 (5% of the view size), but you can adjust it as needed for your specific use case.
- \`ea.cloneElements()\` function to clone elements with new IDs and updated relationships, useful for duplicating or moving elements without affecting the originals.
\`\`\`ts
/**
* Zooms the target view to fit the specified elements.
* @param {boolean} selectElements - Whether to select the elements after zooming.
* @param {ExcalidrawElement[]} elements - Array of elements to zoom to.
* @param {number} [margin=0.05] - The margin around the elements when zooming.
*/
viewZoomToElements(selectElements: boolean, elements: ExcalidrawElement[], margin: number = 0.05): void;
/**
* Clones an array of Excalidraw elements or a clipboard string.
* Ensures that relationships (containers, bound elements, groups, bindings)
* are correctly remapped to the newly generated IDs.
*
* @param {ExcalidrawElement[] | string} elementsOrClipboard - The elements array or Excalidraw clipboard string.
* @returns {ExcalidrawElement[]} An array of cloned elements with new IDs and updated relationships.
*/
cloneElements(elementsOrClipboard: ExcalidrawElement[] | string): ExcalidrawElement[];
\`\`\`
## Fixed in ExcalidrawAutomate
- \`ea.addImage()\` now supports adding the markdown section of an Excalidraw file as an image.
`,
"2.23.7": `
## Fixed
- Some Excalidraw Script Icons are loaded with extra bold line weight.
- BUG: Color remapping UI for Shade Master script does not appear to work when editing the colors of a nested Excalidraw drawing. [#2779](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2779)
`,
"2.23.6": `
I apologize in advance — there will likely be a few more micro-releases over the coming weeks.
I'm addressing the Obsidian code scanner findings gradually, and every code change carries some risk. I am making changes in small increments to minimize potential issues.
If you notice anything broken or behaving unexpectedly, please let me know. I'll do my best to investigate and fix it quickly.
## Fixed
- Links in language files
`,
"2.23.5": `
${getYouTubeDiv("otIHXat8Roo")}
## New
- Added **session-scoped AI usage metering** with per-model token/image tracking, a new **"Session token usage"** settings button with Markdown export, and an **"AI Usage: input/output"** button in ExcaliAI next to Run for quick access to the same breakdown.
- Added an explicit opt-in for executing <code>cmd://</code> links from drawings. Command links are now blocked by default, with a security warning prompt on first use and a dedicated setting under Excalidraw Automate.
- Replaced the dropped-link title resolver from Iframely with an HTTPS oEmbed endpoint.
- Hardened **data URL embeddables**: HTML loaded through <code>data:text/html</code> now renders in a sandboxed iframe with a defensive CSP to keep interactive content contained inside the embeddable.
- New option in settings to disable placeholder image.
## Fixed
- Fixed Taskbone OCR, which broke in 2.23.0.
- Fixed inline link suggester in MindMap Builder failing when filenames included the "." (dot) character. [#2772](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2772)
## New in ExcalidrawAutomate
- Added \`getPathForImageFileId(fileId: FileId): string | null\` — returns the vault path for an image element identified by its Excalidraw fileId. Note: Excalidraw does not maintain a persistent index of fileIds to paths; the path is only available for images that have appeared in an open drawing during the current Obsidian session.
- Gemini image models now expose **provider-correct size presets** in AI settings and ExcaliAI, with Google image requests automatically translating presets into Gemini aspect ratio and image size parameters.
- Added three new ExcalidrawAutomate methods for **AI token usage**.
\`\`\`ts
/**
* Returns accumulated AI token usage for the current Obsidian session.
* Usage is keyed by model identifier. Data is not persisted and resets on restart.
*/
public getAIUsage(): AIUsageData;
/**
* Opens a modal showing per-model AI token usage for the current session.
* Includes a "Copy as Markdown" button.
*/
public showAIUsageModal(): void;
/**
* Returns a compact label string: "AI Usage: 355k/23k" (input/output tokens).
* Appends image generation count when present, e.g. "+ 3 imgs".
*/
public formatAIUsageLabel(): string;
/**
* Returns the vault path for an image file identified by its Excalidraw fileId.
* Only available for images seen in an open drawing during the current session.
* @param {FileId} fileId - The Excalidraw fileId of the image.
* @returns {string | null} The vault path, or null if not cached in this session.
*/
getPathForImageFileId(fileId: FileId): string | null;
\`\`\`
`,
"2.23.3": `
I apologize in advance — there will likely be a few more micro-releases over the coming weeks.
I'm addressing the Obsidian scanner findings gradually, and every code change carries some risk. The safest approach I know is to ship small, incremental updates focused on specific fixes rather than large sweeping changes.
If you notice anything broken or behaving unexpectedly, please let me know. I'll do my best to investigate and fix it quickly.
## Fixed
- Excalidraw Script Library icons were not downloading correctly. [#2768](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2768)
`,
"2.23.2": `
## Fixed
- Further code scanner and transparency improvements, including a new \`ExcalidrawAutomate.printURLsInCodebase()\` function to list all URLs used in the codebase. All URL calls require explicit user action, either through enabled settings or clearly indicated links. Run the function in the Obsidian Developer Console (\`CTRL+SHIFT+I\` / \`CMD+OPT+I\`).
`,
"2.23.0": `
<div class="excalidraw-videoWrapper">
<a href="${URLs.WWW_YOUTUBE_COM_WATCH_2}" target="_blank"><img src="${URLs.I_YTIMG_COM_VI_EIT56Z3KPJI_MAXRESDEFAULT_JPG}" style="width:100%;"></a>
</div>
${getYouTubeDiv("EiT56z3KPjI")}
## New
- Added a new setting under *Excalidraw Automate* to opt-in to \`excalidraw-onload-scripts\`.
@@ -145,9 +305,7 @@ Share your work. Ask questions. Learn from others. 👉 https://community.sketc
Curious about the philosophy behind it?
<div class="excalidraw-videoWrapper">
<a href="${URLs.WWW_YOUTUBE_COM_WATCH_3}" target="_blank"><img src="${URLs.SKETCH_YOUR_MIND_COM_IMAGES_THUMBNAIL_PODCAST_JPG}" style="width:100%;"></a>
</div>
${getYouTubeDiv("TnwRlaIdhSU")}
`,
"2.22.1": `
@@ -155,26 +313,26 @@ Curious about the philosophy behind it?
- Added a command palette action to switch all currently open Excalidraw drawings to view mode.
- While this temporary mode is enabled, any Excalidraw drawing opened afterward will also open in view mode.
- This is useful when presenting multiple drawings and you want to avoid accidentally moving elements, and when you don't want the tools to be in the way.
- Added an optional phone-only layout setting to push Excalidraw's footer controls above the system navigation bar on some Android devices [#2688](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2688}), [#2652](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2652}), [#798](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_798})
- Added an optional phone-only layout setting to push Excalidraw's footer controls above the system navigation bar on some Android devices [#2688](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2688), [#2652](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2652), [#798](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/798)
- Look for ""Extra bottom padding for phone controls" in the plugin settings.
## Fixed
- invisible cursor color in color picker, mermaid chat, in text elements in dark mode [#2739](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2739})
- invisible cursor color in color picker, mermaid chat, in text elements in dark mode [#2739](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2739)
- image sizing issue when embedding image type "SVG Image" to markdown
- copying a nested image fragment in Excalidraw and pasting to markdown lost the image block reference
- modifier keys conflicted with Excalidraw alt-select (lasso) behavior
`,
"2.22.0": `
## Fixed
- Fixed misaligned panel buttons in tray mode [#2718](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2718}) 🙏[@heinrich26](${URLs.GITHUB_COM_HEINRICH26})
- Fixed misaligned panel buttons in tray mode [#2718](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2718) 🙏[@heinrich26](${URLs.GITHUB_COM}/heinrich26)
- Improved loading of nested Excalidraw files within a scene, with some additional performance gains.
- Fixed an issue where the caret color did not match the text color [#11018](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES_11018})
- Fixed an issue where the caret color did not match the text color [#11018](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES}/11018)
## New from Excalidraw.com
- Added several text editing improvements, including a right-side handle on wrapped text for easier auto-resizing without opening the context menu [#10979](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10979})
- Added support for Mermaid state diagrams [#11031](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_11031})
- There is a new Preferences menu above the Dark/Light mode switch in the main menu [#10760](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10760})
- Added a new Preferences option to switch between Wrap and Overlap selection modes. Overlap mode behaves similarly to the lasso selection tool available under More Tools [#11053](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_11053})
- Added several text editing improvements, including a right-side handle on wrapped text for easier auto-resizing without opening the context menu [#10979](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10979)
- Added support for Mermaid state diagrams [#11031](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11031)
- There is a new Preferences menu above the Dark/Light mode switch in the main menu [#10760](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10760)
- Added a new Preferences option to switch between Wrap and Overlap selection modes. Overlap mode behaves similarly to the lasso selection tool available under More Tools [#11053](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11053)
## New
- Added support for embedding the [Sheet Plus](obsidian://show-plugin?id=sheet-plus) plugin as an active embeddable element in Excalidraw. At the moment, changing the canvas theme between dark and light mode does not automatically re-render embedded sheets. To apply the theme change, close and reopen the drawing. This will likely be improved in a future update.
@@ -191,30 +349,30 @@ Curious about the philosophy behind it?
"2.21.2": `
## Fixed
- The new ExcalidrawAutomate function \`parseText()\` broke if the text was a transcluded image or PDF document, causing downstream paste issues in MindMap Builder.
- Custom pen sloppiness not being saved to a template drawing [#2715](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL_2715}) 🙏[@sreedharsreeram](${URLs.GITHUB_COM_SREEDHARSREERAM})
- Custom pen sloppiness not being saved to a template drawing [#2715](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2715) 🙏[@sreedharsreeram](${URLs.GITHUB_COM_SREEDHARSREERAM})
`,
"2.21.1": `
## Fixed
- Drawing and editor fails to initialize in a new window [#2713](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2713})
- Drawing and editor fails to initialize in a new window [#2713](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2713)
- Duplicate selected image with a different image ID command palette action did not duplicate cropped PDF images.
- Memory leak issue with PDF import as images.
## New
- Put caret at pointer position when clicking on selected text element [#10970](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10970})
- Put caret at pointer position when clicking on selected text element [#10970](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10970)
`,
"2.21.0": `
## New
- LaTeX editor is now floating [#2684](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL_2684}) 🙏[@TravisLEBLANC1](${URLs.GITHUB_COM_TRAVISLEBLANC1}), [#2698](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL_2698}) 🙏[@heinrich26](${URLs.GITHUB_COM_HEINRICH26})
- LaTeX editor is now floating [#2684](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2684) 🙏[@TravisLEBLANC1](${URLs.GITHUB_COM_TRAVISLEBLANC1}), [#2698](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2698) 🙏[@heinrich26](${URLs.GITHUB_COM}/heinrich26)
- Inline link suggester supports new triggers \`![[drawing#^frame=\` and \`![[drawing#^clippedframe=\`, thus it is easy to reference frames like pdf pages, slides or other parts of your scene marked using marker frames.
- Support for mermaid Entity Relationship Diagrams, and new ERD/cardinality arrowheads [#10940](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10940})
- New Context Menu options to disable arrow binding and midpoint snapping [#10906](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10906})
- Improved UI styling and icons are better aligned with Obsidian [#2703](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL_2703}), [#2687](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL_2687}), [#2697](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL_2697}) 🙏[@heinrich26](${URLs.GITHUB_COM_HEINRICH26})
- Support for mermaid Entity Relationship Diagrams, and new ERD/cardinality arrowheads [#10940](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10940)
- New Context Menu options to disable arrow binding and midpoint snapping [#10906](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10906)
- Improved UI styling and icons are better aligned with Obsidian [#2703](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2703), [#2687](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2687), [#2697](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2697) 🙏[@heinrich26](${URLs.GITHUB_COM}/heinrich26)
## Fixed
- Sizing of embedded images in Markdown when image type is set to SVG [#2685](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2685})
- Fixed Enter, Up/Down arrows, and TAB keys stopped working in text elements after deleting the \`#\` character [#2704](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2704})
- Sizing of embedded images in Markdown when image type is set to SVG [#2685](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2685)
- Fixed Enter, Up/Down arrows, and TAB keys stopped working in text elements after deleting the \`#\` character [#2704](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2704)
## MindMap Builder
- Fixed navigation (arrow keys) scoping and recognition
@@ -237,9 +395,7 @@ public async parseText (text: string): Promise<string | undefined>;
\`\`\`
`,
"2.20.6": `
<div class="excalidraw-videoWrapper">
<a href="${URLs.WWW_YOUTUBE_COM_WATCH_4}" target="_blank"><img src="${URLs.I_YTIMG_COM_VI_G_BIYQ7TJTM_MAXRESDEFAULT_JPG}" style="width:100%;"></a>
</div>
${getYouTubeDiv("g-BiyQ7TJTM")}
## New
- Inline suggester now supports searching for tags in addition to files. Trigger with "#".
@@ -249,8 +405,8 @@ public async parseText (text: string): Promise<string | undefined>;
- Added experimental MindMap Builder API, accessible via \`window.MindMapBuilderAPI\`. See [MindMap Builder API documentation](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_BLOB_MASTER_DOCS_EA_SCRIPT_DOCS_MINDMAPBUILDERAPI_MD}) for more. Essentially, the API allows mindmaps to be created using the Obsidian CLI.
## New from Excalidraw.com
- Allow clicking on links and embeds with laser tool [#10797](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10797})
- Improved paste text to diagram with more options and support for more data [#10824](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10824})
- Allow clicking on links and embeds with laser tool [#10797](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10797)
- Improved paste text to diagram with more options and support for more data [#10824](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10824)
try copy/pasting this into Excalidraw:
\`\`\`
@@ -265,51 +421,51 @@ stakeholder_mgmt, 1, 6, 10
## Fixed
- Significant performance improvement of MindMap Builder and all other scripts modifying elements in large scenes containing thousands of elements.
- Multiple arrow related updates and fixes from Excalidraw.com [#10832](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10832}) [#10831](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10831}) [#10816](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10816})
- Multiple arrow related updates and fixes from Excalidraw.com [#10832](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10832) [#10831](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10831) [#10816](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10816)
- Hide MindMap Builder and other floating tools when creating a screenshot
`,
"2.20.5": `
## Fixed
- Obsidian Mobile: The floating navigation bar got stuck at the bottom after closing Excalidraw or switching to a markdown note. [#2673](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2673})
- "Toggle UI Mode" now includes a preference setting for Obsidian Phone as well. You can now set different default layouts for phone, tablet, and desktop. [#2670](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2670})
- Obsidian Mobile: The floating navigation bar got stuck at the bottom after closing Excalidraw or switching to a markdown note. [#2673](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2673)
- "Toggle UI Mode" now includes a preference setting for Obsidian Phone as well. You can now set different default layouts for phone, tablet, and desktop. [#2670](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2670)
## New
- Added "Toggle Full Screen" button to toolbar right next to the "Obsidian menu", and the "Insert Any File" button.
`,
"2.20.4": `
## Fixed
- Fix NativeSVG embed mode into Markdown documents, ahead of the Obsidian 1.12.1 release. [#2665](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2665})
- Color picker once again supports 8-digit hex codes (Hex color string with an opacity). [#10772](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES_10772})
- Fixed regression that removed LaTeX scaling. [#2668](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL_2668}) 🙏[@TravisLEBLANC1](${URLs.GITHUB_COM_TRAVISLEBLANC1})
- Fix NativeSVG embed mode into Markdown documents, ahead of the Obsidian 1.12.1 release. [#2665](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2665)
- Color picker once again supports 8-digit hex codes (Hex color string with an opacity). [#10772](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES}/10772)
- Fixed regression that removed LaTeX scaling. [#2668](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2668) 🙏[@TravisLEBLANC1](${URLs.GITHUB_COM_TRAVISLEBLANC1})
- Corrected malformed frame embeds when using marker frames.
- Context menu options **“Do not invert image(s) in dark mode”** and **“Invert image(s) in dark mode”** now properly cascade when drawings are nested as images inside other drawings.
- Improved performance of the [MindMap Builder script](${URLs.VISUAL_THINKING_WORKSHOP_COM_MINDMAP}).
## New
- [Deconstruct Selected Elements script](${URLs.YOUTU_BE_HRTAAD34ZZG}) now includes a folder selection option, allowing you to choose the destination folder for the generated image.
- Arrow binding midpoints. When the projected point is close to center, snap it to the exact center. This way it's easier to create neat(er) simple arrow connections. [#10611](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10611})
- [Deconstruct Selected Elements script](${getYouTubeUrl("HRtaaD34Zzg")}) now includes a folder selection option, allowing you to choose the destination folder for the generated image.
- Arrow binding midpoints. When the projected point is close to center, snap it to the exact center. This way it's easier to create neat(er) simple arrow connections. [#10611](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10611)
`,
"2.20.3": `
## Fixed
- Hover preview when hovering an element with a link in the scene was unreliable
- If a text element had a link in the text body, in some situations, the link became unresponsive to clicks. [#2660](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2660})
- If a text element had a link in the text body, in some situations, the link became unresponsive to clicks. [#2660](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2660)
## New
- Added default keymap to latex editor [#2655](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL_2655}) 🙏[superle3](${URLs.GITHUB_COM_SUPERLE3})
- Added default keymap to latex editor [#2655](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2655) 🙏[superle3](${URLs.GITHUB_COM_SUPERLE3})
`,
"2.20.2": `
## New from Excalidraw.com
- Arrow focus indicator [#10613](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10613})
- Arrow focus indicator [#10613](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10613)
## Fixed
- Experimental file type display now also works in Obsidian Mobile. (Reported on Discord)
- Text to Mermaid stores chat history locally (i.e. not synchronized between devices).
- Image positioning in crop editor [#2589](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2589}), [#10726](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10726})
- Image positioning in crop editor [#2589](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2589), [#10726](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10726)
## MindMap Builder
- Implemented better undo support (effective only for the very last MindMap Builder action). Additionally, CMD/CTRL+Z and CTRL+Y, CMD+SHIFT+Z now work when the MindMap input window is focused.
- Fixed: Double character input issue (IME Composition Error) when creating nodes [#2647](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2647})
- Fixed: Double character input issue (IME Composition Error) when creating nodes [#2647](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2647)
- Fixed: More robust error handling when the MindMap is corrupted or invalid.
- Updated Excalidraw Writing Machine to support document generation from MindMaps. Writing Machine will honor the branch order. Requires update of the Writing Machine Script.
@@ -330,7 +486,7 @@ stakeholder_mgmt, 1, 6, 10
"2.20.1": `
## Fixed
- Fixed Experimental file type display, available under miscellaneous settings. (Reported on Discord)
- Fixed image inversion in dark mode on iOS devices. [#2636](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2636})
- Fixed image inversion in dark mode on iOS devices. [#2636](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2636)
- Fixed UI Mode switching on tablets was unreliable.
## New/Fixed in MindMap Builder
@@ -353,9 +509,7 @@ stakeholder_mgmt, 1, 6, 10
`,
"2.20.0": `
<div class="excalidraw-videoWrapper">
<a href="${URLs.WWW_YOUTUBE_COM_WATCH_5}" target="_blank"><img src="${URLs.I_YTIMG_COM_VI_5G9QF_U9W0Q_MAXRESDEFAULT_JPG}" style="width:100%;"></a>
</div>
${getYouTubeDiv("5G9QF-u9w0Q")}
> [!Tip]- Learn MindMap Builder
> Learn it fast with the low-cost [MindMap Builder course](${URLs.VISUAL_THINKING_WORKSHOP_COM_MINDMAP}). Register before **31 Jan** to join a live Q&A:
@@ -363,20 +517,20 @@ stakeholder_mgmt, 1, 6, 10
> - Sun Feb 1 @ 09:00 CET ([local time](${URLs.WWW_TIMEANDDATE_COM_WORLDCLOCK_FIXEDTIME_HTML_1}))
## Scripts
- Moved [Shade Master](${URLs.YOUTU_BE_ISUORBVKYHQ}) to use the new Excalidraw Sidepanel API (just like MindMap Builder).
- Moved [Shade Master](${getYouTubeUrl("ISuORbVKyhQ")}) to use the new Excalidraw Sidepanel API (just like MindMap Builder).
## New
- Dark theme from Excalidraw.com [#10578](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10578}) (including correct emoji rendering in dark mode 😍).
- Dark theme from Excalidraw.com [#10578](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10578) (including correct emoji rendering in dark mode 😍).
- New image context-menu option (right-click an image) to control whether that image inverts in dark mode
- Default behavior: SVG-based images (including LaTeX, Mermaid, and nested Excalidraw images) invert in dark mode; bitmap images (PNG/JPG) do not.
- New from Excalidraw.com: chat-style interface for Mermaid TextToDiagrams (requires an OpenAI API key configured in Excalidraw plugin settings). [#10530](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL_10530})
- New from Excalidraw.com: chat-style interface for Mermaid TextToDiagrams (requires an OpenAI API key configured in Excalidraw plugin settings). [#10530](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10530)
- Breaking change: the legacy “force SVG” option for Mermaid diagrams is no longer supported. If a diagram can be rendered as Excalidraw, it will be; otherwise, an SVG will be used.
- Moved the Shade Master script to use the new Sidepanel (just like MindMap Builder).
## Fixed
- In full-screen mode on phones, a large area at the top of the screen was left unused. Also fixed an issue where the Obsidian Mobile navigation bar could overlap the Excalidraw toolbar.
- The link indicator in the top-right corner would remain visible even when an element was set to transparent [#2625](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2625})
- Importing PDFs with mixed page sizes could produce distorted pages [#2578](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES_2578})
- The link indicator in the top-right corner would remain visible even when an element was set to transparent [#2625](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2625)
- Importing PDFs with mixed page sizes could produce distorted pages [#2578](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2578)
- Some PDFs failed to load when importing PDFs as images (notably documents using JPEG2000-compressed images). Also improved handling of certain color profiles and cases where text rendered with missing/incorrect glyphs.
- A long-standing export issue: when exporting in a theme different from the current view (e.g., viewing in dark mode but exporting in light mode), nested Excalidraw images containing bitmap images could export with inverted colors.
`,
+2 -1
View File
@@ -6,6 +6,7 @@ import {
ModifierSetType,
modifierKeyTooltipMessages,
} from "src/utils/modifierkeyHelper";
import { setStyle } from "src/utils/styleUtils";
type ModifierKeyCategories = Partial<{
[modifierSetType in ModifierSetType]: string;
@@ -113,7 +114,7 @@ export class ModifierKeySettingsComponent {
// the click via CMD being held). On macOS, CMD is also reserved for
// non-link-click actions.
toggle.setDisabled(true);
toggle.toggleEl.style.opacity = "0.5";
setStyle(toggle.toggleEl, { opacity: "0.5" });
}
});
@@ -7,6 +7,7 @@ import {
STANDARD_PAGE_SIZES,
} from "src/types/exportUtilTypes";
import { t } from "src/lang/helpers";
import { hideElement, showElement } from "src/utils/styleUtils";
export interface PDFExportSettings {
pageSize: PageSize;
@@ -55,15 +56,21 @@ export class PDFExportSettingsComponent {
.setValue(this.settings.pageSize)
.onChange((value) => {
this.settings.pageSize = value as PageSize;
div.style.display = this.isOrientationAndTilingVisible()
? "block"
: "none";
if (this.isOrientationAndTilingVisible()) {
showElement(div);
} else {
hideElement(div);
}
this.update();
}),
);
const div = this.contentEl.createDiv();
div.style.display = this.isOrientationAndTilingVisible() ? "block" : "none";
if (this.isOrientationAndTilingVisible()) {
showElement(div);
} else {
hideElement(div);
}
new Setting(div)
.setName(t("EXPORTDIALOG_PAGE_ORIENTATION"))
@@ -140,7 +147,11 @@ export class PDFExportSettingsComponent {
.setValue(this.settings.paperColor)
.onChange((value) => {
this.settings.paperColor = value as typeof this.settings.paperColor;
colorInput.style.display = value === "custom" ? "block" : "none";
if (value === "custom") {
showElement(colorInput);
} else {
hideElement(colorInput);
}
this.update();
}),
);
@@ -149,10 +160,12 @@ export class PDFExportSettingsComponent {
type: "color",
value: this.settings.customPaperColor,
});
colorInput.style.width = "50px";
colorInput.style.marginLeft = "10px";
colorInput.style.display =
this.settings.paperColor === "custom" ? "block" : "none";
colorInput.addClass("excalidraw-pdfexportsettings-colorinput");
if (this.settings.paperColor === "custom") {
showElement(colorInput);
} else {
hideElement(colorInput);
}
colorInput.addEventListener("change", (e) => {
this.settings.customPaperColor = (e.target as HTMLInputElement).value;
this.update();
+71 -39
View File
@@ -17,6 +17,7 @@ import { fragWithHTML } from "src/utils/utils";
import { setSanitizedHtml } from "src/utils/htmlUtils";
import { showColorPicker } from "./ColorPicker";
import { URLs } from "src/constants/safeUrls";
import { hideElement, showElement } from "src/utils/styleUtils";
const EASINGFUNCTIONS: Record<string, string> = {
linear: "linear",
@@ -71,9 +72,9 @@ export class PenSettingsModal extends Modal {
void this.createForm();
}
async onClose() {
onClose() {
if (this.dirty) {
await this.plugin.saveSettings();
void this.plugin.saveSettings();
getExcalidrawViews(this.app, true).forEach((excalidrawView) =>
excalidrawView.updatePinnedCustomPens(),
);
@@ -90,10 +91,10 @@ export class PenSettingsModal extends Modal {
if (COLOR_NAMES.has(color)) {
return [COLOR_NAMES.get(color), opacity];
}
const style = new Option().style;
style.color = color;
if (!!style.color) {
const digits = style.color.match(
const optionStyle = new Option().style;
optionStyle.color = color;
if (optionStyle.color) {
const digits = optionStyle.color.match(
/^[^\d]*(\d*)[^\d]*(\d*)[^\d]*(\d*)[^\d]*([\d.]*)?/,
);
if (!digits) {
@@ -191,7 +192,7 @@ export class PenSettingsModal extends Modal {
const strokeSetting = new Setting(ce)
.setName(
fragWithHTML(
!Boolean(ps.strokeColor)
!ps.strokeColor
? "Stroke color: <b>Current</b>"
: "Stroke color: <b>Preset color</b>",
),
@@ -203,9 +204,13 @@ export class PenSettingsModal extends Modal {
)
.addToggle((toggle) => {
strokeUseCurrentToggle = toggle;
toggle.setValue(!Boolean(ps.strokeColor)).onChange((value) => {
toggle.setValue(!ps.strokeColor).onChange((value) => {
this.dirty = true;
scSetting.settingEl.style.display = value ? "none" : "";
if (value) {
hideElement(scSetting.settingEl);
} else {
showElement(scSetting.settingEl);
}
strokeSetting.setName(
fragWithHTML(
value
@@ -288,7 +293,11 @@ export class PenSettingsModal extends Modal {
});
});
scSetting.settingEl.style.display = !Boolean(ps.strokeColor) ? "none" : "";
if (ps.strokeColor) {
showElement(scSetting.settingEl);
} else {
hideElement(scSetting.settingEl);
}
let bgcpComponent: ColorComponent;
let bgctComponent: TextComponent;
@@ -299,7 +308,7 @@ export class PenSettingsModal extends Modal {
const bgSetting = new Setting(ce)
.setName(
fragWithHTML(
!Boolean(ps.backgroundColor)
!ps.backgroundColor
? "Background color: <b>Current</b>"
: "Background color: <b>Preset color</b>",
),
@@ -311,7 +320,7 @@ export class PenSettingsModal extends Modal {
)
.addToggle((toggle) => {
bgUseCurrentToggle = toggle;
toggle.setValue(!Boolean(ps.backgroundColor)).onChange((value) => {
toggle.setValue(!ps.backgroundColor).onChange((value) => {
this.dirty = true;
bgSetting.setName(
fragWithHTML(
@@ -320,9 +329,18 @@ export class PenSettingsModal extends Modal {
: "Background color: <b>Preset color</b>",
),
);
bgctSetting.settingEl.style.display = value ? "none" : "";
bgcSetting.settingEl.style.display =
value || ps.backgroundColor === "transparent" ? "none" : "";
if (value) {
hideElement(bgctSetting.settingEl);
} else {
showElement(bgctSetting.settingEl);
}
if (value || ps.backgroundColor === "transparent") {
hideElement(bgcSetting.settingEl);
} else {
showElement(bgcSetting.settingEl);
}
if (value) {
delete ps.backgroundColor;
} else {
@@ -351,8 +369,13 @@ export class PenSettingsModal extends Modal {
.setValue(ps.backgroundColor === "transparent")
.onChange((value) => {
this.dirty = true;
bgcSetting.settingEl.style.display = value ? "none" : "";
fsSetting.settingEl.style.display = value ? "none" : "";
if (value) {
hideElement(bgcSetting.settingEl);
hideElement(fsSetting.settingEl);
} else {
showElement(bgcSetting.settingEl);
showElement(fsSetting.settingEl);
}
bgctSetting.setName(
fragWithHTML(
value
@@ -366,9 +389,11 @@ export class PenSettingsModal extends Modal {
});
});
bgctSetting.settingEl.style.display = !Boolean(ps.backgroundColor)
? "none"
: "";
if (ps.backgroundColor) {
showElement(bgctSetting.settingEl);
} else {
hideElement(bgctSetting.settingEl);
}
let bgChangeBounce: boolean = false;
const bgcSetting = new Setting(ce)
.setName("Background color")
@@ -433,10 +458,11 @@ export class PenSettingsModal extends Modal {
});
});
bgcSetting.settingEl.style.display =
!Boolean(ps.backgroundColor) || ps.backgroundColor === "transparent"
? "none"
: "";
if (!ps.backgroundColor || ps.backgroundColor === "transparent") {
hideElement(bgcSetting.settingEl);
} else {
showElement(bgcSetting.settingEl);
}
const fsSetting = new Setting(ce)
.setName("Fill Style")
@@ -456,10 +482,11 @@ export class PenSettingsModal extends Modal {
ps.fillStyle = value;
}),
);
fsSetting.settingEl.style.display =
!Boolean(ps.backgroundColor) || ps.backgroundColor === "transparent"
? "none"
: "";
if (!ps.backgroundColor || ps.backgroundColor === "transparent") {
hideElement(fsSetting.settingEl);
} else {
showElement(fsSetting.settingEl);
}
const rSetting = new Setting(ce)
.setName(
@@ -522,9 +549,11 @@ export class PenSettingsModal extends Modal {
toggle.setValue(!ps.penOptions.constantPressure).onChange((value) => {
this.dirty = true;
ps.penOptions.constantPressure = !value;
spSetting.settingEl.style.display = ps.penOptions.constantPressure
? "none"
: "";
if (ps.penOptions.constantPressure) {
hideElement(spSetting.settingEl);
} else {
showElement(spSetting.settingEl);
}
}),
);
@@ -588,7 +617,7 @@ export class PenSettingsModal extends Modal {
.setLimits(-1, 1, 0.05)
.setValue(ps.penOptions.options.thinning)
.onChange((value) => {
this.dirty;
this.dirty = true;
tSetting.setName(fragWithHTML(`Thinnning <b>${value}</b>`));
ps.penOptions.options.thinning = value;
}),
@@ -604,7 +633,7 @@ export class PenSettingsModal extends Modal {
.setLimits(0, 1, 0.05)
.setValue(ps.penOptions.options.smoothing)
.onChange((value) => {
this.dirty;
this.dirty = true;
sSetting.setName(fragWithHTML(`Smoothing <b>${value}</b>`));
ps.penOptions.options.smoothing = value;
}),
@@ -620,7 +649,7 @@ export class PenSettingsModal extends Modal {
.setLimits(0, 1, 0.05)
.setValue(ps.penOptions.options.streamline)
.onChange((value) => {
this.dirty;
this.dirty = true;
slSetting.setName(fragWithHTML(`Streamline <b>${value}</b>`));
ps.penOptions.options.streamline = value;
}),
@@ -672,9 +701,12 @@ export class PenSettingsModal extends Modal {
}
}),
);
spSetting.settingEl.style.display = ps.penOptions.constantPressure
? "none"
: "";
if (ps.penOptions.constantPressure) {
hideElement(spSetting.settingEl);
} else {
showElement(spSetting.settingEl);
}
ce.createEl("h3", { text: "Start" });
ce.createEl("p", { text: "Tapering options for the start of the line." });
@@ -707,7 +739,7 @@ export class PenSettingsModal extends Modal {
: ps.penOptions.options.start.taper,
)
.onChange((value) => {
this.dirty;
this.dirty = true;
ps.penOptions.options.start.taper = value === 151 ? true : value;
stSetting.setName(
fragWithHTML(
@@ -765,7 +797,7 @@ export class PenSettingsModal extends Modal {
: ps.penOptions.options.end.taper,
)
.onChange((value) => {
this.dirty;
this.dirty = true;
ps.penOptions.options.end.taper = value === 151 ? true : value;
etSetting.setName(
fragWithHTML(
+171 -130
View File
@@ -11,7 +11,7 @@ import {
} from "obsidian";
import ExcalidrawView from "../../view/ExcalidrawView";
import ExcalidrawPlugin from "../../core/main";
import { escapeRegExp, getLinkParts, sleep } from "../../utils/utils";
import { escapeRegExp } from "../../utils/utils";
import { getLeaf, openLeaf } from "../../utils/obsidianUtils";
import { createOrOverwriteFile } from "src/utils/fileUtils";
import { KeyEvent, isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
@@ -38,6 +38,15 @@ import { editorLivePreviewField } from "obsidian";
import { Extension } from "@codemirror/state";
import { FloatingModal } from "./FloatingModal";
import { setSanitizedHtml } from "src/utils/htmlUtils";
import { setStyle } from "src/utils/styleUtils";
/**
* Minimal type for obsidian-latex-suite plugin.
* Only types the properties actually used by this codebase.
*/
interface LatexSuitePlugin {
editorExtensions?: Extension | Extension[];
}
export class Prompt extends Modal {
private promptEl: HTMLInputElement;
@@ -67,7 +76,9 @@ export class Prompt extends Modal {
div.addClass("excalidraw-prompt-div");
if (this.prompt_desc) {
div = div.createDiv();
div.style.width = "100%";
setStyle(div, {
width: "100%",
});
const p = div.createEl("p");
setSanitizedHtml(p, this.prompt_desc);
}
@@ -96,11 +107,10 @@ export class Prompt extends Modal {
export class LaTexPrompt extends FloatingModal {
public waitForClose: Promise<string>;
private promptEl: HTMLInputElement;
private resolvePromise: (input: string) => void;
private rejectPromise: (reason?: any) => void;
private rejectPromise: (reason?: string) => void;
private editorView: EditorView;
private readonly latexsSuitePlugin: any;
private readonly latexsSuitePlugin: LatexSuitePlugin | undefined;
protected constructor(
app: App,
@@ -110,7 +120,9 @@ export class LaTexPrompt extends FloatingModal {
super(app);
this.titleEl.setText(this.prompt_text);
this.contentEl.addClass("excalidraw-LatexPrompt");
this.latexsSuitePlugin = app.plugins.plugins["obsidian-latex-suite"];
this.latexsSuitePlugin = app.plugins.plugins["obsidian-latex-suite"] as
| LatexSuitePlugin
| undefined;
super.enableKeyCapture(); // otherwise latex-suite (or Ctrl-Enter) do not get the key event
const mainContentContainer: HTMLDivElement = this.contentEl.createDiv();
this.display(default_value, mainContentContainer);
@@ -131,11 +143,20 @@ export class LaTexPrompt extends FloatingModal {
);
}
public static Prompt(
public static async Prompt(
plugin: ExcalidrawPlugin,
app: App,
prompt_text?: string,
default_value?: string,
): Promise<string> {
const mathjaxAPI = await plugin.extrasGateway.getMathJax();
if (!mathjaxAPI) {
return Promise.reject(
new Error("MathJax is not available or activation was cancelled"),
);
}
const latexprompt = new this(app, prompt_text, default_value);
return latexprompt.waitForClose;
@@ -169,7 +190,7 @@ export class LaTexPrompt extends FloatingModal {
extensions.push([
language,
editorLivePreviewField.init(() => false),
this.latexsSuitePlugin.editorExtensions,
this.latexsSuitePlugin?.editorExtensions,
]);
} else {
// Show a suggestion note if Latex Suite plugin is not installed
@@ -193,18 +214,21 @@ export class LaTexPrompt extends FloatingModal {
const actionButtonContainer: HTMLDivElement =
buttonBarContainer.createDiv();
setStyle(
this.createButton(
actionButtonContainer,
"",
() => this.submitCallback(),
t("PROMPT_BUTTON_OK") ?? "",
undefined,
"check",
).setCta().buttonEl,
{ marginRight: "0" },
);
this.createButton(
actionButtonContainer,
"",
this.submitCallback.bind(this),
t("PROMPT_BUTTON_OK") ?? "",
undefined,
"check",
).setCta().buttonEl.style.marginRight = "0";
this.createButton(
actionButtonContainer,
"",
this.cancelCallback.bind(this),
() => this.cancelCallback(),
t("PROMPT_BUTTON_CANCEL"),
undefined,
"x",
@@ -215,14 +239,16 @@ export class LaTexPrompt extends FloatingModal {
private createButton(
container: HTMLElement,
text: string,
callback: (evt: MouseEvent) => any,
callback: (evt: MouseEvent) => void,
tooltip: string = "",
margin: string = "5px",
iconId?: string,
) {
const btn = new ButtonComponent(container);
btn.buttonEl.style.padding = "0.5em";
btn.buttonEl.style.marginLeft = margin;
setStyle(btn.buttonEl, {
padding: "0.5em",
marginLeft: margin,
});
btn.setTooltip(tooltip);
if (iconId) {
@@ -250,8 +276,8 @@ export class LaTexPrompt extends FloatingModal {
this.close();
}
async onOpen(): Promise<void> {
await super.onOpen();
onOpen(): void {
super.onOpen();
this.editorView.focus();
}
@@ -266,7 +292,7 @@ export class GenericInputPrompt extends Modal {
private view: ExcalidrawView;
private plugin: ExcalidrawPlugin;
private resolvePromise: (input: string) => void;
private rejectPromise: (reason?: any) => void;
private rejectPromise: (reason?: string) => void;
private didSubmit: boolean = false;
private inputComponent: TextAreaComponent;
private input: string;
@@ -386,9 +412,9 @@ export class GenericInputPrompt extends Modal {
this.contentEl.empty();
if (this.blockPointerInputOutsideModal) {
const bgEl = this.bgEl;
bgEl.style.pointerEvents = this.blockPointerInputOutsideModal
? "none"
: "auto";
setStyle(bgEl, {
pointerEvents: this.blockPointerInputOutsideModal ? "none" : "auto",
});
}
this.titleEl.textContent = this.header;
@@ -426,11 +452,15 @@ export class GenericInputPrompt extends Modal {
) {
const textComponent = new TextAreaComponent(container);
textComponent.inputEl.style.width = "100%";
textComponent.inputEl.style.height = `${this.lines * 2}em`;
setStyle(textComponent.inputEl, {
width: "100%",
height: `${this.lines * 2}em`,
});
if (this.lines === 1) {
textComponent.inputEl.style.resize = "none";
textComponent.inputEl.style.overflow = "hidden";
setStyle(textComponent.inputEl, {
resize: "none",
overflow: "hidden",
});
}
textComponent
.setPlaceholder(placeholder ?? "")
@@ -456,14 +486,16 @@ export class GenericInputPrompt extends Modal {
private createButton(
container: HTMLElement,
text: string,
callback: (evt: MouseEvent) => any,
callback: (evt: MouseEvent) => void,
tooltip: string = "",
margin: string = "5px",
iconId?: string,
) {
const btn = new ButtonComponent(container);
btn.buttonEl.style.padding = "0.5em";
btn.buttonEl.style.marginLeft = margin;
setStyle(btn.buttonEl, {
padding: "0.5em",
marginLeft: margin,
});
btn.setTooltip(tooltip);
if (iconId) {
@@ -487,17 +519,26 @@ export class GenericInputPrompt extends Modal {
buttonBarContainer.createDiv();
if (this.buttons && this.buttons.length > 0) {
let b = null;
let b: ButtonComponent = null;
for (const button of this.buttons) {
const btn = new ButtonComponent(actionButtonContainer);
btn.buttonEl.style.marginLeft = "5px";
setStyle(btn.buttonEl, {
marginLeft: "5px",
});
if (button.tooltip) {
btn.setTooltip(button.tooltip);
}
button.iconId
? btn.setIcon(button.iconId)
: btn.setButtonText(button.caption);
button.tooltip && btn.setTooltip(button.tooltip);
if (button.iconId) {
btn.setIcon(button.iconId);
} else {
btn.setButtonText(button.caption);
}
if (button.tooltip) {
btn.setTooltip(button.tooltip);
}
btn.onClick(() => {
const res = button.action(this.input);
if (res) {
@@ -507,25 +548,32 @@ export class GenericInputPrompt extends Modal {
});
b = b ?? btn;
}
if (b) {
if (b !== null) {
b.setCta();
b.buttonEl.style.marginRight = "0";
setStyle(b.buttonEl, {
marginRight: "0",
});
}
} else {
this.createButton(
actionButtonContainer,
"",
this.submitClickCallback.bind(this),
t("PROMPT_BUTTON_OK") ?? "",
"5px",
"check",
).setCta().buttonEl.style.marginRight = "0";
setStyle(
this.createButton(
actionButtonContainer,
"",
() => this.submitClickCallback(),
t("PROMPT_BUTTON_OK") ?? "",
"5px",
"check",
).setCta().buttonEl,
{
marginRight: "0",
},
);
}
this.createButton(
actionButtonContainer,
"",
this.cancelClickCallback.bind(this),
() => this.cancelClickCallback(),
t("PROMPT_BUTTON_CANCEL"),
"5px",
"x",
@@ -543,7 +591,7 @@ export class GenericInputPrompt extends Modal {
this.createButton(
editorButtonContainer,
"",
this.delBtnClickCallback.bind(this),
() => this.delBtnClickCallback(),
"Delete",
"5px",
"delete",
@@ -559,7 +607,7 @@ export class GenericInputPrompt extends Modal {
this.createButton(
editorButtonContainer,
"",
this.specialCharsBtnClickCallback.bind(this),
(evt) => this.specialCharsBtnClickCallback(evt),
t("PROMPT_BUTTON_SPECIAL_CHARS"),
"5px",
"at-sign",
@@ -568,7 +616,7 @@ export class GenericInputPrompt extends Modal {
this.createButton(
editorButtonContainer,
"",
this.linkBtnClickCallback.bind(this),
() => this.linkBtnClickCallback(),
t("PROMPT_BUTTON_INSERT_LINK"),
"5px",
"link",
@@ -577,7 +625,7 @@ export class GenericInputPrompt extends Modal {
this.createButton(
editorButtonContainer,
"",
this.uppercaseBtnClickCallback.bind(this),
() => this.uppercaseBtnClickCallback(),
t("PROMPT_BUTTON_UPPERCASE"),
"5px",
"arrow-big-up",
@@ -724,8 +772,8 @@ export class GenericInputPrompt extends Modal {
this.view.ownerWindow.clearTimeout(this.selectionUpdateTimer);
// Remove any existing popup
const existingPopup = document.querySelector(
".excalidraw-special-chars-popup",
const existingPopup = activeDocument.querySelector(
".excalidraw-genericInputPrompt-specialCharPopup",
);
if (existingPopup) {
existingPopup.remove();
@@ -733,24 +781,15 @@ export class GenericInputPrompt extends Modal {
}
// Create popup element
const popup = document.createElement("div");
popup.className = "excalidraw-special-chars-popup";
popup.style.position = "absolute";
popup.style.zIndex = "1000";
popup.style.background = "var(--background-primary)";
popup.style.border = "1px solid var(--background-modifier-border)";
popup.style.borderRadius = "4px";
popup.style.padding = "4px";
popup.style.boxShadow = "0 2px 8px var(--background-modifier-box-shadow)";
popup.style.display = "flex";
popup.style.flexWrap = "wrap";
popup.style.maxWidth = "200px";
const popup = activeDocument.createElement("div");
popup.addClass("excalidraw-genericInputPrompt-specialCharPopup");
// Position near the button
const rect = (evt.target as HTMLElement).getBoundingClientRect();
popup.style.top = `${rect.bottom + 5}px`;
popup.style.left = `${rect.left}px`;
setStyle(popup, {
top: `${rect.bottom + 5}px`,
left: `${rect.left}px`,
});
// Special characters to include
const specialChars = [
",",
@@ -770,15 +809,9 @@ export class GenericInputPrompt extends Modal {
// Add character buttons
specialChars.forEach((char) => {
const charButton = document.createElement("button");
const charButton = activeDocument.createElement("button");
charButton.textContent = char;
charButton.style.margin = "2px";
charButton.style.width = "28px";
charButton.style.height = "28px";
charButton.style.cursor = "pointer";
charButton.style.background = "var(--interactive-normal)";
charButton.style.border = "none";
charButton.style.borderRadius = "4px";
charButton.addClass("excalidraw-genericInputPrompt-specialCharButton");
charButton.addEventListener("click", () => {
this.insertStringBtnClickCallback(char);
@@ -795,19 +828,19 @@ export class GenericInputPrompt extends Modal {
(evt.target as HTMLElement) !== e.target
) {
popup.remove();
document.removeEventListener("click", closePopupListener);
activeDocument.removeEventListener("click", closePopupListener);
}
};
// Add to document and set up listeners
document.body.appendChild(popup);
activeDocument.body.appendChild(popup);
window.setTimeout(() => {
document.addEventListener("click", closePopupListener);
activeDocument.addEventListener("click", closePopupListener);
}, 10);
};
async onOpen() {
await super.onOpen();
onOpen() {
super.onOpen();
this.modalEl.classList.add("excalidraw-modal");
this.containerEl.classList.add("excalidraw-modal");
this.inputComponent.inputEl.focus();
@@ -832,7 +865,9 @@ export class GenericInputPrompt extends Modal {
modalEl.querySelector(".modal-titlebar") ||
modalEl.querySelector(".modal-title") ||
modalEl;
(header as HTMLElement).style.cursor = "move";
setStyle(header as HTMLElement, {
cursor: "move",
});
// Track focus changes to store the last focused interactive element
const onFocusIn = (e: FocusEvent) => {
@@ -894,10 +929,12 @@ export class GenericInputPrompt extends Modal {
initialX = rect.left;
initialY = rect.top;
modalEl.style.position = "absolute";
modalEl.style.margin = "0";
modalEl.style.left = `${initialX}px`;
modalEl.style.top = `${initialY}px`;
setStyle(modalEl, {
position: "absolute",
margin: "0",
left: `${initialX}px`,
top: `${initialY}px`,
});
};
const onPointerMove = (e: PointerEvent) => {
@@ -908,8 +945,10 @@ export class GenericInputPrompt extends Modal {
const dx = e.clientX - startX;
const dy = e.clientY - startY;
modalEl.style.left = `${initialX + dx}px`;
modalEl.style.top = `${initialY + dy}px`;
setStyle(modalEl, {
left: `${initialX + dx}px`,
top: `${initialY + dy}px`,
});
};
const onPointerUp = () => {
@@ -950,15 +989,15 @@ export class GenericInputPrompt extends Modal {
// Set up event listeners
modalEl.addEventListener("focusin", onFocusIn);
modalEl.addEventListener("pointerdown", onPointerDown);
document.addEventListener("pointermove", onPointerMove);
document.addEventListener("pointerup", onPointerUp);
activeDocument.addEventListener("pointermove", onPointerMove);
activeDocument.addEventListener("pointerup", onPointerUp);
// Store cleanup function for use in onClose
this.cleanupDragListeners = () => {
modalEl.removeEventListener("focusin", onFocusIn);
modalEl.removeEventListener("pointerdown", onPointerDown);
document.removeEventListener("pointermove", onPointerMove);
document.removeEventListener("pointerup", onPointerUp);
activeDocument.removeEventListener("pointermove", onPointerMove);
activeDocument.removeEventListener("pointerup", onPointerUp);
};
}
@@ -975,20 +1014,20 @@ export class GenericInputPrompt extends Modal {
}
}
export class GenericSuggester extends FuzzySuggestModal<any> {
private resolvePromise: (value: any) => void;
private rejectPromise: (reason?: any) => void;
public promise: Promise<any>;
export class GenericSuggester<T> extends FuzzySuggestModal<T> {
private resolvePromise: (value: T) => void;
private rejectPromise: (reason?: string) => void;
public promise: Promise<T>;
private resolved: boolean;
public static Suggest(
public static Suggest<T>(
app: App,
displayItems: string[],
items: string[],
items: T[],
hint?: string,
instructions?: Instruction[],
) {
const newSuggester = new GenericSuggester(
const newSuggester = new GenericSuggester<T>(
app,
displayItems,
items,
@@ -1001,7 +1040,7 @@ export class GenericSuggester extends FuzzySuggestModal<any> {
public constructor(
app: App,
private displayItems: string[],
private items: any[],
private items: T[],
private hint?: string,
private instructions?: Instruction[],
) {
@@ -1011,7 +1050,7 @@ export class GenericSuggester extends FuzzySuggestModal<any> {
if (instructions) {
this.setInstructions(this.instructions);
}
this.promise = new Promise<any>((resolve, reject) => {
this.promise = new Promise<T>((resolve, reject) => {
this.resolvePromise = resolve;
this.rejectPromise = reject;
});
@@ -1019,20 +1058,20 @@ export class GenericSuggester extends FuzzySuggestModal<any> {
this.open();
}
getItemText(item: string): string {
getItemText(item: T): string {
return this.displayItems[this.items.indexOf(item)];
}
getItems(): any[] {
getItems(): T[] {
return this.items;
}
selectSuggestion(value: FuzzyMatch<string>, evt: MouseEvent | KeyboardEvent) {
selectSuggestion(value: FuzzyMatch<T>, evt: MouseEvent | KeyboardEvent) {
this.resolved = true;
super.selectSuggestion(value, evt);
}
onChooseItem(item: any): void {
onChooseItem(item: T): void {
this.resolved = true;
this.resolvePromise(item);
}
@@ -1048,7 +1087,7 @@ export class GenericSuggester extends FuzzySuggestModal<any> {
export class NewFileActions extends Modal {
public waitForClose: Promise<TFile | null>;
private resolvePromise: (file: TFile | null) => void;
private rejectPromise: (reason?: any) => void;
private rejectPromise: (reason?: string) => void;
private newFile: TFile = null;
private plugin: ExcalidrawPlugin;
private path: string;
@@ -1130,7 +1169,7 @@ export class NewFileActions extends Modal {
this.contentEl.createDiv({ cls: "excalidraw-prompt-center" }, (el) => {
//files manually follow one of two options:
el.style.textAlign = "right";
setStyle(el, { textAlign: "right" });
const checks = (): boolean => {
if (!this.path || this.path === "") {
@@ -1221,36 +1260,36 @@ export class NewFileActions extends Modal {
}
}
export class MultiOptionConfirmationPrompt extends Modal {
public waitForClose: Promise<any>;
private resolvePromise: (value: any) => void;
private rejectPromise: (reason?: any) => void;
private selectedValue: any = null;
export class MultiOptionConfirmationPrompt<T = boolean | null> extends Modal {
public waitForClose: Promise<T>;
private resolvePromise: (value: T) => void;
private rejectPromise: (reason?: string) => void;
private selectedValue: T = null;
private readonly message: string;
private readonly buttons: Map<string, any>;
private readonly buttons: Map<string, T>;
private ctaButtonLabel: string = null;
private ctaButtonEl: HTMLButtonElement | null = null;
constructor(
private plugin: ExcalidrawPlugin,
message: string,
buttons?: Map<string, any>,
buttons?: Map<string, T>,
ctaButtonLabel?: string,
) {
super(plugin.app);
this.message = message;
if (!buttons || buttons.size === 0) {
buttons = new Map<string, any>([
buttons = new Map<string, boolean | null>([
[t("PROMPT_BUTTON_CANCEL"), null],
[t("PROMPT_BUTTON_OK"), true],
]);
]) as unknown as Map<string, T>;
if (!ctaButtonLabel) {
ctaButtonLabel = t("PROMPT_BUTTON_CANCEL");
}
}
this.ctaButtonLabel = ctaButtonLabel;
this.buttons = buttons;
this.waitForClose = new Promise<any>((resolve, reject) => {
this.waitForClose = new Promise<T>((resolve, reject) => {
this.resolvePromise = resolve;
this.rejectPromise = reject;
});
@@ -1264,13 +1303,13 @@ export class MultiOptionConfirmationPrompt extends Modal {
this.titleEl.textContent = t("PROMPT_TITLE_CONFIRMATION");
const messageEl = this.contentEl.createDiv();
messageEl.style.marginBottom = "1rem";
messageEl.addClass("excalidraw-multiOptionConfirmationPrompt-message");
setSanitizedHtml(messageEl, this.message);
const buttonContainer = this.contentEl.createDiv();
buttonContainer.style.display = "flex";
buttonContainer.style.justifyContent = "flex-end";
buttonContainer.style.flexWrap = "wrap";
buttonContainer.addClass(
"excalidraw-multiOptionConfirmationPrompt-buttonContainer",
);
// Convert Map to Array for easier iteration
const buttonEntries = Array.from(this.buttons.entries());
@@ -1289,7 +1328,9 @@ export class MultiOptionConfirmationPrompt extends Modal {
}
if (index < buttonEntries.length - 1) {
button.buttonEl.style.marginRight = "0.5rem";
setStyle(button.buttonEl, {
marginRight: "0.5rem",
});
}
});
@@ -1309,8 +1350,8 @@ export class MultiOptionConfirmationPrompt extends Modal {
return button;
}
async onOpen() {
await super.onOpen();
onOpen() {
super.onOpen();
const defaultButton =
this.ctaButtonEl ?? this.contentEl.querySelector("button");
// Obsidian modal open may apply its own autofocus after onOpen; defer to enforce default keyboard action.
@@ -1423,9 +1464,9 @@ export async function linkPrompt(
}
if (linkText.search("#") > -1) {
const linkParts = getLinkParts(linkText, view ? view.file : undefined);
subpath = `#${linkParts.isBlockRef ? "^" : ""}${linkParts.ref}`;
linkText = linkParts.path;
const hashIndex = linkText.indexOf("#");
subpath = linkText.slice(hashIndex);
linkText = linkText.slice(0, hashIndex);
}
if (linkText.match(REG_LINKINDEX_INVALIDCHARS)) {
new Notice(t("FILENAME_INVALID_CHARS"), 4000);
+4 -4
View File
@@ -1,4 +1,4 @@
import { Modal, Setting, TFile } from "obsidian";
import { Modal, Setting, TFile, TAbstractFile } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
import { getIMGFilename } from "src/utils/fileUtils";
import { setElementDisplay } from "src/utils/htmlUtils";
@@ -61,10 +61,10 @@ const listOfOutOfSyncImgExports = async (
}
const outOfSyncFiles = new Set<TFile>();
const allFiles = list.files.filter(
(f: any) => f.path.endsWith(".svg") || f.path.endsWith(".png"),
(f: TAbstractFile) => f.path.endsWith(".svg") || f.path.endsWith(".png"),
);
const totalCount = allFiles.length;
allFiles.forEach((f: any, idx: number) => {
allFiles.forEach((f: TAbstractFile, idx: number) => {
const maybeExcalidraFilePath = getIMGFilename(f.path, "md");
const imgFile = app.vault.getAbstractFileByPath(f.path);
const excalidrawFile = app.vault.getAbstractFileByPath(
@@ -105,7 +105,7 @@ export class PublishOutOfDateFilesDialog extends Modal {
super(plugin.app);
}
async onClose() {}
onClose() {}
onOpen() {
this.containerEl.classList.add("excalidraw-release");
+10 -7
View File
@@ -1,13 +1,13 @@
import { App, MarkdownRenderer, Modal } from "obsidian";
import ExcalidrawPlugin from "../../core/main";
import { App, Component, MarkdownRenderer, Modal } from "obsidian";
import { Rank, SwordColors } from "src/constants/actionIcons";
import { convertSVGStringToElement } from "src/utils/utils";
import { URLs } from "src/constants/safeUrls";
import { setStyle } from "src/utils/styleUtils";
export class RankMessage extends Modal {
private renderComponent: Component;
constructor(
app: App,
private plugin: ExcalidrawPlugin,
private filecount: number,
private rank: Rank,
private color: string,
@@ -18,15 +18,17 @@ export class RankMessage extends Modal {
}
onOpen(): void {
this.renderComponent = new Component();
this.renderComponent.load();
//this.contentEl.classList.add("excalidraw-release");
this.containerEl.classList.add("excalidraw-release");
this.titleEl.setText("Congratulations, glorious knight!");
void this.createForm();
}
async onClose() {
onClose() {
this.contentEl.empty();
this.plugin = null;
this.renderComponent.unload();
}
async createForm() {
@@ -44,12 +46,13 @@ export class RankMessage extends Modal {
`You have ${this.filecount} Excalidraw drawings in your Vault earning you a new rank: **${this.rank}**! You've ascended to **${title}**!\n\nI've spent the past 3+ years building this plugin. If you appreciate my work, consider supporting me on [Ko-Fi](${URLs.KO_FI_COM_ZSOLT}) or join the next [Visual Thinking Workshop](${URLs.VISUAL_THINKING_WORKSHOP_COM}) cohort.`,
this.contentEl,
"",
this.plugin,
this.renderComponent,
);
this.contentEl.createEl("p", { text: "" }, (el) => {
//files manually follow one of two options:
el.style.textAlign = "right";
setStyle(el, { textAlign: "right" });
const bOk = el.createEl("button", { text: "Close" });
bOk.onclick = () => this.close();
});
+17 -10
View File
@@ -1,8 +1,9 @@
import { App, MarkdownRenderer, Modal } from "obsidian";
import { App, Component, MarkdownRenderer, Modal } from "obsidian";
import { isVersionNewerThanOther } from "src/utils/utils";
import ExcalidrawPlugin from "../../core/main";
import { RELEASE_NOTES } from "./Messages";
import { t } from "src/lang/helpers";
import { setStyle } from "src/utils/styleUtils";
declare const PLUGIN_VERSION: string;
@@ -16,6 +17,7 @@ export class ReleaseNotes extends Modal {
private plugin: ExcalidrawPlugin;
private options: ReleaseNotesOptions;
private version: string;
private renderComponent: Component;
constructor(
app: App,
@@ -30,6 +32,8 @@ export class ReleaseNotes extends Modal {
}
onOpen(): void {
this.renderComponent = new Component();
this.renderComponent.load();
const { containerEl, titleEl, headerEl } = this;
//this.contentEl.classList.add("excalidraw-release");
containerEl.classList.add("excalidraw-release");
@@ -39,20 +43,23 @@ export class ReleaseNotes extends Modal {
void this.createForm();
if (headerEl) {
headerEl.style.pointerEvents = "none";
setStyle(headerEl, { pointerEvents: "none" });
} // Disable pointer events on header to allow clicks through
}
async onClose() {
onClose() {
this.contentEl.empty();
this.renderComponent.unload();
if (this.options.persistVersion === false) {
return;
}
await this.plugin.loadSettings();
if (this.plugin.settings.previousRelease !== PLUGIN_VERSION) {
this.plugin.settings.previousRelease = PLUGIN_VERSION;
await this.plugin.saveSettings();
}
void (async () => {
await this.plugin.loadSettings();
if (this.plugin.settings.previousRelease !== PLUGIN_VERSION) {
this.plugin.settings.previousRelease = PLUGIN_VERSION;
await this.plugin.saveSettings();
}
})();
}
async createForm() {
@@ -78,12 +85,12 @@ export class ReleaseNotes extends Modal {
message,
this.contentEl,
"",
this.plugin,
this.renderComponent,
);
this.contentEl.createEl("p", { text: "" }, (el) => {
//files manually follow one of two options:
el.style.textAlign = "right";
setStyle(el, { textAlign: "right" });
const bOk = el.createEl("button", { text: "Close" });
bOk.onclick = () => this.close();
});
+39 -34
View File
@@ -1,65 +1,70 @@
import { MarkdownRenderer, Modal, Notice, request } from "obsidian";
import { Component, MarkdownRenderer, Modal, Notice, request } from "obsidian";
import ExcalidrawPlugin from "../../core/main";
import { errorlog } from "../../utils/utils";
import { log } from "src/utils/debugHelper";
import { ContentSearcher } from "../components/ContentSearcher";
import { URLs } from "src/constants/safeUrls";
import { mainDocument } from "src/constants/constants";
import { t } from "src/lang/helpers";
const URL =
URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_INDEX_NEW_MD;
export class ScriptInstallPrompt extends Modal {
private contentDiv: HTMLDivElement;
private renderComponent: Component;
constructor(private plugin: ExcalidrawPlugin) {
super(plugin.app);
// this.titleEl.setText(t("INSTAL_MODAL_TITLE"));
}
async onOpen(): Promise<void> {
onOpen(): void {
this.renderComponent = new Component();
this.renderComponent.load();
this.contentEl.classList.add("excalidraw-scriptengine-install");
this.contentDiv = document.createElement("div");
this.contentDiv = mainDocument.createElement("div");
this.contentEl.appendChild(this.contentDiv);
new ContentSearcher(this.contentDiv);
this.containerEl.classList.add("excalidraw-scriptengine-install");
try {
const source = await request({ url: URL });
if (!source) {
new Notice(
"Error opening the Excalidraw Script Store page. " +
"Please double check that you can access the website. " +
"I've logged the link in developer console (press CTRL+SHIFT+i)",
5000,
void (async () => {
try {
const source = await request({ url: URL });
if (!source) {
new Notice(t("SCRIPT_INSTALL_PROMPT_FETCH_ERROR"), 5000);
log(URL);
this.close();
return;
}
await MarkdownRenderer.render(
this.plugin.app,
source,
this.contentDiv,
"",
this.renderComponent,
);
log(URL);
this.close();
return;
}
await MarkdownRenderer.render(
this.plugin.app,
source,
this.contentDiv,
"",
this.plugin,
);
this.contentDiv
.querySelectorAll("h1[data-heading],h2[data-heading],h3[data-heading]")
.forEach((el) => {
el.setAttribute("id", el.getAttribute("data-heading"));
this.contentDiv
.querySelectorAll(
"h1[data-heading],h2[data-heading],h3[data-heading]",
)
.forEach((el) => {
el.setAttribute("id", el.getAttribute("data-heading"));
});
this.contentDiv.querySelectorAll("a.internal-link").forEach((el) => {
el.removeAttribute("target");
});
this.contentDiv.querySelectorAll("a.internal-link").forEach((el) => {
el.removeAttribute("target");
});
} catch (e) {
errorlog({ where: "ScriptInstallPrompt.onOpen", error: e });
new Notice("Could not open ScriptEngine repository");
this.close();
}
} catch (e) {
errorlog({ where: "ScriptInstallPrompt.onOpen", error: e as unknown });
new Notice(t("SCRIPT_INSTALL_PROMPT_OPEN_ERROR"));
this.close();
}
})();
}
onClose(): void {
this.contentEl.empty();
this.renderComponent.unload();
}
}
-1
View File
@@ -2,7 +2,6 @@ import { App, FuzzySuggestModal, Notice } from "obsidian";
import { t } from "../../lang/helpers";
import ExcalidrawView from "src/view/ExcalidrawView";
import { getEA } from "src/core";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import {
CARD_HEIGHT,
CARD_WIDTH,
+45 -6
View File
@@ -528,7 +528,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "getExcalidrawAPI",
code: "getExcalidrawAPI(): any;",
code: "getExcalidrawAPI(): ExcalidrawImperativeAPI;",
desc: `${hyperlink(URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_TREE_MASTER_SRC_PACKAGES_EXCALIDRAW, "Excalidraw API")}`,
after: "",
},
@@ -573,6 +573,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "Returns the TFile file handle for the image element",
after: "",
},
{
field: "getPathForImageFileId",
code: "getPathForImageFileId(fileId: FileId): string | null;",
desc: "Returns the vault or external URI path for an image identified by its Excalidraw fileId. Note: this will only return a path for images that have appeared in an open drawing during the current Obsidian session. Excalidraw does not maintain a persistent index of fileIds to paths — it only caches them at runtime to support copy/paste of image references between drawings without duplicating files.",
after: "",
},
{
field: "updateViewSVGImageColorMap",
code: "async updateViewSVGImageColorMap(elements: ExcalidrawImageElement | ExcalidrawImageElement[], colors: ColorMap | SVGColorInfo | ColorMap[] | SVGColorInfo[]): Promise<void>;",
@@ -743,7 +749,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "setScriptSettings",
code: "async setScriptSettings(settings: any): Promise<void>;",
code: "async setScriptSettings(settings: Record<string, unknown>): Promise<void>;",
desc: `Sets script settings.\nSee for more details: ${hyperlink(URLs.ZSVICZIAN_GITHUB_IO_OBSIDIAN_EXCALIDRAW_PLUGIN_EXCALIDRAWSCRIPTSENGINE_HTML, "Script Engine Help")}`,
after: "",
},
@@ -833,6 +839,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "Returns a clone of the element with a new element id",
after: "",
},
{
field: "cloneElements",
code: "cloneElements(elementsOrClipboard: ExcalidrawElement[] | string): ExcalidrawElement[];",
desc: "Clones an array of Excalidraw elements or a clipboard string, ensuring that relationships (containers, bound elements, groups, bindings) are correctly remapped to the newly generated IDs.",
after: "",
},
{
field: "moveViewElementToZIndex",
code: "moveViewElementToZIndex(elementId:number, newZIndex:number): void;",
@@ -945,7 +957,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "getActiveEmbeddableViewOrEditor",
code: "getActiveEmbeddableViewOrEditor (view?:ExcalidrawView): {view:any}|{file:TFile, editor:Editor}|{node: ObsidianCanvasNode}|null;",
code: "getActiveEmbeddableViewOrEditor (view?:ExcalidrawView): {view:View}|{file:TFile, editor:Editor}|{node: ObsidianCanvasNode}|null;",
desc:
"Returns the editor or leaf.view of the currently active embedded obsidian file.<br>" +
"If view is not provided, ea.targetView is used.<br>" +
@@ -1102,7 +1114,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
"<b>imageGenerationProperties</b>: <code>{ size?, quality?, n?, mask? }</code>. If present, Excalidraw uses the image generation/edit pipeline. <code>mask</code> accepts the same format as <code>image</code>.<br>" +
"<b>File support by provider</b>: Google accepts inline file/audio parts such as PDFs and voice clips. Anthropic currently accepts PDF document parts. OpenAI/OpenAI-compatible/xAI remain limited to text plus images in the current chat-completions pipeline.<br>" +
"<b>RequestUrlResponse</b> returns:<br>" +
"<code>{ status:number, headers:Record<string,string>, text:string, json:any, arrayBuffer:ArrayBuffer }</code><br>" +
"<code>{ status:number, headers:Record<string,string>, text:string, json:Record<string,unknown>, arrayBuffer:ArrayBuffer }</code><br>" +
"For text models, <code>json</code> is normalized to an OpenAI-style chat completion object, so existing scripts can continue reading <code>json.choices[0].message.content</code>. For image models, <code>json</code> preserves the image endpoint response such as <code>json.data[0].url</code>.",
after: "",
},
@@ -1166,6 +1178,33 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
"Use this when a script needs Mermaid-style iterative prompting without manually maintaining the message array.",
after: "",
},
{
field: "getAIUsage",
code: "getAIUsage(): AIUsageData",
desc:
"Returns accumulated AI token usage for the current Obsidian session, keyed by model identifier.<br>" +
"<code>AIUsageData</code> contains <code>textModels</code> (inputTokens, outputTokens per model), " +
"<code>imageModels</code> (generations per model), and session totals.<br>" +
"Usage is not persisted and resets when Obsidian is restarted.",
after: "",
},
{
field: "showAIUsageModal",
code: "showAIUsageModal(): void",
desc:
"Opens a modal dialog showing per-model AI token usage for the current session.<br>" +
"The dialog includes a 'Copy as Markdown' button so the table can be pasted elsewhere.",
after: "",
},
{
field: "formatAIUsageLabel",
code: "formatAIUsageLabel(): string",
desc:
"Returns a compact label string summarising total session token usage.<br>" +
'Format: <code>"AI Usage: 355k/23k"</code> (input tokens / output tokens).<br>' +
'Appends image generation count when present, e.g. <code>"AI Usage: 355k/23k + 3 imgs"</code>.',
after: "",
},
{
field: "extractCodeBlocks",
code: "extractCodeBlocks(markdown: string): { data: string, type: string }[]",
@@ -1206,7 +1245,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "viewZoomToElements",
code: "viewZoomToElements(selectElements: boolean,elements: ExcalidrawElement[]):void",
code: "viewZoomToElements(selectElements: boolean,elements: ExcalidrawElement[], margin: number = 0.05):void",
desc: "Zoom tarteView to fit elements provided as input. elements === [] will zoom to fit the entire scene. SelectElements toggles whether the elements should be in a selected state at the end of the operation.",
after: "",
},
@@ -1241,7 +1280,7 @@ export const EXCALIDRAW_SCRIPTENGINE_INFO: SuggesterInfo[] = [
},
{
field: "suggester",
code: "suggester: (displayItems: string[], items: any[], hint?: string, instructions?:Instruction[]);",
code: "suggester: (displayItems: string[], items: unknown[], hint?: string, instructions?:Instruction[]);",
desc: "Opens a suggester. Displays the displayItems and returns the corresponding item from items[]\nYou need to await the result of suggester.\nIf the user cancels (ESC), suggester will return undefined\nHint and instructions are optional\n\n<code>interface Instruction {command: string;purpose: string;}</code>",
after: "",
},
+5 -3
View File
@@ -14,9 +14,9 @@ export class UIModeSettings extends Modal {
void this.createForm();
}
async onClose() {
onClose() {
if (this.isDirty) {
await this.plugin.saveSettings();
void this.plugin.saveSettings();
}
this.plugin = null;
}
@@ -27,7 +27,9 @@ export class UIModeSettings extends Modal {
this.contentEl,
this.plugin.settings,
this.app,
() => this.applySettingsUpdate(),
() => {
void this.applySettingsUpdate();
},
() => this.close(),
).render();
}
+31 -35
View File
@@ -20,6 +20,7 @@ import { InsertPDFModal } from "./InsertPDFModal";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { cleanSectionHeading } from "src/utils/pathUtils";
import { t } from "src/lang/helpers";
import { hideElement, setStyle, showElement } from "src/utils/styleUtils";
export class UniversalInsertFileModal extends Modal {
private center: { x: number; y: number } = { x: 0, y: 0 };
@@ -33,9 +34,9 @@ export class UniversalInsertFileModal extends Modal {
const appState = view.excalidrawAPI.getAppState();
const containerRect = view.containerEl.getBoundingClientRect();
const viewportWidth =
window.innerWidth || document.documentElement.clientWidth;
window.innerWidth || activeDocument.documentElement.clientWidth;
const viewportHeight =
window.innerHeight || document.documentElement.clientHeight;
window.innerHeight || activeDocument.documentElement.clientHeight;
const curViewport = sceneCoordsToViewportCoords(
{
@@ -117,43 +118,46 @@ export class UniversalInsertFileModal extends Modal {
file,
)
).blocks
.filter((b: any) => b.display && b.node?.type === "heading")
.filter(
(b: any) =>
(b: { display: string; node?: { type: string } }) =>
b.display && b.node?.type === "heading",
)
.filter(
(b: { display: string; node?: { type: string } }) =>
!isExcalidraw || !MD_EX_SECTIONS.includes(b.display),
)
: null;
if (isMarkdown || (isExcalidraw && sections?.length > 0)) {
sectionPickerSetting.settingEl.style.display = "";
sectionPicker.selectEl.style.display = "block";
showElement(sectionPickerSetting.settingEl);
showElement(sectionPicker.selectEl);
while (sectionPicker.selectEl.options.length > 0) {
sectionPicker.selectEl.remove(0);
}
if (!isExcalidraw) {
sectionPicker.addOption("", "");
}
sections.forEach((b: any) => {
sections.forEach((b: { display: string; node?: { type: string } }) => {
sectionPicker.addOption(
`#${cleanSectionHeading(b.display)}`,
b.display,
);
});
} else {
sectionPickerSetting.settingEl.style.display = "none";
sectionPicker.selectEl.style.display = "none";
hideElement(sectionPickerSetting.settingEl);
hideElement(sectionPicker.selectEl);
}
if (isExcalidraw && !isSelf) {
sizeToggleSetting.settingEl.style.display = "";
showElement(sizeToggleSetting.settingEl);
} else {
sizeToggleSetting.settingEl.style.display = "none";
hideElement(sizeToggleSetting.settingEl);
}
if (!isSelf && (isImage || file?.extension === "md")) {
actionImage.buttonEl.style.display = "block";
showElement(actionImage.buttonEl);
} else {
actionImage.buttonEl.style.display = "none";
hideElement(actionImage.buttonEl);
}
if (
@@ -161,15 +165,15 @@ export class UniversalInsertFileModal extends Modal {
isAnimatedImage ||
(isExcalidraw && sections?.length > 0)
) {
actionIFrame.buttonEl.style.display = "block";
showElement(actionIFrame.buttonEl);
} else {
actionIFrame.buttonEl.style.display = "none";
hideElement(actionIFrame.buttonEl);
}
if (isPDF) {
actionPDF.buttonEl.style.display = "block";
showElement(actionPDF.buttonEl);
} else {
actionPDF.buttonEl.style.display = "none";
hideElement(actionPDF.buttonEl);
}
};
@@ -179,11 +183,17 @@ export class UniversalInsertFileModal extends Modal {
this.view.file,
)
).blocks
.filter((b: any) => b.display && b.node?.type === "heading")
.filter((b: any) => !MD_EX_SECTIONS.includes(b.display));
.filter(
(b: { display: string; node?: { type: string } }) =>
b.display && b.node?.type === "heading",
)
.filter(
(b: { display: string; node?: { type: string } }) =>
!MD_EX_SECTIONS.includes(b.display),
);
const search = new TextComponent(ce);
search.inputEl.style.width = "100%";
setStyle(search.inputEl, { width: "100%" });
const suggester = new FileSuggestionModal(
this.app,
search,
@@ -201,7 +211,7 @@ export class UniversalInsertFileModal extends Modal {
.setName(t("UIFM_SECTION_HEAD"))
.addDropdown((dropdown) => {
sectionPicker = dropdown;
sectionPicker.selectEl.style.width = "100%";
setStyle(sectionPicker.selectEl, { width: "100%" });
});
const sizeToggleSetting = new Setting(ce)
@@ -303,20 +313,6 @@ export class UniversalInsertFileModal extends Modal {
return;
}
return;
case "i":
if (isVisible(actionImage)) {
actionImage.buttonEl.click();
}
return;
case "p":
if (isVisible(actionPDF)) {
actionPDF.buttonEl.click();
}
return;
case "f":
if (isVisible(actionIFrame)) {
actionIFrame.buttonEl.click();
}
}
}),
);
+12 -11
View File
@@ -14,8 +14,8 @@ declare const PLUGIN_VERSION: string;
* The user can click ignore to dismiss the dialog.
*/
export class VersionMismatchPrompt extends Modal {
private resolvePromise: (value: any) => void;
public promise: Promise<any>;
private resolvePromise: (value: boolean) => void;
public promise: Promise<boolean>;
private resolved: boolean;
private isDirty: boolean = false;
@@ -23,7 +23,7 @@ export class VersionMismatchPrompt extends Modal {
super(plugin.app);
}
async start(): Promise<any> {
async start(): Promise<boolean> {
this.promise = new Promise((resolve) => {
this.resolvePromise = resolve;
});
@@ -91,21 +91,22 @@ export class VersionMismatchPrompt extends Modal {
});
setElementDisplay(buttonBar, "flex");
buttonBar.style.gap = "0.5rem";
buttonBar.style.marginTop = "1rem";
redownloadBtn.style.backgroundColor = "var(--interactive-accent)";
redownloadBtn.style.color = "var(--text-on-accent)";
buttonBar.addClass("excalidraw-versionmismatch-buttonbar");
redownloadBtn.addClass("mod-cta");
}
async onClose() {
onClose() {
super.onClose();
if (this.isDirty) {
await this.plugin.saveSettings();
void this.plugin.saveSettings();
}
if (!this.resolvePromise) {
return;
}
if (!this.resolved) {
this.resolvePromise && this.resolvePromise(false);
this.resolvePromise(false);
} else {
this.resolvePromise && this.resolvePromise(true);
this.resolvePromise(true);
}
}
}
+11 -17
View File
@@ -1,8 +1,9 @@
import { ExcalidrawTextElement } from "@zsviczian/excalidraw/types/element/src/types";
import { Notice } from "obsidian";
import { t } from "src/lang/helpers";
import { NamedExcalidrawFrameElement } from "src/types/excalidrawElementTypes";
import { ScriptEngine } from "../Scripts";
import ExcalidrawView from "src/view/ExcalidrawView";
import { mainDocument } from "src/constants/constants";
/**
*
@@ -24,10 +25,7 @@ export async function copyLinkToSelectedElementToClipboard(
if (elements.length === 2) {
const textEl = elements.filter((el) => el.type === "text");
if (
textEl.length === 1 &&
(textEl[0] as ExcalidrawTextElement).containerId
) {
if (textEl.length === 1 && textEl[0].containerId) {
const container = elements.filter(
(el) =>
el.boundElements && el.boundElements.some((be) => be.type === "text"),
@@ -45,9 +43,11 @@ export async function copyLinkToSelectedElementToClipboard(
: view.plugin.ea.getLargestElement(elements).id;
}
const frames = elements.filter((el) => el.type === "frame");
const frames = elements.filter(
(el): el is NamedExcalidrawFrameElement => el.type === "frame",
);
const hasFrame = frames.length === 1;
const hasMarkerFrame = hasFrame && (frames[0] as any).frameRole === "marker";
const hasMarkerFrame = hasFrame && frames[0].frameRole === "marker";
const hasGroup = elements.some((el) => el.groupIds && el.groupIds.length > 0);
// Feature 1: UIFM_ANCHOR checkbox (persisted)
@@ -56,7 +56,7 @@ export async function copyLinkToSelectedElementToClipboard(
// Feature 2: frame link by name (persisted)
let copyFrameLinkByName = Boolean(view.plugin.settings.copyFrameLinkByName);
const frameNameRaw = hasFrame ? (frames[0] as any)?.name : undefined;
const frameNameRaw = hasFrame ? frames[0]?.name : undefined;
const frameName = typeof frameNameRaw === "string" ? frameNameRaw.trim() : "";
const frameNameIsValid =
hasFrame && frameName.length > 0 && /[\p{L}\p{N}_ -]+/u.test(frameName);
@@ -169,13 +169,10 @@ export async function copyLinkToSelectedElementToClipboard(
(container: HTMLElement) => {
const wrapper =
container.createDiv?.("excalidraw-prompt-checkboxes") ?? container;
const ownerDoc = wrapper.ownerDocument ?? document;
const ownerDoc = wrapper.ownerDocument ?? mainDocument;
const anchorRow = ownerDoc.createElement("label");
anchorRow.style.display = "flex";
anchorRow.style.alignItems = "center";
anchorRow.style.gap = "8px";
anchorRow.style.marginTop = "8px";
anchorRow.addClass("excalidraw-copylinkprompt-label");
const anchorCb = ownerDoc.createElement("input");
anchorCb.type = "checkbox";
@@ -194,10 +191,7 @@ export async function copyLinkToSelectedElementToClipboard(
if (frameNameIsValid) {
const frameRow = ownerDoc.createElement("label");
frameRow.style.display = "flex";
frameRow.style.alignItems = "center";
frameRow.style.gap = "8px";
frameRow.style.marginTop = "8px";
frameRow.addClass("excalidraw-copylinkprompt-label");
const frameCb = ownerDoc.createElement("input");
frameCb.type = "checkbox";
+121 -59
View File
@@ -6,7 +6,7 @@ import {
FileId,
} from "@zsviczian/excalidraw/types/element/src/types";
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import { App, MarkdownRenderer, Notice, TFile } from "obsidian";
import { App, Component, MarkdownRenderer, Notice, TFile } from "obsidian";
import {
DEFAULT_MD_EMBED_CSS,
fileid,
@@ -15,12 +15,14 @@ import {
THEME_FILTER,
FRONTMATTER_KEYS,
getCSSFontDefinition,
mainDocument,
} from "../constants/constants";
import { createSVG } from "src/utils/excalidrawAutomateUtils";
import { ExcalidrawData, getTransclusion } from "./ExcalidrawData";
import { t } from "../lang/helpers";
import { tex2dataURL } from "./LaTeX";
import ExcalidrawPlugin from "../core/main";
import type { PdfJsDocumentProxy } from "src/types/pdfJsTypes";
import {
blobToBase64,
getDataURLFromURL,
@@ -55,7 +57,7 @@ import {
shouldRenderMermaid,
} from "../utils/mermaidUtils";
import { mermaidToExcalidraw } from "src/constants/constants";
import { ImageKey, imageCache } from "./ImageCache";
import { ImageKey, getImageCache } from "./ImageCache";
import { FILENAMEPARTS, PreviewImageType } from "../types/utilTypes";
import {
ColorMap,
@@ -67,6 +69,12 @@ import {
} from "src/types/embeddedFileLoaderTypes";
import { ExportSettings } from "src/types/exportUtilTypes";
import { setStyleText } from "src/utils/htmlUtils";
import { hideElement, setStyle } from "src/utils/styleUtils";
import {
isInstanceOfHTMLImageElement,
isInstanceOfSVGElement,
} from "src/utils/typechecks";
import { strictArrayBuffer } from "src/utils/obsidianUtils";
//An ugly workaround for the following situation.
//File A is a markdown file that has an embedded Excalidraw file B
@@ -142,7 +150,7 @@ const replaceSVGColors = (
// Modify the fill and stroke attributes of child nodes
const childNodes = (node: ChildNode) => {
if (node instanceof SVGElement) {
if (isInstanceOfSVGElement(node)) {
const oldFill = node.getAttribute("fill")?.toLocaleLowerCase();
const oldStroke = node.getAttribute("stroke")?.toLocaleLowerCase();
@@ -186,6 +194,7 @@ export class EmbeddedFile {
public attemptCounter: number = 0;
public isHyperLink: boolean = false;
public isLocalLink: boolean = false;
public isMarkdownSection: boolean = false;
public hyperlink: DataURL;
public colorMap: ColorMap | null = null;
public pdfPageViewProps: PDFPageViewProps;
@@ -208,7 +217,12 @@ export class EmbeddedFile {
this.colorMap = colorMapJSON
? JSON.parse(colorMapJSON.toLocaleLowerCase())
: null;
} catch (_) {
} catch (error) {
console.log(
`Error parsing colorMap for file ${imgPath}`,
this.constructor,
error,
);
this.colorMap = null;
}
}
@@ -267,6 +281,14 @@ export class EmbeddedFile {
}
} else {
this.filenameparts = getEmbeddedFilenameParts(imgPath);
this.isMarkdownSection =
(this.filenameparts.hasBlockref || this.filenameparts.hasSectionref) &&
!(
this.filenameparts.hasGroupref ||
this.filenameparts.hasArearef ||
this.filenameparts.hasFrameref ||
this.filenameparts.hasClippedFrameref
);
this.filenameparts.filepath = this.file.path;
}
}
@@ -380,18 +402,18 @@ export class EmbeddedFile {
return (
this.isHyperLink ||
this.isLocalLink ||
!Boolean(
!(
this.linkParts &&
this.linkParts.original &&
this.linkParts.original.endsWith("|100%"),
this.linkParts.original.endsWith("|100%")
)
);
}
}
export class EmbeddedFilesLoader {
private pdfDocsMap: Map<string, any> = new Map();
private pdfDocs: Set<any> = new Set();
private pdfDocsMap: Map<string, PdfJsDocumentProxy> = new Map();
private pdfDocs: Set<PdfJsDocumentProxy> = new Set();
private plugin: ExcalidrawPlugin;
private isDark: boolean;
public terminate = false;
@@ -478,7 +500,7 @@ export class EmbeddedFilesLoader {
!hasColorMap &&
this.plugin.settings.allowImageCacheInScene &&
file &&
imageCache.isReady();
getImageCache().isReady();
const hasFilenameParts = Boolean(
inFile instanceof EmbeddedFile && inFile.filenameparts,
);
@@ -513,7 +535,7 @@ export class EmbeddedFilesLoader {
};
const maybeSVG = shouldUseCache
? await imageCache.getImageFromCache(cacheKey, {
? await getImageCache().getImageFromCache(cacheKey, {
skipDependencyCheck: cacheValidation === "stale-first",
})
: undefined;
@@ -568,7 +590,7 @@ export class EmbeddedFilesLoader {
hasSVGwithBitmap = true;
}
if (hasSVGwithBitmap && isDark && !Boolean(maybeSVG)) {
if (hasSVGwithBitmap && isDark && !maybeSVG) {
imageList.forEach((i) => {
const id = i.parentElement?.id;
if (id.endsWith("-invert-bitmap")) {
@@ -586,7 +608,7 @@ export class EmbeddedFilesLoader {
hasSVGwithBitmap = true;
}
if (svgsToInvert.length > 0 && isDark && !Boolean(maybeSVG)) {
if (svgsToInvert.length > 0 && isDark && !maybeSVG) {
svgsToInvert.forEach((i) => {
const id = i.id;
svg.querySelectorAll(`use[href='#${id}']`).forEach((u) => {
@@ -598,10 +620,10 @@ export class EmbeddedFilesLoader {
if (!hasSVGwithBitmap && svg.getAttribute("hasbitmap")) {
hasSVGwithBitmap = true;
}
if (shouldUseCache && !Boolean(maybeSVG)) {
if (shouldUseCache && !maybeSVG) {
//cache SVG should have the width and height parameters and not the embedded font
//see svgWithFont below
imageCache.addImageToCache(cacheKey, "", svg);
getImageCache().addImageToCache(cacheKey, "", svg);
}
if (!svg.hasAttribute("width") && svg.hasAttribute("viewBox")) {
@@ -618,7 +640,7 @@ export class EmbeddedFilesLoader {
}
const dURL = svgToBase64(svg.outerHTML) as DataURL;
return {
dataURL: dURL as DataURL,
dataURL: dURL,
hasSVGwithBitmap,
loadedFromCache: Boolean(maybeSVG),
};
@@ -649,6 +671,8 @@ export class EmbeddedFilesLoader {
inFile instanceof EmbeddedFile ? inFile.isHyperLink : false;
const isLocalLink =
inFile instanceof EmbeddedFile ? inFile.isLocalLink : false;
const isMarkdownSection =
inFile instanceof EmbeddedFile ? inFile.isMarkdownSection : false;
const hyperlink = inFile instanceof EmbeddedFile ? inFile.hyperlink : "";
const file: TFile = inFile instanceof EmbeddedFile ? inFile.file : inFile;
if (file && markdownRendererRecursionWatcthdog.has(file)) {
@@ -674,7 +698,10 @@ export class EmbeddedFilesLoader {
let hasSVGwithBitmap = false;
const isExcalidrawFile =
!isHyperLink && !isLocalLink && this.plugin.isExcalidrawFile(file);
!isMarkdownSection &&
!isHyperLink &&
!isLocalLink &&
this.plugin.isExcalidrawFile(file);
const isPDF =
!isHyperLink && !isLocalLink && file.extension.toLowerCase() === "pdf";
@@ -774,7 +801,7 @@ export class EmbeddedFilesLoader {
mimeType,
fileId: await generateIdFromFile(
isHyperLink || isPDF || isExcalidrawFile
? new TextEncoder().encode(dataURL as string).buffer
? new TextEncoder().encode(dataURL).buffer
: ab,
inFile instanceof EmbeddedFile
? inFile.filenameparts?.linkpartReference
@@ -810,6 +837,9 @@ export class EmbeddedFilesLoader {
addFiles,
depth,
isThemeChange = false,
// the fileIDWhitelist is designed to support partial loading of Excalidraw drawings.
// See getTemplate in excalidrawAutomateUtils. By providing the whitelist loading the scene will skip images
// not on the list (e.g. when rendering an image fragment based on a groupID or frame reference)
fileIDWhiteList,
forceReloadFileIDs,
cacheValidation = "validated",
@@ -832,7 +862,7 @@ export class EmbeddedFilesLoader {
new Notice(t("INFINITE_LOOP_WARNING") + depth.toString(), 6000);
return;
}
const entries = excalidrawData.getFileEntries();
const entries = Array.from(excalidrawData.getFileEntries());
//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";
@@ -853,7 +883,6 @@ export class EmbeddedFilesLoader {
});
}
});
let entry: IteratorResult<[FileId, EmbeddedFile]>;
const files: FileData[][] = [];
files.push([]);
let batch = 0;
@@ -863,12 +892,12 @@ export class EmbeddedFilesLoader {
function* loadIterator(
this: EmbeddedFilesLoader,
): Generator<Promise<void>> {
while (!(entry = entries.next()).done) {
if (fileIDWhiteList && !fileIDWhiteList.has(entry.value[0])) {
for (const entry of entries) {
if (fileIDWhiteList && !fileIDWhiteList.has(entry[0])) {
continue;
}
const embeddedFile: EmbeddedFile = entry.value[1];
const id = entry.value[0];
const embeddedFile: EmbeddedFile = entry[1];
const id = entry[0];
yield createSafeLoadTask(
async () => {
if (this.terminate) {
@@ -1082,7 +1111,7 @@ export class EmbeddedFilesLoader {
errorlog({ where: "EmbeddedFileLoader.loadSceneFiles", error: e });
}
} finally {
clearInterval(addFilesTimer);
window.clearInterval(addFilesTimer);
this.emptyPDFDocsMap();
}
}
@@ -1098,7 +1127,7 @@ export class EmbeddedFilesLoader {
const pageNum = isNaN(linkParts.page) ? 1 : (linkParts.page ?? 1);
const requestedScale = this.plugin.settings.pdfScale;
const shouldUseCache =
imageCache.isReady() &&
getImageCache().isReady() &&
(!options || this.plugin.settings.allowImageCacheInScene);
const cacheKey: ImageKey = {
filepath: file.path,
@@ -1121,7 +1150,7 @@ export class EmbeddedFilesLoader {
inlineFonts: false,
};
const cachedData = shouldUseCache
? await imageCache.getImageCacheData(cacheKey, {
? await getImageCache().getImageCacheData(cacheKey, {
skipDependencyCheck: options?.cacheValidation === "stale-first",
minRenderScale:
options?.cacheValidation === "stale-first"
@@ -1172,8 +1201,12 @@ export class EmbeddedFilesLoader {
cropRect && cropRect.length === 4 && cropRect.every((x) => !isNaN(x));
let viewProps: PDFPageViewProps;
const shouldRetryWithFreshDoc = (e: any): boolean => {
const message = `${e?.message ?? e ?? ""}`;
const shouldRetryWithFreshDoc = (e: unknown): boolean => {
const message = `${
typeof e === "object" && e !== null && "message" in e
? String((e as { message?: unknown }).message ?? "")
: String(e ?? "")
}`;
return (
message.includes("sendWithPromise") ||
message.includes("WorkerTransport") ||
@@ -1306,12 +1339,13 @@ export class EmbeddedFilesLoader {
});
});
const base64 = await blobToBase64(blob);
shouldUseCache &&
imageCache.addImageToCache(cacheKey, "", blob, {
if (shouldUseCache) {
getImageCache().addImageToCache(cacheKey, "", blob, {
renderScale: requestedScale,
size: { width, height },
pdfPageViewProps: viewProps,
});
}
const result: [DataURL, Size, PDFPageViewProps, number, boolean] = [
`data:image/png;base64,${base64}` as DataURL,
{ width, height },
@@ -1364,7 +1398,7 @@ export class EmbeddedFilesLoader {
break;
case "Assistant":
case "Helvetica":
fontDef = await getCSSFontDefinition(2);
fontDef = await getCSSFontDefinition(2); //retruns empty string
break;
case "Excalifont":
fontDef = await getCSSFontDefinition(5);
@@ -1384,16 +1418,14 @@ export class EmbeddedFilesLoader {
case "":
fontDef = "";
break;
default:
default: {
const font = await getFontDataURL(plugin.app, fontName, file.path);
fontDef = font.fontDef;
fontName = font.fontName;
}
}
if (
fileCache?.frontmatter &&
fileCache.frontmatter[FRONTMATTER_KEYS.banner.name] !== null
) {
if (fileCache?.frontmatter && fileCache.frontmatter.banner !== null) {
text = text.replace(/banner:\s*.*/, ""); //patch https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/814
}
@@ -1456,22 +1488,26 @@ export class EmbeddedFilesLoader {
const mdDIV = createDiv();
mdDIV.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
mdDIV.setAttribute("class", "excalidraw-md-host");
// mdDIV.setAttribute("style",style);
if (fontName !== "") {
mdDIV.style.fontFamily = fontName;
setStyle(mdDIV, { fontFamily: fontName });
}
mdDIV.style.overflow = "auto";
mdDIV.style.display = "block";
mdDIV.style.color = fontColor && fontColor !== "" ? fontColor : "initial";
setStyle(mdDIV, {
overflow: "auto",
display: "block",
color: fontColor && fontColor !== "" ? fontColor : "initial",
});
const renderComponent = new Component();
renderComponent.load();
//await MarkdownRenderer.renderMarkdown(text, mdDIV, file.path, plugin);
await MarkdownRenderer.render(
this.plugin.app,
text,
mdDIV,
file.path,
this.plugin,
renderComponent,
);
renderComponent.unload();
mdDIV
.querySelectorAll(":scope > *[class^='frontmatter']")
@@ -1510,8 +1546,8 @@ export class EmbeddedFilesLoader {
//get SVG size.
//First I need to create a fully self contained copy of the document to convert
//blank styles into inline styles using computedStyle
const iframeHost = document.body.createDiv();
iframeHost.style.display = "none";
const iframeHost = mainDocument.body.createDiv();
hideElement(iframeHost);
const iframe = iframeHost.createEl("iframe");
const iframeDoc = iframe.contentWindow.document;
if (style) {
@@ -1530,9 +1566,10 @@ export class EmbeddedFilesLoader {
const elementStyle = el.style;
const computedStyle = window.getComputedStyle(el);
let style = "";
for (const prop in elementStyle) {
if (elementStyle.hasOwnProperty(prop)) {
style += `${prop}: ${computedStyle[prop]};`;
for (const [prop] of Object.entries(elementStyle)) {
if (Object.hasOwn(elementStyle ?? {}, prop)) {
const value = computedStyle.getPropertyValue(prop);
style += `${prop}: ${value};`;
}
}
el.setAttribute("style", style);
@@ -1540,7 +1577,7 @@ export class EmbeddedFilesLoader {
const xmlINiframe = new XMLSerializer().serializeToString(stylingDIV);
const xmlFooter = new XMLSerializer().serializeToString(footerDIV);
document.body.removeChild(iframeHost);
mainDocument.body.removeChild(iframeHost);
//5.2
//get SVG size
@@ -1552,20 +1589,22 @@ export class EmbeddedFilesLoader {
const svgEl = doc.firstElementChild;
const host = createDiv();
host.appendChild(svgEl);
document.body.appendChild(host);
mainDocument.body.appendChild(host);
const footerHeight = svgEl.querySelector(
".excalidraw-md-footer",
).scrollHeight;
const height =
svgEl.querySelector(".excalidraw-md-host").scrollHeight + footerHeight;
const svgHeight = height <= linkParts.height ? height : linkParts.height;
document.body.removeChild(host);
mainDocument.body.removeChild(host);
//finalize SVG
svgStyle = ` width="${linkParts.width}px" height="${svgHeight}px"`;
foreignObjectStyle = ` width="${linkParts.width}px" height="${svgHeight}px"`;
mdDIV.style.height = `${svgHeight - footerHeight}px`;
mdDIV.style.overflow = "hidden";
setStyle(mdDIV, {
height: `${svgHeight - footerHeight}px`,
overflow: "hidden",
});
const imageList = mdDIV.querySelectorAll(
"img:not([src^='data:image/svg+xml'])",
@@ -1575,8 +1614,8 @@ export class EmbeddedFilesLoader {
}
if (hasSVGwithBitmap && this.isDark) {
imageList.forEach((img) => {
if (img instanceof HTMLImageElement) {
img.style.filter = THEME_FILTER;
if (isInstanceOfHTMLImageElement(img)) {
setStyle(img, { filter: THEME_FILTER });
}
});
}
@@ -1633,21 +1672,28 @@ export const generateIdFromFile = async (
// Hash the combined data (file and key, if provided)
// Ensure we pass an ArrayBuffer (not ArrayBufferLike) to subtle.digest
const buffer: ArrayBuffer = dataToHash.buffer.slice(
dataToHash.byteOffset,
dataToHash.byteOffset + dataToHash.byteLength,
) as ArrayBuffer;
const buffer = strictArrayBuffer(
dataToHash.buffer.slice(
dataToHash.byteOffset,
dataToHash.byteOffset + dataToHash.byteLength,
),
);
const hashBuffer = await window.crypto.subtle.digest("SHA-1", buffer);
id = Array.from(new Uint8Array(hashBuffer))
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("") as FileId;
} catch (error) {
errorlog({ where: "EmbeddedFileLoader.generateIdFromFile", error });
errorlog({
where: "EmbeddedFileLoader.generateIdFromFile",
error: error as unknown,
});
id = fileid() as FileId;
}
return id;
};
// This function is for converting blob:app://obsidian.md image URLs (from Obsidian's image cache) to base64 data URLs.
// fetch is used here because requestUrl does not support blob: URLs, and fetch is the only browser API that can read them directly.
const replaceBlobWithBase64 = async (
divElement: HTMLDivElement,
): Promise<void> => {
@@ -1658,11 +1704,27 @@ const replaceBlobWithBase64 = async (
for (const img of images) {
const blobUrl = img.src;
try {
// fetch is the only way to read blob: URLs in browser/Obsidian context.
const response = await fetch(blobUrl);
const blob = await response.blob();
const base64 = await blobToBase64(blob);
img.src = `data:${blob.type};base64,${base64}`;
} catch (error) {
// fallback: use canvas if fetch fails (should be rare)
const canvas = createEl("canvas");
const width = img.naturalWidth || img.width || 0;
const height = img.naturalHeight || img.height || 0;
if (width > 0 && height > 0) {
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
if (ctx) {
ctx.drawImage(img, 0, 0, width, height);
img.src = canvas.toDataURL();
}
canvas.width = 0;
canvas.height = 0;
}
console.error(`Failed to fetch or convert blob: ${blobUrl}`, error);
}
}
+320 -117
View File
@@ -1,17 +1,21 @@
import ExcalidrawPlugin from "src/core/main";
import LZString from "lz-string";
import {
FillStyle,
StrokeStyle,
ExcalidrawElement,
ExcalidrawArrowElement,
ExcalidrawBindableElement,
FileId,
NonDeletedExcalidrawElement,
ExcalidrawImageElement,
ExcalidrawLinearElement,
ExcalidrawTextElement,
StrokeRoundness,
RoundnessType,
ExcalidrawFrameElement,
ExcalidrawTextContainer,
ElementsMap,
} from "@zsviczian/excalidraw/types/element/src/types";
import { ColorMap, MimeType } from "../types/embeddedFileLoaderTypes";
import {
@@ -62,6 +66,7 @@ import {
addAppendUpdateCustomData,
getSVG,
} from "src/utils/utils";
import type { ExcalidrawCustomDataPatch } from "src/utils/elementCustomDataUtils";
import { InlineLinkSuggester } from "./Suggesters/InlineLinkSuggester";
import {
getExcalidrawViews,
@@ -82,7 +87,12 @@ import {
import { EmbeddedFile, EmbeddedFilesLoader } from "./EmbeddedFileLoader";
import { tex2dataURL } from "./LaTeX";
import { NewFileActions } from "src/shared/Dialogs/Prompt";
import { ConnectionPoint, DeviceType, Point } from "src/types/types";
import {
ConnectionPoint,
DeviceType,
ObsidianDraggable,
Point,
} from "src/types/types";
import CM, { ColorMaster, extendPlugins } from "@zsviczian/colormaster";
import HarmonyPlugin from "@zsviczian/colormaster/plugins/harmony";
import MixPlugin from "@zsviczian/colormaster/plugins/mix";
@@ -104,10 +114,7 @@ import {
} from "src/shared/svgToExcalidraw/parser";
import { ROUNDNESS } from "src/constants/constants";
import { ClipboardData } from "@zsviczian/excalidraw/types/excalidraw/clipboard";
import {
emulateKeysForLinkClick,
PaneTarget,
} from "src/utils/modifierkeyHelper";
import { emulateKeysForLinkClick } from "src/utils/modifierkeyHelper";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import PolyBool from "polybooljs";
import { EmbeddableMDCustomProps } from "./Dialogs/EmbeddableSettings";
@@ -122,7 +129,10 @@ import {
maskEditAIImage as _maskEditAIImage,
createAIChatSession as _createAIChatSession,
extractCodeBlocks as _extractCodeBlocks,
getAIUsage as _getAIUsage,
formatAIUsageLabel as _formatAIUsageLabel,
} from "../utils/AIUtils";
import { AIUsageModal } from "./Dialogs/AIUsageModal";
import {
EXCALIDRAW_AUTOMATE_INFO,
EXCALIDRAW_SCRIPTENGINE_INFO,
@@ -165,6 +175,9 @@ import {
updateOrAddSVGColorInfo,
verifyMinimumPluginVersion,
} from "src/utils/excalidrawAutomateUtils";
type MutableElementMapEntry = Mutable<ExcalidrawElement> &
Record<string, unknown>;
import { getLastActiveExcalidrawView } from "src/utils/excalidrawViewLookup";
import {
exportToPDF,
@@ -179,7 +192,7 @@ import {
PDFPageProperties,
ExportSettings,
} from "src/types/exportUtilTypes";
import { FrameRenderingOptions } from "src/types/utilTypes";
import { FrameRenderingOptions, PaneTarget } from "src/types/utilTypes";
import { CaptureUpdateAction } from "src/constants/constants";
import { AutoexportConfig } from "src/types/excalidrawViewTypes";
import { FloatingModal } from "./Dialogs/FloatingModal";
@@ -191,20 +204,9 @@ import { AIRequest, ExcalidrawAISettings } from "src/types/AIUtilTypes";
import { getAspectRatio } from "src/utils/YoutTubeUtils";
import { getPDFCropRect } from "src/utils/PDFUtils";
import { CaptureUpdateActionType } from "@zsviczian/excalidraw/types/element/src";
import { URL_REGISTRY, URLs } from "src/constants/safeUrls";
import { URL_REGISTRY } from "src/constants/safeUrls";
type ExcalidrawCustomDataValue =
| string
| number
| boolean
| null
| ExcalidrawCustomDataValue[]
| { [key: string]: ExcalidrawCustomDataValue };
type ExcalidrawCustomDataPatch = Partial<
Record<string, ExcalidrawCustomDataValue | undefined>
>;
type ExcalidrawAutomateHelpTarget = ((...args: any[]) => any) | string;
type ExcalidrawAutomateHelpTarget = ((...args: unknown[]) => unknown) | string;
extendPlugins([
HarmonyPlugin,
@@ -223,7 +225,6 @@ extendPlugins([
]);
declare const PLUGIN_VERSION: string;
declare var LZString: any;
const GAP = 4;
@@ -341,8 +342,11 @@ export class ExcalidrawAutomate {
.sort((a, b) => a.localeCompare(b))
.forEach((purpose) => {
// Correct: %c turns on styling for the header
console.log(`\n%c${purpose.toUpperCase()}`, "font-weight: bold; font-size: 16px;");
console.log(
`\n%c${purpose.toUpperCase()}`,
"font-weight: bold; font-size: 16px;",
);
grouped[purpose]
.sort((a, b) => a.localeCompare(b))
.forEach((url) => {
@@ -352,7 +356,6 @@ export class ExcalidrawAutomate {
});
}
/**
* Add or modify keys in an element's customData while preserving existing keys.
* Creates customData={} if it does not exist.
@@ -512,6 +515,37 @@ export class ExcalidrawAutomate {
return _createAIChatSession(initialRequest, { plugin: this.plugin });
}
/**
* Returns the accumulated AI token usage for the current Obsidian session.
* Usage is keyed by model identifier and tracks input/output tokens for text
* models and generation counts for image models.
* Data is not persisted and resets when Obsidian is restarted.
*/
public getAIUsage() {
return _getAIUsage();
}
/**
* Opens a modal dialog showing per-model AI token usage for the current session.
* The dialog includes a "Copy as Markdown" button so the table can be pasted elsewhere.
*/
public showAIUsageModal() {
if (!this.plugin?.app) {
return;
}
const usage = _getAIUsage();
new AIUsageModal(this.plugin.app, usage).open();
}
/**
* Returns a compact label string summarising total session token usage.
* Format: "AI Usage: 355k/23k" (input tokens / output tokens).
* Appends image generation count when present, e.g. "+ 3 imgs".
*/
public formatAIUsageLabel() {
return _formatAIUsageLabel();
}
/**
* Extracts code blocks from markdown text.
* @param {string} markdown - The markdown string to parse.
@@ -762,7 +796,7 @@ export class ExcalidrawAutomate {
}
plugin: ExcalidrawPlugin;
elementsDict: { [key: string]: any }; //contains the ExcalidrawElements currently edited in Automate indexed by el.id
elementsDict: { [key: string]: MutableElementMapEntry }; //contains the ExcalidrawElements currently edited in Automate indexed by el.id
imagesDict: { [key: FileId]: ImageInfo }; //the images files including DataURL, indexed by fileId
mostRecentMarkdownSVG: SVGSVGElement = null; //Markdown renderer will drop a copy of the most recent SVG here for debugging purposes
style: {
@@ -783,6 +817,9 @@ export class ExcalidrawAutomate {
startArrowHead: string; //"arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null
endArrowHead: string;
};
setStyle(style: Partial<ExcalidrawAutomate["style"]>) {
Object.assign(this.style, style);
}
canvas: {
theme: string; //"dark"|"light"
viewBackgroundColor: string;
@@ -1027,13 +1064,13 @@ export class ExcalidrawAutomate {
setFillStyle(val: number): "hachure" | "cross-hatch" | "solid" {
switch (val) {
case 0:
this.style.fillStyle = "hachure";
this.setStyle({ fillStyle: "hachure" });
return "hachure";
case 1:
this.style.fillStyle = "cross-hatch";
this.setStyle({ fillStyle: "cross-hatch" });
return "cross-hatch";
default:
this.style.fillStyle = "solid";
this.setStyle({ fillStyle: "solid" });
return "solid";
}
}
@@ -1046,13 +1083,13 @@ export class ExcalidrawAutomate {
setStrokeStyle(val: number): "solid" | "dashed" | "dotted" {
switch (val) {
case 0:
this.style.strokeStyle = "solid";
this.setStyle({ strokeStyle: "solid" });
return "solid";
case 1:
this.style.strokeStyle = "dashed";
this.setStyle({ strokeStyle: "dashed" });
return "dashed";
default:
this.style.strokeStyle = "dotted";
this.setStyle({ strokeStyle: "dotted" });
return "dotted";
}
}
@@ -1065,12 +1102,14 @@ export class ExcalidrawAutomate {
setStrokeSharpness(val: number): "round" | "sharp" {
switch (val) {
case 0:
this.style.roundness = {
type: ROUNDNESS.LEGACY,
};
this.setStyle({
roundness: {
type: ROUNDNESS.LEGACY,
},
});
return "round";
default:
this.style.roundness = null; //sharp
this.setStyle({ roundness: null }); //sharp
return "sharp";
}
}
@@ -1081,7 +1120,7 @@ export class ExcalidrawAutomate {
* @returns {string} The font family string.
*/
setFontFamily(val: number): string {
this.style.fontFamily = val;
this.setStyle({ fontFamily: val });
return getFontFamilyString({ fontFamily: val });
}
@@ -1109,7 +1148,10 @@ export class ExcalidrawAutomate {
addToGroup(objectIds: string[]): string {
const id = nanoid();
objectIds.forEach((objectId) => {
this.elementsDict[objectId]?.groupIds?.push(id);
const groupIds = this.elementsDict[objectId]?.groupIds as
| string[]
| undefined;
groupIds?.push(id);
});
return id;
}
@@ -1163,11 +1205,11 @@ export class ExcalidrawAutomate {
/**
* Extracts the Excalidraw Scene from an Excalidraw File.
* @param {TFile} file - The Excalidraw file to extract the scene from.
* @returns {Promise<{elements: ExcalidrawElement[]; appState: AppState;}>} Promise resolving to the Excalidraw scene.
* @returns {Promise<{elements: ExcalidrawElement[]; appState: Partial<AppState>;}>} Promise resolving to the Excalidraw scene.
*/
async getSceneFromFile(
file: TFile,
): Promise<{ elements: ExcalidrawElement[]; appState: AppState }> {
): Promise<{ elements: ExcalidrawElement[]; appState: Partial<AppState> }> {
if (!file) {
errorMessage("file not found", "getScene()");
return null;
@@ -1193,7 +1235,7 @@ export class ExcalidrawAutomate {
* Gets all elements from ExcalidrawAutomate elementsDict.
* @returns {Mutable<ExcalidrawElement>[]} Array of elements from elementsDict.
*/
getElements(): Mutable<ExcalidrawElement>[] {
getElements(): MutableElementMapEntry[] {
const elements = [];
const elementIds = Object.keys(this.elementsDict);
for (let i = 0; i < elementIds.length; i++) {
@@ -1207,7 +1249,7 @@ export class ExcalidrawAutomate {
* @param {string} id - The element ID to retrieve.
* @returns {Mutable<ExcalidrawElement>} The element with the specified ID.
*/
getElement(id: string): Mutable<ExcalidrawElement> {
getElement(id: string): MutableElementMapEntry {
return this.elementsDict[id];
}
@@ -1254,7 +1296,7 @@ export class ExcalidrawAutomate {
}
if (element.type === "text") {
if (element.id in this.elementsDict) {
return { eaElement: element as Mutable<ExcalidrawTextElement> };
return { eaElement: element };
}
if (searchInView && this.targetView && this.targetView._loaded) {
@@ -1274,34 +1316,30 @@ export class ExcalidrawAutomate {
if (!boundElement) {
return {};
}
const textElement = this.elementsDict[
boundElement.id
] as Mutable<ExcalidrawTextElement>;
if (textElement) {
return { eaElement: textElement };
}
if (
!textElement &&
searchInView &&
this.targetView &&
this.targetView._loaded
) {
if (searchInView && this.targetView && this.targetView._loaded) {
const viewElements = this.getViewElements();
const ve = viewElements.find((e) => e.id === boundElement.id);
return { sceneElement: ve as ExcalidrawTextElement };
if (ve) {
return {
sceneElement: ve as ExcalidrawTextElement,
};
}
}
return {};
}
/**
* Creates a drawing and saves it to the specified filename.
* @param {Object} [params] - Parameters for creating the drawing.
* @param {string} [params.filename] - The filename for the drawing. If null, default filename as defined in Excalidraw settings.
* @param {string} [params.foldername] - The folder name for the drawing. If null, default folder as defined in Excalidraw settings.
* @param {string} [params.templatePath] - The template path to use for the drawing.
* @param {boolean} [params.onNewPane] - Whether to open the drawing in a new pane.
* @param {boolean} [params.silent] - Whether to create the drawing silently.
* @param {Object} [params.frontmatterKeys] - Frontmatter keys to include in the drawing.
* Creates a new Excalidraw drawing file from current EA state and optional template.
* @param params - Optional creation parameters.
* @param {string} [params.plaintext] - Text to insert above the `# Text Elements` section.
* @returns {Promise<string>} Promise resolving to the path of the created drawing.
*/
@@ -1382,12 +1420,14 @@ export class ExcalidrawAutomate {
frontmatter = mergeMarkdownFiles(template.frontmatter, frontmatter);
}
const templateAppstate = template?.appState ?? {};
Object.keys(templateAppstate).forEach((key) => {
if (templateAppstate[key] === undefined) {
delete templateAppstate[key];
}
});
const templateAppstate = Object.fromEntries(
Object.entries(template?.appState ?? {}).filter(
([, value]) => value !== undefined,
),
) as Partial<AppState> & {
currentItemLinearStrokeSharpness?: boolean;
currentItemStrokeSharpness?: boolean;
};
const scene = {
type: "excalidraw",
version: 2,
@@ -1756,7 +1796,7 @@ export class ExcalidrawAutomate {
loader?: EmbeddedFilesLoader,
theme?: string,
padding?: number,
): Promise<any> {
): Promise<Blob> {
if (!theme) {
theme = this.plugin.settings.previewMatchObsidianTheme
? isObsidianThemeDark()
@@ -1879,7 +1919,7 @@ export class ExcalidrawAutomate {
*/
private boxedElement(
id: string,
eltype: any,
eltype: string,
x: number,
y: number,
w: number,
@@ -1912,14 +1952,14 @@ export class ExcalidrawAutomate {
versionNonce: Math.floor(Math.random() * 1000000000),
updated: Date.now(),
isDeleted: false,
groupIds: [] as any,
boundElements: [] as any,
groupIds: [] as string[],
boundElements: [] as { id: string; type: "arrow" | "text" }[],
link,
locked: false,
frameId: null as string,
frameId: null as string | null,
hasTextLink: !!(eltype === "text" && link),
...(scale ? { scale } : {}),
};
} as unknown as Mutable<ExcalidrawElement>;
}
/**
@@ -2209,7 +2249,7 @@ export class ExcalidrawAutomate {
const sx = a / 9;
const sy = b * 0.8;
const step = 6;
const p: any = [];
const p: [number, number][] = [];
const pushPoint = (i: number, dir: number) => {
const x = i + Math.random() * sx - sx / 2;
p.push([
@@ -2229,7 +2269,7 @@ export class ExcalidrawAutomate {
pushPoint(i, -1);
}
p.push(p[0]);
const scale = (p: [[x: number, y: number]]): [[x: number, y: number]] => {
const scale = (p: [x: number, y: number][]): [x: number, y: number][] => {
const box = getLineBox(p);
const scaleX = width / box.w;
const scaleY = height / box.h;
@@ -2327,7 +2367,7 @@ export class ExcalidrawAutomate {
let boxId: string = null;
const strokeColor = this.style.strokeColor;
this.style.strokeColor = formatting?.boxStrokeColor ?? strokeColor;
this.setStyle({ strokeColor: formatting?.boxStrokeColor ?? strokeColor });
const boxPadding = formatting?.boxPadding ?? 30;
if (formatting?.box) {
switch (formatting.box) {
@@ -2364,9 +2404,9 @@ export class ExcalidrawAutomate {
);
}
}
this.style.strokeColor = strokeColor;
this.setStyle({ strokeColor });
const isContainerBound = boxId && formatting.box !== "blob";
this.elementsDict[id] = {
const newTextElement = {
text,
fontSize: this.style.fontSize,
fontFamily: this.style.fontFamily,
@@ -2378,9 +2418,12 @@ export class ExcalidrawAutomate {
containerId: isContainerBound ? boxId : null,
originalText: isContainerBound ? originalText : text,
rawText: isContainerBound ? originalText : text,
lineHeight: getLineHeight(this.style.fontFamily),
lineHeight: getLineHeight(
this.style.fontFamily,
) as Mutable<ExcalidrawTextElement>["lineHeight"],
autoResize: formatting?.box ? true : (formatting?.autoResize ?? true),
};
} as unknown as Mutable<ExcalidrawTextElement>;
this.elementsDict[id] = newTextElement;
if (boxId && formatting?.box === "blob") {
this.addToGroup([id, boxId]);
}
@@ -2389,7 +2432,10 @@ export class ExcalidrawAutomate {
if (!box.boundElements) {
box.boundElements = [];
}
box.boundElements.push({ type: "text", id });
(box.boundElements as { type: "text" | "arrow"; id: string }[]).push({
type: "text",
id,
});
}
const textElement = this.getElement(id) as Mutable<ExcalidrawTextElement>;
const container =
@@ -2399,7 +2445,7 @@ export class ExcalidrawAutomate {
const dimensions = refreshTextDimensions(
textElement,
container,
arrayToMap(this.getElements()),
arrayToMap(this.getElements()) as ElementsMap,
originalText,
);
@@ -2423,10 +2469,10 @@ export class ExcalidrawAutomate {
* @param {string} [id] - The ID of the line element.
* @returns {string} The ID of the added line element.
*/
addLine(points: [[x: number, y: number]], id?: string): string {
addLine(points: [x: number, y: number][], id?: string): string {
const box = getLineBox(points);
id = id ?? nanoid();
this.elementsDict[id] = {
const lineElement = {
points: normalizeLinePoints(points),
lastCommittedPoint: null,
startBinding: null,
@@ -2441,7 +2487,8 @@ export class ExcalidrawAutomate {
box.w,
box.h,
),
};
} as unknown as Mutable<ExcalidrawLinearElement>;
this.elementsDict[id] = lineElement;
return id;
}
@@ -2517,7 +2564,7 @@ export class ExcalidrawAutomate {
) as Mutable<ExcalidrawBindableElement>)
: null;
id = id ?? nanoid();
this.elementsDict[id] = {
const arrowElement = {
points: normalizeLinePoints(points),
elbowed,
lastCommittedPoint: null,
@@ -2535,11 +2582,13 @@ export class ExcalidrawAutomate {
startArrowhead:
typeof formatting?.startArrowHead !== "undefined"
? formatting.startArrowHead
: this.style.startArrowHead,
: (this.style
.startArrowHead as Mutable<ExcalidrawArrowElement>["startArrowhead"]),
endArrowhead:
typeof formatting?.endArrowHead !== "undefined"
? formatting.endArrowHead
: this.style.endArrowHead,
: (this.style
.endArrowHead as Mutable<ExcalidrawArrowElement>["endArrowhead"]),
...this.boxedElement(
id,
"arrow",
@@ -2548,7 +2597,8 @@ export class ExcalidrawAutomate {
box.w,
box.h,
),
};
} as unknown as Mutable<ExcalidrawArrowElement>;
this.elementsDict[id] = arrowElement;
if (startElement) {
if (!startElement.boundElements) {
startElement.boundElements = [];
@@ -2673,7 +2723,7 @@ export class ExcalidrawAutomate {
created: Date.now(),
size: await getImageSize(dataURL),
hasSVGwithBitmap: false,
pdfPageViewProps: null as any,
pdfPageViewProps: null,
}
: await (() => {
const loader = new EmbeddedFilesLoader(
@@ -2808,9 +2858,12 @@ export class ExcalidrawAutomate {
image.size.width * Math.abs(scaleX),
image.size.height * Math.abs(scaleY),
);
this.elementsDict[id].fileId = image.fileId;
const imageElement = this.elementsDict[
id
] as Mutable<ExcalidrawImageElement>;
imageElement.fileId = image.fileId;
this.addAppendUpdateCustomData(id, { latex: tex });
this.elementsDict[id].scale = [Math.sign(scaleX), Math.sign(scaleY)];
imageElement.scale = [Math.sign(scaleX), Math.sign(scaleY)];
return id;
}
@@ -2891,7 +2944,10 @@ export class ExcalidrawAutomate {
const numberOfPoints = formatting?.numberOfPoints
? formatting.numberOfPoints
: 0;
const getSidePoints = (side: string, el: any) => {
const getSidePoints = (
side: string,
el: ExcalidrawElement,
): [number, number] => {
switch (side) {
case "bottom":
return [(el.x + (el.x + el.width)) / 2, el.y + el.height + padding];
@@ -2908,8 +2964,12 @@ export class ExcalidrawAutomate {
let aY;
let bX;
let bY;
const elA = this.elementsDict[objectA];
const elB = this.elementsDict[objectB];
const elA = this.elementsDict[
objectA
] as Mutable<ExcalidrawBindableElement>;
const elB = this.elementsDict[
objectB
] as Mutable<ExcalidrawBindableElement>;
if (!connectionA || !connectionB) {
const aCenterX = elA.x + elA.width / 2;
const bCenterX = elB.x + elB.width / 2;
@@ -2972,7 +3032,9 @@ export class ExcalidrawAutomate {
* @returns {string} The ID of the added text element.
*/
addLabelToLine(lineId: string, label: string): string {
const line = this.elementsDict[lineId];
const line = this.elementsDict[lineId] as
| Mutable<ExcalidrawLinearElement>
| undefined;
if (
!line ||
!["arrow", "line"].includes(line.type) ||
@@ -2996,13 +3058,13 @@ export class ExcalidrawAutomate {
angle -= Math.PI;
//delta = -delta;
}
this.style.angle = angle;
this.setStyle({ angle });
const id = this.addText(
line.x + line.points[1][0] / 2 - size.width / 2, //+delta,
line.y + line.points[1][1] / 2 - size.height, //-5*size.height/6,
label,
);
this.style.angle = 0;
this.setStyle({ angle: 0 });
return id;
}
@@ -3133,7 +3195,7 @@ export class ExcalidrawAutomate {
errorMessage("targetView not set", "getExcalidrawAPI()");
return null;
}
return (this.targetView as ExcalidrawView).excalidrawAPI;
return this.targetView.excalidrawAPI;
}
/**
@@ -3205,9 +3267,9 @@ export class ExcalidrawAutomate {
/**
* Gets the selected element in the view. If more are selected, gets the first.
* @returns {any} The selected element or null if none selected.
* @returns {ExcalidrawElement | null} The selected element or null if none selected.
*/
getViewSelectedElement(): any {
getViewSelectedElement(): ExcalidrawElement | null {
const elements = this.getViewSelectedElements();
return elements ? elements[0] : null;
}
@@ -3215,9 +3277,11 @@ export class ExcalidrawAutomate {
/**
* Gets the selected elements in the view.
* @param {boolean} [includeFrameChildren=true] - Whether to include frame children in the selection.
* @returns {any[]} Array of selected elements.
* @returns {ExcalidrawElement[]} Array of selected elements.
*/
getViewSelectedElements(includeFrameChildren: boolean = true): any[] {
getViewSelectedElements(
includeFrameChildren: boolean = true,
): ExcalidrawElement[] {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "getViewSelectedElements()");
return [];
@@ -3234,6 +3298,22 @@ export class ExcalidrawAutomate {
return getEmbeddedFileForImageElment(this, el)?.file;
}
/**
* Returns the vault or external URI path for an image file identified by its Excalidraw fileId.
*
* Note: Excalidraw does not maintain a persistent index of fileIds to paths.
* The `filesMaster` cache is populated at runtime as images appear in open drawings,
* and is used to support copy/paste of image references between drawings without
* duplicating files. This function will only return a path for images that have
* been seen in a drawing during the current Obsidian session.
*
* @param {FileId} fileId - The Excalidraw fileId of the image.
* @returns {string | null} The vault path of the image file, or null if not cached.
*/
getPathForImageFileId(fileId: FileId): string | null {
return this.plugin.filesMaster?.get(fileId)?.path ?? null;
}
/**
* Gets the color map associated with an image element in the view.
* @param {ExcalidrawElement} el - The image element.
@@ -3391,10 +3471,7 @@ export class ExcalidrawAutomate {
if (!ed.loaded) {
return svgColors;
}
(img
? ed.scene.elements.filter((el: ExcalidrawElement) => el.id === img.id)
: ed.scene.elements
).forEach((el: ExcalidrawElement) => {
ed.scene.elements.forEach((el: ExcalidrawElement) => {
if ("strokeColor" in el) {
updateOrAddSVGColorInfo(svgColors, el.strokeColor, { stroke: true });
}
@@ -3542,7 +3619,7 @@ export class ExcalidrawAutomate {
errorMessage("targetView not set", "viewToggleFullScreen()");
return;
}
const view = this.targetView as ExcalidrawView;
const view = this.targetView;
const isFullscreen = view.isFullscreen();
if (forceViewMode) {
view.updateScene({
@@ -3573,7 +3650,7 @@ export class ExcalidrawAutomate {
errorMessage("targetView not set", "viewToggleFullScreen()");
return;
}
const view = this.targetView as ExcalidrawView;
const view = this.targetView;
view.updateScene({
appState: { viewModeEnabled: enabled },
captureUpdate: CaptureUpdateAction.NEVER,
@@ -3587,8 +3664,8 @@ export class ExcalidrawAutomate {
* @param {ExcalidrawElement[]} [scene.elements] - Array of elements in the scene.
* @param {AppState} [scene.appState] - The app state of the scene.
* @param {BinaryFiles} [scene.files] - The files in the scene.
* @param {boolean} [scene.commitToHistory] - Whether to commit the scene to history. @deprecated Use scene.storageOption instead
* @param {"capture" | "none" | "update"} [scene.storeAction] - The store action for the scene. @deprecated Use scene.storageOption instead
* @param {boolean} [scene.commitToHistory] - Deprecated: Use scene.storageOption instead.
* @param {"capture" | "none" | "update"} [scene.storeAction] - Deprecated: Use scene.storageOption instead
* @param {"IMMEDIATELY" | "NEVER" | "EVENTUALLY"} [scene.captureUpdate] - The capture update action for the scene.
* @param {boolean} [restore=false] - Whether to restore legacy elements in the scene.
*/
@@ -3607,7 +3684,7 @@ export class ExcalidrawAutomate {
errorMessage("targetView not set", "viewToggleFullScreen()");
return;
}
if (!Boolean(scene.storeAction)) {
if (!scene.storeAction) {
scene.storeAction = scene.commitToHistory ? "capture" : "update";
}
@@ -3679,16 +3756,18 @@ export class ExcalidrawAutomate {
* Zooms the target view to fit the specified elements.
* @param {boolean} selectElements - Whether to select the elements after zooming.
* @param {ExcalidrawElement[]} elements - Array of elements to zoom to.
* @param {number} [margin=0.05] - The margin around the elements when zooming.
*/
viewZoomToElements(
selectElements: boolean,
elements: ExcalidrawElement[],
margin: number = 0.05,
): void {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
return;
}
this.targetView.zoomToElements(selectElements, elements);
this.targetView.zoomToElements(selectElements, elements, margin);
}
/**
@@ -3805,7 +3884,7 @@ export class ExcalidrawAutomate {
onDropHook: (data: {
ea: ExcalidrawAutomate;
event: React.DragEvent<HTMLDivElement>;
draggable: any; //Obsidian draggable object
draggable: ObsidianDraggable; //Obsidian draggable object
type: "file" | "text" | "unknown";
payload: {
files: TFile[]; //TFile[] array of dropped files
@@ -4081,7 +4160,7 @@ export class ExcalidrawAutomate {
* @returns {ExcalidrawElement[][]} Array of arrays of grouped elements.
*/
getMaximumGroups(elements: ExcalidrawElement[]): ExcalidrawElement[][] {
return getMaximumGroups(elements, arrayToMap(elements));
return getMaximumGroups(elements, arrayToMap(elements) as ElementsMap);
}
/**
@@ -4095,7 +4174,7 @@ export class ExcalidrawAutomate {
return null;
}
let largestElement = elements[0];
const getSize = (el: ExcalidrawElement): Number => {
const getSize = (el: ExcalidrawElement): number => {
return el.height * el.width;
};
let largetstSize = getSize(elements[0]);
@@ -4245,7 +4324,7 @@ export class ExcalidrawAutomate {
* @param {Object} settings - The script settings to set.
* @returns {Promise<void>} Promise resolving when the settings are saved.
*/
async setScriptSettings(settings: any): Promise<void> {
async setScriptSettings(settings: Record<string, unknown>): Promise<void> {
if (!this.activeScript) {
return null;
}
@@ -4473,20 +4552,140 @@ export class ExcalidrawAutomate {
return newEl;
}
/**
* Clones an array of Excalidraw elements or a clipboard string.
* Ensures that relationships (containers, bound elements, groups, bindings)
* are correctly remapped to the newly generated IDs.
*
* @param {ExcalidrawElement[] | string} elementsOrClipboard - The elements array or Excalidraw clipboard string.
* @returns {ExcalidrawElement[]} An array of cloned elements with new IDs and updated relationships.
*/
cloneElements(
elementsOrClipboard: ExcalidrawElement[] | string,
): ExcalidrawElement[] {
let elements: ExcalidrawElement[] = [];
// 1. Parse the input
if (typeof elementsOrClipboard === "string") {
try {
const parsed = JSON.parse(elementsOrClipboard);
if (
parsed.type === "excalidraw/clipboard" &&
Array.isArray(parsed.elements)
) {
elements = parsed.elements;
} else if (Array.isArray(parsed)) {
elements = parsed;
} else {
throw new Error("Invalid clipboard string format.");
}
} catch (e) {
console.error("Failed to parse Excalidraw clipboard string:", e);
return [];
}
} else if (Array.isArray(elementsOrClipboard)) {
elements = elementsOrClipboard;
} else {
console.error(
"Invalid input. Expected array of elements or clipboard string.",
);
return [];
}
if (!elements || elements.length === 0) {
return [];
}
// 2. Create ID mappings
const idMap = new Map<string, string>();
const groupMap = new Map<string, string>();
// Pre-generate new IDs for elements and groups
elements.forEach((el) => {
idMap.set(el.id, nanoid());
if (el.groupIds && Array.isArray(el.groupIds)) {
el.groupIds.forEach((groupId: string) => {
if (!groupMap.has(groupId)) {
groupMap.set(groupId, nanoid());
}
});
}
});
// 3. Clone and remap relationships
const clonedElements: ExcalidrawElement[] = elements.map((el) => {
// Deep clone the element
const newEl = JSON.parse(JSON.stringify(el));
// Update element ID
newEl.id = idMap.get(el.id)!;
// Remap Group IDs
if (newEl.groupIds && Array.isArray(newEl.groupIds)) {
newEl.groupIds = newEl.groupIds.map(
(groupId: string) => groupMap.get(groupId) || groupId,
);
}
// Remap Container ID (e.g., text inside a rectangle)
if (newEl.containerId && idMap.has(newEl.containerId)) {
newEl.containerId = idMap.get(newEl.containerId);
}
// 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,
id: idMap.get(bound.id) || bound.id, // Fallback to original ID if bound element wasn't cloned
}),
);
}
// Remap Arrow Start Binding
if (newEl.startBinding && idMap.has(newEl.startBinding.elementId)) {
newEl.startBinding = {
...newEl.startBinding,
elementId: idMap.get(newEl.startBinding.elementId),
};
}
// Remap Arrow End Binding
if (newEl.endBinding && idMap.has(newEl.endBinding.elementId)) {
newEl.endBinding = {
...newEl.endBinding,
elementId: idMap.get(newEl.endBinding.elementId),
};
}
// Remap Frame ID
if (newEl.frameId && idMap.has(newEl.frameId)) {
newEl.frameId = idMap.get(newEl.frameId);
}
return newEl;
});
return clonedElements;
}
/**
* Moves the specified element to a specific position in the z-index.
* * Operates directly on the Excalidraw Scene in targetView, not through ExcalidrawAutomate elements.
* @param {number} elementId - The ID of the element to move.
* @param {string} elementId - The ID of the element to move.
* @param {number} newZIndex - The new z-index position for the element.
*/
moveViewElementToZIndex(elementId: number, newZIndex: number): void {
moveViewElementToZIndex(elementId: string, newZIndex: number): void {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "moveViewElementToZIndex()");
return;
}
const API = this.getExcalidrawAPI();
const elements = this.getViewElements() as Mutable<ExcalidrawElement>[];
const elementToMove = elements.filter((el: any) => el.id === elementId);
const elementToMove = elements.filter(
(el: ExcalidrawElement) => el.id === elementId,
);
if (elementToMove.length === 0) {
errorMessage(
`Element (id: ${elementId}) not found`,
@@ -4575,7 +4774,9 @@ export class ExcalidrawAutomate {
getCM(color: TInput): ColorMaster {
if (!color) {
log(
"Creates a CM object. Visit https://github.com/lbragile/ColorMaster for documentation.",
"Creates a CM object. Visit http" +
"s://github." +
"com/lbragile/ColorMaster for documentation.",
);
return;
}
@@ -4653,7 +4854,9 @@ export class ExcalidrawAutomate {
);
return false;
}
this.copyViewElementsToEAforEditing(res.content);
this.copyViewElementsToEAforEditing(
res.content as unknown as ExcalidrawElement[],
);
return true;
}
+145 -68
View File
@@ -40,6 +40,7 @@ import {
import { isObsidianThemeDark } from "../utils/obsidianUtils";
import { cleanBlockRef, cleanSectionHeading } from "../utils/pathUtils";
import {
ElementsMap,
ExcalidrawElement,
ExcalidrawImageElement,
ExcalidrawTextElement,
@@ -65,9 +66,30 @@ import { t } from "../lang/helpers";
import { displayFontMessage } from "../utils/excalidrawViewUtils";
import { getPDFRect } from "../utils/PDFUtils";
import { URLs } from "src/constants/safeUrls";
import { errorlog } from "src/utils/coreUtils";
type SceneDataWithFiles = SceneData & { files: BinaryFiles };
type LegacyGridColor = NonNullable<
NonNullable<SceneData["appState"]>["gridColor"]
> & {
MajorGridFrequency?: number;
};
type ExcalidrawDataScene = SceneDataWithFiles & {
type?: string;
version?: number;
source?: string;
theme?: NonNullable<SceneData["appState"]>["theme"];
prevTextMode?: TextMode;
gridStep?: number;
elements: Mutable<ExcalidrawElement>[];
appState: Mutable<NonNullable<SceneData["appState"]>> & {
previousGridSize?: number | null;
gridColor?: LegacyGridColor;
};
};
type RegExpMatchIteratorResult = IteratorResult<RegExpMatchArray, undefined>;
type MarkdownBlockNode = {
@@ -94,10 +116,6 @@ type MarkdownBlockCacheEntry = {
display: string;
};
type MarkdownBlockCacheResult = {
blocks: MarkdownBlockCacheEntry[];
};
export enum AutoexportPreference {
none,
both,
@@ -252,7 +270,7 @@ export function getJSON(data: string): { scene: string; pos: number } {
if (parts.value && parts.value.length > 1) {
const result = parts.value[2];
return {
scene: result.substr(0, result.lastIndexOf("}") + 1),
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
}
@@ -487,7 +505,7 @@ export class ExcalidrawData {
string,
{ raw: string; parsed: string; hasTextLink: boolean }
> = null;
public scene: any = null;
public scene: ExcalidrawDataScene = null;
public deletedElements: ExcalidrawElement[] = [];
public file: TFile = null;
private app: App;
@@ -552,16 +570,22 @@ export class ExcalidrawData {
URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG,
)[1] ?? "1.8.16";
const elements = this.scene.elements;
const elements = this.scene.elements as Mutable<
ExcalidrawElement & { boundElementIds?: string[] }
>[];
for (const el of elements) {
if (el.type === "iframe" && !el.customData) {
//@ts-ignore -- retyping in ExcalidrawData is possible, this is not the live inmutable object
el.type = "embeddable";
}
if (el.boundElements) {
const map = new Map<string, string>();
const map = new Map<string, "text" | "arrow">();
let alreadyHasText: boolean = false;
el.boundElements.forEach((item: { id: string; type: string }) => {
if (item.type !== "text" && item.type !== "arrow") {
return;
}
if (item.type === "text") {
if (!alreadyHasText) {
map.set(item.id, item.type);
@@ -572,7 +596,9 @@ export class ExcalidrawData {
);
if (elementToClean) {
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1600
elementToClean.containerId = null;
if (elementToClean.type === "text") {
elementToClean.containerId = null;
}
}
}
} else {
@@ -615,27 +641,31 @@ export class ExcalidrawData {
if (el.y === null) {
el.y = 0;
}
/* FixedPointBinding type no longer has focus property. restoreElemenets should take care of this
if (el.startBinding?.focus === null) {
el.startBinding.focus = 0;
}
if (el.endBinding?.focus === null) {
el.endBinding.focus = 0;
}
*/
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/497
if (el.fontSize === null) {
if (el.type === "text" && el.fontSize === null) {
el.fontSize = 20;
}
if (el.type === "text" && !el.hasOwnProperty("autoResize")) {
if (el.type === "text" && !Object.hasOwn(el ?? {}, "autoResize")) {
el.autoResize = true;
}
if (el.type === "text" && !el.hasOwnProperty("lineHeight")) {
el.lineHeight = getLineHeight(el.fontFamily);
if (el.type === "text" && !Object.hasOwn(el ?? {}, "lineHeight")) {
el.lineHeight = getLineHeight(el.fontFamily) as number & {
_brand: "unitlessLineHeight";
};
}
if (el.type === "image" && !el.hasOwnProperty("roundness")) {
if (el.type === "image" && !Object.hasOwn(el ?? {}, "roundness")) {
el.roundness = null;
}
}
@@ -644,15 +674,17 @@ export class ExcalidrawData {
try {
//Fix text elements that point to a container, but the container does not point back
const textElWithOneWayLinkToContainer = elements.filter(
(textEl: any) =>
(
textEl: Mutable<ExcalidrawElement>,
): textEl is Mutable<ExcalidrawTextElement> =>
textEl.type === "text" &&
textEl.containerId &&
elements.some(
(container: any) =>
(container: Mutable<ExcalidrawElement>) =>
container.id === textEl.containerId &&
container.boundElements.length > 0 &&
container.boundElements.some(
(boundEl: any) =>
(boundEl: { id: string; type: string }) =>
boundEl.type === "text" &&
boundEl.id !== textEl.id &&
boundEl.id.length > 8,
@@ -660,23 +692,36 @@ export class ExcalidrawData {
),
);
//if(textElWithOneWayLinkToContainer.length>0) log({message: "cleanup", textElWithOneWayLinkToContainer});
textElWithOneWayLinkToContainer.forEach((textEl: any) => {
try {
const container = elements.filter(
(container: any) => container.id === textEl.containerId,
)[0];
const boundEl = container.boundElements.filter(
(boundEl: any) =>
!(
boundEl.type === "text" &&
!elements.some((el: any) => el.id === boundEl.id)
),
);
container.boundElements = [{ id: textEl.id, type: "text" }].concat(
boundEl,
);
} catch (_) {}
});
textElWithOneWayLinkToContainer.forEach(
(textEl: Mutable<ExcalidrawTextElement>) => {
try {
const container = elements.filter(
(container: Mutable<ExcalidrawElement>) =>
container.id === textEl.containerId,
)[0];
const boundEl = container.boundElements.filter(
(boundEl: { id: string; type: "text" | "arrow" }) =>
!(
boundEl.type === "text" &&
!elements.some(
(el: Mutable<ExcalidrawElement>) => el.id === boundEl.id,
)
),
);
container.boundElements = [
{ id: textEl.id, type: "text" as "text" | "arrow" },
].concat(boundEl);
} catch (e) {
errorlog({
message: "unexpected error in initializeNonInitializedFields",
context: this.initializeNonInitializedFields.bind(
this,
) as unknown,
error: e as unknown,
});
}
},
);
const ellipseAndRhombusContainerWrapping = !isVersionNewerThanOther(
saveVersion,
@@ -685,10 +730,10 @@ export class ExcalidrawData {
//Remove from bound elements references that do not exist in the scene
const containers = elements.filter(
(container: any) =>
(container: Mutable<ExcalidrawElement>) =>
container.boundElements && container.boundElements.length > 0,
);
containers.forEach((container: any) => {
containers.forEach((container: Mutable<ExcalidrawElement>) => {
if (
ellipseAndRhombusContainerWrapping &&
!container.customData?.legacyTextWrap
@@ -696,7 +741,10 @@ export class ExcalidrawData {
addAppendUpdateCustomData(container, { legacyTextWrap: true });
}
const filteredBoundElements = container.boundElements.filter(
(boundEl: any) => elements.some((el: any) => el.id === boundEl.id),
(boundEl: { id: string; type: string }) =>
elements.some(
(el: Mutable<ExcalidrawElement>) => el.id === boundEl.id,
),
);
if (filteredBoundElements.length !== container.boundElements.length) {
//log({message: "cleanup",oldBound: container.boundElements, newBound: filteredBoundElements});
@@ -707,17 +755,22 @@ export class ExcalidrawData {
//Clear the containerId for textElements if the referenced container does not exist in the scene
elements
.filter(
(textEl: any) =>
(
textEl: Mutable<ExcalidrawElement>,
): textEl is Mutable<ExcalidrawTextElement> =>
textEl.type === "text" &&
textEl.containerId &&
!elements.some(
(container: any) => container.id === textEl.containerId,
(container: Mutable<ExcalidrawElement>) =>
container.id === textEl.containerId,
),
)
.forEach((textEl: any) => {
.forEach((textEl: Mutable<ExcalidrawTextElement>) => {
textEl.containerId = null;
}); // log({message:"cleanup",textEl})});
} catch {}
} catch (error) {
console.log(error);
}
}
/**
@@ -801,7 +854,7 @@ export class ExcalidrawData {
//once off migration of legacy scenes
if (
this.scene?.elements?.some(
(el: any) => el.type === "iframe" && !el.customData,
(el: ExcalidrawElement) => el.type === "iframe" && !el.customData,
)
) {
const prompt = new MultiOptionConfirmationPrompt(
@@ -825,12 +878,12 @@ export class ExcalidrawData {
const timer = window.setTimeout(() => {
const notice = new Notice(t("FONT_LOAD_SLOW"), 15000);
notice.noticeEl.oncontextmenu = () => {
notice.messageEl.oncontextmenu = () => {
displayFontMessage(this.app);
};
}, 5000);
await loadSceneFonts(this.scene.elements);
clearTimeout(timer);
window.clearTimeout(timer);
if (!this.scene.files) {
this.scene.files = {}; //loading legacy scenes that do not yet have the files attribute.
@@ -847,7 +900,7 @@ export class ExcalidrawData {
}
//girdSize, gridStep, previousGridSize, gridModeEnabled migration
if (this.scene.appState.hasOwnProperty("previousGridSize")) {
if (Object.hasOwn(this.scene.appState ?? {}, "previousGridSize")) {
//if previousGridSize was present this is legacy data
if (this.scene.appState.gridSize === null) {
this.scene.appState.gridSize = this.scene.appState.previousGridSize;
@@ -858,7 +911,9 @@ export class ExcalidrawData {
delete this.scene.appState.previousGridSize;
}
if (this.scene.appState?.gridColor?.hasOwnProperty("MajorGridFrequency")) {
if (
Object.hasOwn(this.scene.appState?.gridColor ?? {}, "MajorGridFrequency")
) {
//if this is present, this is legacy data
if (this.scene.appState.gridColor.MajorGridFrequency > 1) {
this.scene.gridStep = this.scene.appState.gridColor.MajorGridFrequency;
@@ -953,7 +1008,9 @@ export class ExcalidrawData {
while (!(parts = res.next()).done) {
let text = data.substring(position, parts.value.index);
const id: string = parts.value[1];
const textEl = this.scene.elements.filter((el: any) => el.id === id)[0];
const textEl = this.scene.elements.filter(
(el: ExcalidrawElement) => el.id === id,
)[0];
if (textEl) {
if (textEl.type !== "text") {
//markdown link attached to elements
@@ -999,7 +1056,9 @@ export class ExcalidrawData {
//In theory only non-text elements should be left in the elementLinkMap
//new file format from 2.0.26
for (const [id, link] of elementLinkMap) {
const textEl = this.scene.elements.filter((el: any) => el.id === id)[0];
const textEl = this.scene.elements.filter(
(el: ExcalidrawElement) => el.id === id,
)[0];
if (textEl) {
textEl.link = link;
textEl.version++;
@@ -1132,9 +1191,9 @@ export class ExcalidrawData {
private async updateSceneTextElements() {
//update text in scene based on textElements Map
//first get scene text elements
const elementsMap = arrayToMap(this.scene.elements);
const elementsMap = arrayToMap(this.scene.elements) as ElementsMap;
const texts = this.scene.elements?.filter(
(el: any) => el.type === "text" && !el.isDeleted,
(el: ExcalidrawElement) => el.type === "text" && !el.isDeleted,
) as Mutable<ExcalidrawTextElement>[];
for (const te of texts) {
const container = getContainerElement(te, elementsMap);
@@ -1154,7 +1213,13 @@ export class ExcalidrawData {
te.y = y;
te.width = width;
te.height = height;
} catch (_e) {}
} catch (error) {
console.log(
"error updating text element dimensions, likely due to element being deleted meanwhile",
"updateSceneTextElements",
error,
);
}
}
}
@@ -1181,7 +1246,7 @@ export class ExcalidrawData {
private findNewElementLinksInScene(): boolean {
let result = false;
const elements = this.scene.elements?.filter((el: any) => {
const elements = this.scene.elements?.filter((el: ExcalidrawElement) => {
return el.type !== "text" && el.link && !this.elementLinks.has(el.id);
});
if (elements.length === 0) {
@@ -1216,8 +1281,8 @@ export class ExcalidrawData {
//get scene text elements
this.selectedElementIds = selectedElementIds;
const texts = this.scene.elements?.filter(
(el: any) => el.type === "text",
) as ExcalidrawTextElement[];
(el: ExcalidrawElement) => el.type === "text",
);
let dirty: boolean = false; //to keep track if the json has changed
let id: string; //will be used to hold the new 8 char long ID for textelements that don't yet appear under # Text Elements
@@ -1263,7 +1328,8 @@ export class ExcalidrawData {
for (const key of this.elementLinks.keys()) {
//find element in the scene
const el = this.scene.elements?.filter(
(el: any) => el.type !== "text" && el.id === key && el.link, //&&
(el: ExcalidrawElement) =>
el.type !== "text" && el.id === key && el.link, //&&
);
if (el.length === 0) {
this.elementLinks.delete(key); //if no longer in the scene, delete the text element
@@ -1281,7 +1347,7 @@ export class ExcalidrawData {
for (const key of this.textElements.keys()) {
//find text element in the scene
const el = this.scene.elements?.filter(
(el: any) => el.type === "text" && el.id === key,
(el: ExcalidrawElement) => el.type === "text" && el.id === key,
);
if (el.length === 0) {
this.textElements.delete(key); //if no longer in the scene, delete the text element
@@ -1312,7 +1378,11 @@ export class ExcalidrawData {
});
}
private parseLinks(text: string, position: number, parts: any): string {
private parseLinks(
text: string,
position: number,
parts: RegExpMatchIteratorResult,
): string {
return (
text.substring(position, parts.value.index) +
(this.showLinkBrackets ? "[[" : "") +
@@ -1529,7 +1599,9 @@ export class ExcalidrawData {
const textElementLinks = new Map<string, string>();
for (const key of this.textElements.keys()) {
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/566
const element = this.scene.elements.filter((el: any) => el.id === key);
const element = this.scene.elements.filter(
(el: ExcalidrawElement) => el.id === key,
);
const elementString = this.textElements.get(key).raw;
if (
element &&
@@ -1683,7 +1755,7 @@ export class ExcalidrawData {
isDark: scene.appState?.theme === "dark",
isSVGwithBitmap: mimeType === "image/svg+xml", //this treat all SVGs as if they had embedded images REF:addIMAGE
});
this.setFile(key as FileId, embeddedFile);
this.setFile(key, embeddedFile);
return file;
}
@@ -1806,8 +1878,10 @@ export class ExcalidrawData {
(
scene.elements
.filter((el: ExcalidrawImageElement) => el.fileId === fileId)
.sort((a, b) => (a.updated < b.updated ? 1 : -1))[0] as any
).fileId = newId;
.sort((a, b) =>
a.updated < b.updated ? 1 : -1,
)[0] as Mutable<ExcalidrawImageElement>
).fileId = newId as FileId;
dirty = true;
processedIds.add(newId);
if (embeddedFile) {
@@ -1861,10 +1935,10 @@ export class ExcalidrawData {
}
public async syncElements(
newScene: any,
newScene: SceneDataWithFiles,
selectedElementIds?: { [key: string]: boolean },
): Promise<boolean> {
this.scene = newScene;
this.scene = newScene as ExcalidrawDataScene;
let result = false;
if (!this.compatibilityMode) {
result = await this.syncFiles();
@@ -1882,7 +1956,7 @@ export class ExcalidrawData {
return result || this.findNewTextElementsInScene(selectedElementIds);
}
public async updateScene(newScene: any) {
public async updateScene(newScene: string) {
//console.log("Excalidraw.Data.updateScene()");
this.scene = JSON_parse(newScene);
this.updateElementLinksFromScene();
@@ -2417,14 +2491,17 @@ export const getTransclusion = async (
{ isCancelled: () => false },
file,
)
).blocks.filter((block: any) => block.node.type !== "comment");
).blocks.filter(
(block: MarkdownBlockCacheEntry) => block.node.type !== "comment",
);
if (!blocks) {
return { contents: linkParts.original.trim(), lineNum: 0 };
}
if (linkParts.isBlockRef) {
let para = blocks.filter((block: any) => block.node.id == linkParts.ref)[0]
?.node;
let para = blocks.filter(
(block: MarkdownBlockCacheEntry) => block.node.id === linkParts.ref,
)[0]?.node;
if (!para) {
return { contents: linkParts.original.trim(), lineNum: 0 };
}
@@ -2445,7 +2522,7 @@ export const getTransclusion = async (
}
const headings = blocks.filter(
(block: any) => block.display.search(/^#+\s/) === 0,
(block: MarkdownBlockCacheEntry) => block.display.search(/^#+\s/) === 0,
); // startsWith("#"));
let startPos: number = null;
let lineNum: number = 0;
+36 -97
View File
@@ -1,12 +1,10 @@
import { App, Notice, TFile } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
import { PDFPageViewProps, Size } from "src/types/embeddedFileLoaderTypes";
import { convertSVGStringToElement } from "../utils/utils";
import { convertSVGStringToElement, errorlog } from "../utils/utils";
import { FILENAMEPARTS, PreviewImageType } from "../types/utilTypes";
import { hasExcalidrawEmbeddedImagesTreeChanged } from "../utils/fileUtils";
const DB_NAME = `Excalidraw ${(app as unknown as { appId: string }).appId}`;
const CACHE_STORE = "imageCache";
const BACKUP_STORE = "drawingBAK";
import { EXCALIDRAW_PLUGIN } from "src/constants/constants";
type FileCacheData = {
mtime: number;
@@ -179,7 +177,7 @@ class ImageCache {
await new Promise<void>((resolve, reject) => {
upgradeRequest.onsuccess = () => {
const db = upgradeRequest.result as IDBDatabase;
const db = upgradeRequest.result;
db.close();
resolve();
};
@@ -194,7 +192,7 @@ class ImageCache {
this.db = await new Promise<IDBDatabase>((resolve, reject) => {
const openRequest = indexedDB.open(this.dbName);
openRequest.onsuccess = () => {
const db = openRequest.result as IDBDatabase;
const db = openRequest.result;
resolve(db);
};
openRequest.onerror = () => {
@@ -228,10 +226,7 @@ class ImageCache {
private async purgeInvalidCacheFiles(): Promise<void> {
return new Promise<void>((resolve, reject) => {
const transaction = this.db!.transaction(
this.cacheStoreName,
"readwrite",
);
const transaction = this.db.transaction(this.cacheStoreName, "readwrite");
const store = transaction.objectStore(this.cacheStoreName);
const files = this.app.vault.getFiles();
const deletePromises: Promise<void>[] = [];
@@ -279,21 +274,25 @@ class ImageCache {
transaction.commit();
resolve();
})
.catch((error) => reject(error));
.catch((error) => reject(error as Error));
}
};
request.onerror = () => {
const error = request.error;
console.log(error);
const errorMsg = `Failed to purge invalid files from IndexedDB. Error: ${error.message}`;
errorlog({
where: "purgeInvalideCacheFiles",
error: error,
message: errorMsg,
});
reject(new Error(errorMsg));
};
});
}
private async purgeInvalidBackupFiles(): Promise<void> {
const transaction = this.db!.transaction(this.backupStoreName, "readwrite");
const transaction = this.db.transaction(this.backupStoreName, "readwrite");
const store = transaction.objectStore(this.backupStoreName);
const files = this.app.vault.getFiles();
const deletePromises: Promise<void>[] = [];
@@ -324,14 +323,18 @@ class ImageCache {
transaction.commit();
resolve();
})
.catch((error) => reject(error));
.catch((error) => reject(error as Error));
}
};
request.onerror = () => {
const error = request.error;
const errorMsg = `Failed to purge invalid backup files from IndexedDB. Error: ${error.message}`;
console.log(error);
errorlog({
where: "purgeInvalidBackupFiles",
error: error,
message: errorMsg,
});
reject(new Error(errorMsg));
};
});
@@ -341,7 +344,7 @@ class ImageCache {
mode: IDBTransactionMode,
storeName: string,
): IDBObjectStore {
const transaction = this.db!.transaction(storeName, mode);
const transaction = this.db.transaction(storeName, mode);
return transaction.objectStore(storeName);
}
@@ -405,7 +408,7 @@ class ImageCache {
this.getCacheData(key),
new Promise<undefined>((_, reject) =>
window.setTimeout(() => {
reject(undefined);
reject(new Error("Timeout while retrieving cache data"));
}, 100),
),
]);
@@ -444,7 +447,12 @@ class ImageCache {
}
this.touchCacheData(key, cachedData);
return { cacheData: cachedData, key };
} catch (_) {
} catch (error) {
console.error(
"unexpected error in getResolvedCacheData",
this.getResolvedCacheData.bind(this),
error,
);
return undefined;
}
}
@@ -508,7 +516,7 @@ class ImageCache {
if (image instanceof SVGSVGElement) {
svg = image.outerHTML;
} else {
blob = image as Blob;
blob = image;
}
const now = Date.now();
const data: FileCacheData = {
@@ -522,7 +530,7 @@ class ImageCache {
const store = transaction.objectStore(this.cacheStoreName);
const key = getKey(key_);
store.put(data, key);
if (!Boolean(svg) && obsidianURL) {
if (!svg && obsidianURL) {
if (
this.obsidanURLCache.has(key) &&
this.obsidanURLCache.get(key) !== obsidianURL
@@ -604,83 +612,14 @@ class ImageCache {
}
}
export const imageCache = new ImageCache(DB_NAME, CACHE_STORE, BACKUP_STORE);
let imageCache: ImageCache = null;
/* -------------------------------------------------------- */
/* Legacy cleanup */
// early implementation used localStorage as the image cache,
// which if not cleaned can cause Obsidian performance issues
/* -------------------------------------------------------- */
const LEGACY_LS_PURGE_MARKER = "excalidraw-legacy-ls-purge-v1";
type LegacyKeyShape = {
filepath: unknown;
blockref: unknown;
isDark: unknown;
isSVG: unknown;
scale: unknown;
};
const isObject = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const hasLegacyShape = (value: unknown): value is LegacyKeyShape => {
if (!isObject(value)) {
return false;
export const getImageCache = (): ImageCache => {
if (!imageCache) {
const DB_NAME = `Excalidraw ${EXCALIDRAW_PLUGIN.app.appId}`;
const CACHE_STORE = "imageCache";
const BACKUP_STORE = "drawingBAK";
imageCache = new ImageCache(DB_NAME, CACHE_STORE, BACKUP_STORE);
}
return (
"filepath" in value &&
"blockref" in value &&
"isDark" in value &&
"isSVG" in value &&
"scale" in value
);
return imageCache;
};
export const purgeLegacyLocalStorageImageCache = (): string | null => {
try {
if (typeof window === "undefined" || !window.localStorage) {
return null;
}
if (localStorage.getItem(LEGACY_LS_PURGE_MARKER) === "1") {
return null;
}
const keys = Object.keys(localStorage);
let deleted = 0;
for (const key of keys) {
let parsed: unknown;
try {
parsed = JSON.parse(key);
} catch {
continue;
}
if (!hasLegacyShape(parsed)) {
continue;
}
localStorage.removeItem(key);
deleted += 1;
}
localStorage.setItem(LEGACY_LS_PURGE_MARKER, "1");
if (deleted === 0) {
return null;
}
return `Purged ${deleted} legacy localStorage image cache entr${
deleted === 1 ? "y." : "ies."
}`;
} catch {
return null;
}
};
const report = purgeLegacyLocalStorageImageCache();
if (report) {
console.info(report);
}
+41 -59
View File
@@ -1,56 +1,10 @@
// LaTeX.ts
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import { App } from "obsidian";
import { TFile } from "obsidian";
import ExcalidrawView from "../view/ExcalidrawView";
import { FileData, MimeType } from "src/types/embeddedFileLoaderTypes";
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
import ExcalidrawPlugin from "src/core/main";
type MathJaxData = {
mimeType: MimeType;
fileId: FileId;
dataURL: DataURL;
created: number;
size: { height: number; width: number };
};
type MathJaxContext = App | ExcalidrawPlugin;
type MathJaxModule = {
tex2dataURL: (
tex: string,
scale: number,
pluginOrApp: MathJaxContext,
) => Promise<MathJaxData>;
clearMathJaxVariables: () => void;
};
declare const loadMathjaxToSVG: () => Promise<MathJaxModule>;
let mathjaxLoaded = false;
let tex2dataURLExternal:
| ((
tex: string,
scale: number,
pluginOrApp: MathJaxContext,
) => Promise<MathJaxData>)
| null = null;
let clearVariables: (() => void) | null = null;
let loadMathJaxPromise: Promise<void> | null = null;
const loadMathJax = async () => {
if (!loadMathJaxPromise) {
loadMathJaxPromise = (async () => {
if (!mathjaxLoaded) {
const module = await loadMathjaxToSVG();
tex2dataURLExternal = module.tex2dataURL;
clearVariables = module.clearMathJaxVariables;
mathjaxLoaded = true;
}
})();
}
return loadMathJaxPromise;
};
import type { ExcalidrawExtrasAPI } from "@zsviczian/excalidraw-extras-api";
export const updateEquation = async (
equation: string,
@@ -58,14 +12,14 @@ export const updateEquation = async (
view: ExcalidrawView,
addFiles: (files: FileData[], view: ExcalidrawView) => void,
) => {
await loadMathJax();
const data = await tex2dataURLExternal?.(equation, 4, view.app);
// view.plugin gives us access to the gateway
const data = await tex2dataURL(equation, 4, view.plugin);
if (data) {
const files: FileData[] = [];
files.push({
mimeType: data.mimeType as MimeType,
id: fileId as FileId,
dataURL: data.dataURL as DataURL,
mimeType: data.mimeType,
id: fileId,
dataURL: data.dataURL,
created: data.created,
size: data.size,
hasSVGwithBitmap: false,
@@ -85,13 +39,41 @@ export async function tex2dataURL(
dataURL: DataURL;
created: number;
size: { height: number; width: number };
}> {
await loadMathJax();
return tex2dataURLExternal(tex, scale, plugin);
} | null> {
// 1. Ask the gateway to verify the Extras plugin and return the MathJax API
const mathjaxAPI = await plugin.extrasGateway.getMathJax();
if (!mathjaxAPI) {
// The Gateway handles the user prompts. If it returns null, the user cancelled,
// or they don't have the plugin/proper version. We abort cleanly.
return null;
}
// 2. Resolve Preamble File using cachedRead for performance
let preambleStr: string | null = null;
const preamblePath = plugin.settings.latexPreambleLocation || "preamble.sty";
const preambleFile = plugin.app.vault.getAbstractFileByPath(preamblePath);
if (preambleFile instanceof TFile) {
preambleStr = await plugin.app.vault.cachedRead(preambleFile);
}
// 3. Hand the request off to the cleanly isolated Extras plugin
return (await mathjaxAPI.tex2dataURL(tex, scale, preambleStr)) as {
mimeType: MimeType;
fileId: FileId;
dataURL: DataURL;
created: number;
size: { height: number; width: number };
};
}
export const clearMathJaxVariables = () => {
if (clearVariables) {
clearVariables();
export const clearMathJaxVariables = (plugin: ExcalidrawPlugin) => {
// Try to access without prompting the user.
// If the plugin is disabled, we don't need to clear variables anyway.
const api = plugin.app.plugins.plugins["excalidraw-extras"]
?.api as ExcalidrawExtrasAPI;
if (api?.mathjax) {
api.mathjax.clearMathJaxVariables();
}
};
+6 -16
View File
@@ -11,7 +11,7 @@ import { ExportSettings } from "src/types/exportUtilTypes";
import ExcalidrawView from "src/view/ExcalidrawView";
import { URLs } from "src/constants/safeUrls";
const TASKBONE_URL = URLs.API_TASKBONE_COM;
const TASKBONE_URL = `${URLs.API_TASKBONE_COM}/`;
const TASKBONE_OCR_FN = "execute?id=60f394af-85f6-40bc-9613-5d26dc283cbb";
export default class Taskbone {
@@ -151,27 +151,17 @@ export default class Taskbone {
],
};
const apiResponse = await fetch(url, {
method: "post",
body: JSON.stringify(input),
headers: {
"Content-Type": "application/json",
authorization: `Bearer ${this.apiKey}`,
},
});
const content = await apiResponse?.json();
/*const apiResponse = await requestUrl ({
url: url,
const apiResponse = await requestUrl({
url,
method: "post",
contentType: "application/json",
body: JSON.stringify(input),
headers: {
authorization: `Bearer ${this.apiKey}`
authorization: `Bearer ${this.apiKey}`,
},
throw: false
throw: false,
});
const content = apiResponse?.json;*/
const content = apiResponse?.json;
if (!content || apiResponse.status !== 200) {
new Notice(
Loaded 100 of 163 files, more files were not shown because too many files have changed in this diff. Show more