Compare commits

..
190 Commits
Author SHA1 Message Date
zsviczian b976a5d5e6 2.15.3 2025-09-13 21:31:42 +02:00
zsviczian 9221b8c475 Merge pull request #2480 from playermiller109/2025-09-12
Update zh-cn.ts to 37543c6
2025-09-13 07:19:40 +02:00
playermiller109 6d659042ec Update zh-cn.ts to 37543c6 2025-09-12 20:35:04 +08:00
zsviczian 37543c6a56 2.15.3-beta-2 2025-09-11 20:45:07 +02:00
zsviczian 98f065c8cc Merge pull request #2476 from rlan/feat/zh-tw/2eef8d0
Update zh-tw.ts to 2eef8d0. Generated via OpenCC from zh-cn.ts.
2025-09-11 20:12:21 +02:00
Rick Lan a29d9cb7b1 Update zh-tw.ts to 2eef8d0. Generated via OpenCC. 2025-09-07 20:37:30 -07:00
zsviczian 2eef8d0151 fix back-of-the-note card placement 2025-09-07 20:46:10 +02:00
zsviczian f7676b4102 Merge pull request #2473 from PlayerMiller109/2025-09-05
Update zh-cn.ts: Supplement (2.15.1...2.15.2)
2025-09-07 20:07:43 +02:00
PlayerMiller109 ff6da66f94 Update zh-cn.ts: Supplement (2.15.1...2.15.2) 2025-09-05 21:35:51 +08:00
zsviczian 0f7def145d 2.15.2 2025-09-04 21:15:16 +02:00
zsviczian a6586803de fixes active leaf going blacnk, when DEVICE.isPhone (e.g. Kanban view) 2025-09-04 21:03:55 +02:00
zsviczian 7fe1dc5494 add pdf viewer observer 2025-09-04 20:21:25 +02:00
zsviczian b092a09c3b refactor leaf creation 2025-09-03 23:29:15 +02:00
zsviczian e67ed7ff4f updated handleClick 2025-09-03 22:26:58 +02:00
zsviczian 5ab7311e74 reworked useEffect to switch to preview mode 2025-09-03 22:16:32 +02:00
zsviczian dd05339f73 custom embeddable activate on enter, minor restructuring of CustomEmbeddable.tsx 2025-09-03 22:08:13 +02:00
zsviczian ec23f166ab Merge pull request #2466 from rlan/feat/zh-tw/ccb5590
Update zh-tw.ts to ccb5590
2025-08-31 06:54:33 +02:00
zsviczian 42af86ed9f Merge pull request #2467 from Joakim31/master
Update es.ts to 429c9b0
2025-08-31 06:52:02 +02:00
Joakim31 8b198a5785 Update es.ts to 429c9b0 2025-08-28 23:12:27 -05:00
Rick Lan 739b745e95 Update zh-tw.ts to ccb5590 2025-08-27 20:08:27 -07:00
zsviczian ccb5590f0c 2.15.1 2025-08-25 21:32:11 +02:00
zsviczian 524c33a7e5 2.15.1-beta-3, 0.18.0-37; hide raw mode, pinch zoom PDF on iPad, scroll webpage on mobile, insert LatTex and PDF page image to center 2025-08-25 20:34:19 +02:00
zsviczian 09bb5c5486 2.15.1-beta-2 2025-08-24 19:33:42 +02:00
zsviczian 434f61653d fixed Area link rendering, fixed external video autoplay 2025-08-24 17:45:10 +02:00
zsviczian 613b86e9d0 Merge branch 'master' of https://github.com/zsviczian/obsidian-excalidraw-plugin 2025-08-24 17:23:55 +02:00
zsviczian a6cad5010e Merge pull request #2455 from PlayerMiller109/master
Update zh-cn.ts to 425d830
2025-08-24 17:23:43 +02:00
zsviczian 49cf799f66 pdf stying tweaks. Added snapshot and bookmark, fixed crop, added back-of-the-note card to insert image menu 2025-08-24 15:57:06 +02:00
zsviczian 662737436a carved out setupPdfViewEnhancements to its own function 2025-08-24 12:51:11 +02:00
zsviczian 887651a4bc moved PDF view to node, resolved mobile blackout 2025-08-24 12:31:34 +02:00
PlayerMiller109 c0a40c69a1 Update zh-cn.ts to 425d830 2025-08-24 11:04:34 +08:00
PlayerMiller109 e69676f461 Correct 'ES_FILENAME_VISIBLE': '文件名' to '页内标题'
This option corresponds to Obsidian "Appearance - Show inline title" option.
When enabled in Excalidraw, if "Show inline title" is disabled in Obsidian, it will not be shown.
This differs from Canvas, where the filename floats at the top-left corner of the card.
Important to note this distinction.
2025-08-24 11:04:34 +08:00
PlayerMiller109 9582758483 [squash] Update zh-cn.ts to 89f2a3b 2025-08-24 11:03:50 +08:00
PlayerMiller109 a227c746a2 Unify '查看模式' to follow the upstream default
as it is inherited from upstream (e.g. in the right-click context menu) and cannot be changed by the plugin.
2025-08-23 18:28:55 +08:00
zsviczian 425d8304d5 2.15.1-beta-1, 0.18.0-35 2025-08-23 07:31:42 +02:00
zsviczian 1ee277c814 updated package.json 2025-08-22 21:48:19 +02:00
zsviczian 5a2cbadc9d inverted PDF as image embeds 2025-08-22 15:56:10 +02:00
zsviczian f2d0c8c6b7 escapes aborts active embeddable 2025-08-22 15:22:34 +02:00
zsviczian afecea3e67 pan PDF page in active embeddable 2025-08-22 15:16:11 +02:00
zsviczian a3b6acb0a7 mod-themed observer 2025-08-22 10:43:23 +02:00
zsviczian a7f33f3be0 setPDFViewTheme 2025-08-22 09:36:27 +02:00
zsviczian 0ec5ad1bbb customEmbeddable setColor is now selective based on viewType 2025-08-22 07:55:02 +02:00
zsviczian 89f2a3beb5 PDF fixes, insert audio files, local graph view improvements 2025-08-22 06:55:53 +02:00
zsviczian 88e27a35ef do not save on Excalidraw Error popup 2025-08-17 22:53:01 +02:00
zsviczian ea3103b650 change log 2025-08-17 18:42:12 +02:00
zsviczian 59bbbb907d modified string for new setting 2025-08-17 18:30:02 +02:00
zsviczian 488daf0fde Merge pull request #2450 from mfuria/feature/pan-with-right-mouse-button
Add setting: “Pan with right mouse button (desktop)”; wire to Excalidraw
2025-08-17 18:18:52 +02:00
zsviczian cf6128433d Merge pull request #2454 from PlayerMiller109/master
Update zh-cn.ts to 5bf7271
2025-08-17 18:16:37 +02:00
PlayerMiller109 945afffc11 Update '仓库' 2025-08-17 23:16:28 +08:00
PlayerMiller109 fe322f492e Update strings to 5bf7271 2025-08-17 23:15:55 +08:00
zsviczian 22eee5e37e Merge branch 'master' of https://github.com/zsviczian/obsidian-excalidraw-plugin 2025-08-17 15:09:39 +02:00
zsviczian 5bf7271f86 0.18.0-34 (insert image dropdown + new language strings) 2025-08-17 15:09:36 +02:00
zsviczian 1db4654fe2 Merge pull request #2452 from PlayerMiller109/master
Unify zh-cn.ts translation of 'frame' to '画框' to follow the upstream default
2025-08-17 14:35:10 +02:00
PlayerMiller109 3152ec2c58 [squash] Unify zh-cn.ts to 1bd9a70 2025-08-17 19:40:26 +08:00
zsviczian 1bd9a70635 Merge pull request #2451 from dmscode/zh-2025-08-17
Update zh-cn.ts to a0630b4
2025-08-17 13:16:47 +02:00
dmscode 4a775d81f4 Update zh-cn.ts to a0630b4 2025-08-17 07:33:26 +08:00
zsviczian a0630b4719 fix YT link 2025-08-16 15:24:09 +02:00
zsviczian 37ceca8ccd 2.15.0 2025-08-16 15:08:38 +02:00
mfuria 00acbce5f0 fix(i18n): add missing translations; restore trailing spaces; add //mfuria #329. comments
- Fill missing translation strings.
- Restore intentional trailing spaces per review.
- Add `//mfuria #329.` comments.
- No logic changes.
2025-08-16 12:37:55 +02:00
mfuria ea502134fd bugfix: Removed duplicated setting PAN_WITH_RIGHT_MOUSE_BUTTON_NAME 2025-08-16 08:48:58 +02:00
mfuria 1c5daeafae Add pan with right mouse button setting and update translations 2025-08-16 08:48:58 +02:00
zsviczian 1ca55ccfcb Merge pull request #2449 from dmscode/zh-2025-08-15
Update zh-cn.ts to dab8528
2025-08-15 08:28:10 +02:00
dmscode 24566dfb8c Update zh-cn.ts to dab8528 2025-08-15 05:48:51 +08:00
zsviczian dab8528fb6 revert print layout wizard 2025-08-14 22:43:02 +02:00
zsviczian f4c52ea675 2.15.0-prebeta, 0.18.0-31, marker frames initial implementation 2025-08-14 22:41:46 +02:00
zsviczian 10abb50a5c Merge pull request #2443 from rlan/feat/zh-tw/10fad8a
Update zh-tw.ts to 10fad8a.
2025-08-12 09:46:12 +02:00
Rick Lan 1427b0791a Update zh-tw.ts to 10fad8a. New strings by running zh-cn.ts through OpenCC. Edit code style to match en.ts, such that only string content is different. 2025-08-11 00:32:27 -07:00
zsviczian 10fad8a29c Merge pull request #2442 from Joakim31/master
Update es.ts to 6221d98
2025-08-11 07:39:41 +02:00
Joakim31 429c9b0f55 Update es.ts to 6221d98 2025-08-10 17:12:44 -05:00
zsviczian 38d524db75 added editors picks to index-new 2025-08-10 19:43:38 +02:00
zsviczian f7ef047ebd 2.14.3 2025-08-10 18:59:46 +02:00
zsviczian e167dd21c3 Merge pull request #2437 from dmscode/zh-2025-08-10
Update zh-cn.ts to 691c2fd
2025-08-10 13:44:09 +02:00
zsviczian 8baa3aa0e4 Merge pull request #2436 from rlan/zh-tw-from-dmscode-zh-2025-08-02
Update zh-tw.ts to match merged PR 3e86419
2025-08-10 13:43:57 +02:00
zsviczian 615f66393e updated printeable layout wizard 2025-08-10 08:30:59 +02:00
dmscode c621a96179 Update zh-cn.ts to 691c2fd 2025-08-10 07:06:47 +08:00
Rick Lan 65b88ab67d Run through OpenCC 2025-08-09 14:31:07 -07:00
zsviczian 691c2fdc3e simplifed palm guard 2025-08-09 20:06:42 +02:00
zsviczian 79979d38e4 updated index-new 2025-08-09 19:45:11 +02:00
zsviczian 536479c3d9 updated palmguard script 2025-08-09 17:07:37 +02:00
zsviczian 1065551196 fix palm guard script 2025-08-09 12:37:32 +02:00
zsviczian 3105d5533c 2.14.2 2025-08-09 12:07:28 +02:00
zsviczian 4cff3f013b Update feature-request.yml 2025-08-08 20:23:38 +02:00
zsviczian 4a3e527605 Update bug_report.yml 2025-08-08 20:21:13 +02:00
zsviczian fd592e9325 Update bug_report.yml 2025-08-08 20:20:18 +02:00
zsviczian 7ad928ccdc Update How-to.yml 2025-08-08 20:17:43 +02:00
zsviczian e9f632e4db fix-touch move for Floating Modal 2025-08-07 22:31:23 +02:00
zsviczian 6689d9497c 2.14.1
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-08-05 19:17:20 +02:00
zsviczian 3e86419421 Merge pull request #2431 from dmscode/zh-2025-08-02
Update zh-cn.ts to e574d84
2025-08-05 18:16:52 +02:00
dmscode d2d4f16ebd Update zh-cn.ts to e574d84 2025-08-02 06:48:05 +08:00
zsviczian e574d84b84 2.14.1-beta-2, 0.18.0-27 2025-08-01 20:49:47 +02:00
zsviczian 8f3ace89ea Merge pull request #2427 from dmscode/zh-2025-07-29
Update zh-cn.ts to 41065ce
2025-07-29 18:42:56 +02:00
zsviczian e4e4a07aa8 Merge pull request #2426 from Joakim31/master
Update es.ts to 01b0b64a
2025-07-29 07:49:43 +02:00
dmscode 7a90bf753f Update zh-cn.ts to 41065ce 2025-07-29 13:30:36 +08:00
Joakim31 6221d985ac Update es.ts to 01b0b64a 2025-07-28 20:10:04 -05:00
zsviczian 41065ce9f9 2.14.1-beta-1, 0.18.0-26 2025-07-28 21:48:44 +02:00
zsviczian 351977f0d3 Merge pull request #2421 from mnaoumov/custom-attachment-location
Use internal `app.vault.getAvailablePathForAttachments()`
2025-07-28 19:54:08 +02:00
zsviczian 01b0b64a08 Merge pull request #2425 from Joakim31/master
Add Spanish translation
2025-07-28 19:37:38 +02:00
Joakim31 938e93cc43 Add Spanish translation 2025-07-27 22:56:57 -05:00
Michael Naumov cebcd2b43c Use internal getAvailablePathForAttachments
Fixes https://github.com/RainCat1998/obsidian-custom-attachment-location/issues/179
2025-07-23 22:42:02 -06:00
zsviczian 80b6e30040 shade master help converted to Markdown
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-07-23 22:33:40 +02:00
zsviczian 6e92a6a399 fixed svg 2025-07-23 20:25:41 +02:00
zsviczian 992ae8b238 update index 2025-07-23 20:23:23 +02:00
zsviczian 5cd07e7766 update index 2025-07-23 20:22:29 +02:00
zsviczian 07817a4d2d publish script 2025-07-23 20:18:29 +02:00
zsviczian a22bb4c58c images 2025-07-23 19:56:37 +02:00
zsviczian 43e00a51be images 2025-07-23 19:55:01 +02:00
zsviczian 049b5bfa85 2.14.0 2025-07-22 08:45:29 +02:00
zsviczian 743afa73b4 Merge pull request #2413 from rlan/master
Add Taiwan-idiomatic Traditional Chinese
2025-07-22 08:17:25 +02:00
zsviczian 6469eec051 added NotebookLM link 2025-07-22 06:25:12 +02:00
zsviczian 9f46821a41 Merge pull request #2412 from dmscode/zh-2025-07-20
Update zh-cn.ts to 207fea3
2025-07-21 10:07:01 +02:00
dmscode 1fb3a47bdc Update zh-cn.ts to 207fea3 2025-07-21 14:08:59 +08:00
稻米鼠 bcd0cdda65 Merge pull request #1 from PlayerMiller109/zh-2025-07-20
Supplement (2.13.0...2.13.1)
2025-07-21 13:56:57 +08:00
zsviczian 207fea3f57 ContentSearcher.ts, added to ScriptInstallPrompt.ts and Settings.ts 2025-07-20 21:07:03 +02:00
Rick Lan e55ba3cc21 Add Taiwan-idiomatic Traditional Chinese 2025-07-20 20:54:04 +09:00
PlayerMiller109 71c87a7630 Supplement (2.13.0...2.13.1) 2025-07-20 10:31:38 +08:00
dmscode e598a91f43 Update zh-cn.ts to 972fe1b 2025-07-20 06:09:52 +08:00
zsviczian 972fe1baea copy settings to the clipboard
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-07-19 18:43:01 +02:00
zsviczian d7e1268afa updated info links in settings 2025-07-19 17:45:05 +02:00
zsviczian 7a3b937ea7 Merge pull request #2411 from dmscode/zh-2025-07-19
Fixed for issue 2175
2025-07-19 08:17:27 +02:00
dmscode c850cd15ae Fixed for issue 2175 2025-07-19 10:02:10 +08:00
zsviczian e9f70fd09e 2.13.2 2025-07-16 19:12:09 +02:00
zsviczian 2083443dfe Merge pull request #2408 from duianto/patch-1
Fix typos
2025-07-16 19:03:47 +02:00
zsviczian 69d9b8c1c9 Merge pull request #2407 from dmscode/zh-2025-07-13
Update zh-cn.ts to 6434a6e
2025-07-16 19:02:14 +02:00
duianto 65f4c9f3b3 Fix typos 2025-07-15 10:30:02 +02:00
dmscode b89a106523 Update zh-cn.ts to 6434a6e 2025-07-13 07:59:32 +08:00
zsviczian 6434a6e58a 2.13.1
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-07-12 17:55:44 +02:00
zsviczian 68180db2aa 2.13.0, 0.18.0-25
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-07-01 20:49:40 +02:00
zsviczian 63505d17e9 MultiOptionConfirmationPrompt 2025-07-01 18:02:50 +00:00
zsviczian 0851b45977 Merge pull request #2397 from dmscode/zh-2025-06-30
CodeQL / Analyze (javascript) (push) Has been cancelled
Update zh-cn.ts to 8240d87
2025-06-30 18:54:54 +02:00
dmscode 16332a3e83 Update zh-cn.ts to 8240d87 2025-06-30 14:07:31 +08:00
zsviczian 8240d87fa8 2.13.0 code, but not yet released. Manifest version not updated
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-06-29 22:56:02 +02:00
zsviczian a7db044715 Merge pull request #2378 from zsviczian/dependabot/npm_and_yarn/master/multi-2bdc9b2f63
CodeQL / Analyze (javascript) (push) Has been cancelled
Bump chroma-js and @types/chroma-js
2025-06-24 21:10:45 +02:00
dependabot[bot] 339c274f1b Bump chroma-js and @types/chroma-js
Bumps [chroma-js](https://github.com/gka/chroma.js) and [@types/chroma-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/chroma-js). These dependencies needed to be updated together.

Updates `chroma-js` from 2.6.0 to 3.1.2
- [Release notes](https://github.com/gka/chroma.js/releases)
- [Changelog](https://github.com/gka/chroma.js/blob/main/CHANGELOG.md)
- [Commits](https://github.com/gka/chroma.js/compare/v2.6.0...v3.1.2)

Updates `@types/chroma-js` from 2.4.5 to 3.1.1
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/chroma-js)

---
updated-dependencies:
- dependency-name: chroma-js
  dependency-version: 3.1.2
  dependency-type: direct:production
  update-type: version-update:semver-major
- dependency-name: "@types/chroma-js"
  dependency-version: 3.1.1
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-06-23 20:14:35 +00:00
zsviczian d5a19cbc09 Merge branch 'master' of https://github.com/zsviczian/obsidian-excalidraw-plugin
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-06-23 22:13:16 +02:00
zsviczian 400cffcd01 fix hover preview, bump excalidraw to 0.18.0-24 2025-06-23 22:13:13 +02:00
zsviczian e5438c1e56 fixed determineFocusDistance function signature preventing ExcaliBrain from rendering
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-06-16 11:52:12 +00:00
zsviczian 7e2ef3f115 Merge pull request #2383 from dmscode/zh-2025-06-16
Update zh-cn.ts to 32d0301
2025-06-16 11:06:54 +02:00
dmscode ad091df4d9 Update zh-cn.ts to 32d0301 2025-06-16 06:52:20 +08:00
dmscode 0837c017a1 Update zh-cn.ts to 32d0301 2025-06-15 06:48:05 +08:00
zsviczian 32d0301366 2.12.3, 0.18.0-23 2025-06-14 23:36:37 +02:00
zsviczian 5accd657d9 npm version, fix gpt-4-vision 2025-06-12 19:19:14 +00:00
zsviczian 8da97a63e0 Update bug_report.yml 2025-06-04 21:26:22 +02:00
zsviczian a5d7731533 localgraph loadFile does not exist if localGraph is not yet visible (leaf not loaded) 2025-05-30 08:18:47 +02:00
zsviczian acb83fd697 2.12.2 0.18.0-18
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-05-28 07:22:11 +00:00
zsviczian 271f21f85a 0.18.0-18 2025-05-28 06:30:26 +02:00
zsviczian 371fb54787 2.12.1, 0.18.0-18
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-05-26 22:50:40 +02:00
zsviczian 3f19f9771a updated boolean operations 2025-05-26 18:57:20 +02:00
zsviczian 5a8596d113 Merge pull request #2359 from zsviczian/move-input
CodeQL / Analyze (javascript) (push) Has been cancelled
feat: Implement draggable inputPrompt
2025-05-26 17:52:24 +02:00
zsviczian 6edd8b9a4e Implement draggable inputPrompt 2025-05-26 15:51:34 +00:00
zsviczian 778346b0dd Merge pull request #2358 from dmscode/zh-language-update/2025-05-26
Update zh-cn.ts to ff404e4
2025-05-26 11:36:06 +02:00
dmscode 85ac633263 Update zh-cn.ts to ff404e4 2025-05-26 05:56:02 +08:00
zsviczian ff404e4dd6 text to path minor changes
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-05-25 23:01:00 +02:00
zsviczian d0845a7d68 text to path updated 2025-05-25 22:56:20 +02:00
zsviczian 954eaefe29 2.12.0, 0.18.0-17 2025-05-25 22:00:12 +02:00
zsviczian 175b202a6f text to path 2025-05-25 19:51:17 +02:00
zsviczian b77b4df56d text to path 2025-05-25 19:24:20 +02:00
zsviczian dd7abe2547 0.18.0-17 - Text to Path 2025-05-25 19:18:00 +02:00
zsviczian cac27fb936 test script update alert 2025-05-25 18:09:49 +02:00
zsviczian d9aef84e13 Merge pull request #2353 from dmscode/zh-2025-05-20
CodeQL / Analyze (javascript) (push) Has been cancelled
Update zh-cn.ts to 6824a1a
2025-05-21 07:56:09 +02:00
dmscode c6a81bef24 Update zh-cn.ts to 6824a1a 2025-05-20 13:28:52 +08:00
zsviczian 6824a1aa68 2.12.0-beta-2
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-05-18 18:49:02 +02:00
zsviczian 00de9d639b 2.12.0-beta-1
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-05-17 10:01:17 +02:00
zsviczian 5a66c78428 2.11.2-beta, 0.18.0-15
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-05-11 18:23:24 +02:00
zsviczian d1be193125 2.11.1, 0.18.0-14
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-05-08 22:26:13 +02:00
zsviczian f4c8d21a33 screenshot fix 2025-05-08 18:03:53 +02:00
zsviczian d588f749d2 Merge pull request #2337 from dmscode/zh-2b38c03
CodeQL / Analyze (javascript) (push) Has been cancelled
Update zh-cn.ts to 2b38c03
2025-05-04 17:27:01 +02:00
dmscode c1f909427b Update zh-cn.ts to 2b38c03 2025-05-04 06:45:50 +08:00
zsviczian 2b38c03840 2.11.0, 0.18.0-13
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-05-03 13:48:57 +02:00
zsviczian 8cca77dcab updated prompt styling 2025-05-03 13:28:50 +02:00
zsviczian 5b341cb5fb minor updates to inputPrompt 2025-05-03 11:07:46 +02:00
zsviczian 526299e41f utils.ts minor change
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-05-02 16:40:30 +02:00
zsviczian ae82bce4da Merge pull request #2334 from dmscode/master
CodeQL / Analyze (javascript) (push) Has been cancelled
Update zh-cn.ts to aa4fbe1
2025-04-29 13:10:14 +02:00
dmscode 499ca87759 Update zh-cn.ts to aa4fbe1 2025-04-28 18:11:38 +08:00
zsviczian aa4fbe1f6c restrict screenshot to main workspace
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-04-28 07:33:53 +02:00
zsviczian 05b72f9f07 Merge pull request #2333 from dmscode/master
Update zh-cn.ts to bd9721f
2025-04-28 07:19:13 +02:00
dmscode 53ffa50b15 Update zh-cn.ts to bd9721f 2025-04-28 07:31:56 +08:00
zsviczian bd9721f308 2.11.0-beta-1, 0.18.0-12 : added screenshot feature
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-04-27 16:50:22 +02:00
zsviczian 875bd4cb35 Merge pull request #2332 from dmscode/master
Update zh-cn.ts to 4a803f4
2025-04-27 16:29:49 +02:00
zsviczian ec575c307a updated type references matching Excalidraw component updates
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-04-27 11:05:38 +02:00
dmscode 05087874e2 Update zh-cn.ts to 4a803f4 2025-04-26 17:45:11 +08:00
zsviczian 4a803f4b46 PDF export: HD Screen and Martch Image + disable double click text create
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-04-26 08:13:06 +02:00
zsviczian a48222022e Merge pull request #2328 from dmscode/master
CodeQL / Analyze (javascript) (push) Has been cancelled
Update zh-cn.ts to 4840470
2025-04-20 12:19:49 +02:00
稻米鼠 eebbde1c40 Merge branch 'zsviczian:master' into master 2025-04-20 18:12:27 +08:00
dmscode c0a7686338 Update zh-cn.ts to 4840470 2025-04-20 18:11:07 +08:00
zsviczian 4840470b60 Fix dimensions undefined 2025-04-20 11:40:24 +02:00
zsviczian 091d9b9669 updated authorURL 2025-04-20 10:09:32 +02:00
zsviczian d5b86289b6 Merge branch 'master' of https://github.com/zsviczian/obsidian-excalidraw-plugin 2025-04-20 10:02:54 +02:00
zsviczian dceb6ce690 2.10.2-beta-1 0.18.0-8 2025-04-20 10:02:42 +02:00
zsviczian c29c25d252 Merge pull request #2323 from dmscode/master
CodeQL / Analyze (javascript) (push) Has been cancelled
Update zh-cn.ts to 6e57d4e
2025-04-18 15:39:03 +02:00
dmscode a2fb36671d Update zh-cn.ts to 6e57d4e 2025-04-17 06:56:13 +08:00
zsviczian 6e57d4e69a 2.10.1 0.18.0-7
CodeQL / Analyze (javascript) (push) Has been cancelled
2025-04-16 20:33:48 +02:00
107 changed files with 13541 additions and 3698 deletions

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
{
"name": "Node.js 20",
"image": "mcr.microsoft.com/devcontainers/javascript-node:20",
"features": {
"ghcr.io/devcontainers/features/node:1": {
"version": "20"
}
},
"postCreateCommand": "npm install",
"customizations": {
"vscode": {
"extensions": [
"ms-vscode.vscode-typescript-next"
]
}
}
}
+4 -4
View File
@@ -10,10 +10,10 @@ body:
I am a one-person team working on this plugin as a part-time hobby. Please help me manage the workload by following these guidelines. **Support requests that don't include enough details may be closed without review**.
Before submitting a support request, please:
1. **Review the [documentation](https://github.com/zsviczian/obsidian-excalidraw-plugin/wiki)** – your question may already be answered.
2. **[Search issues](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues) (including closed ones)** to see if your question has already been addressed.
3. **[Watch the Feature Walkthrough Video](https://youtu.be/P_Q6avJGoWI)**: As it infact answers 90% of the typical questions I receive
4. **[Consult NotebookLM with your question](https://excalidraw-obsidian.online/WIKI/09+Video+Transcripts/Videos/Turn+any+YouTube+Channel+into+your+AI+Mentor+-+Obsidian+is+the+ultimate+automation+workbench+for+PKM)**
1. **[Consult NotebookLM with your question](https://notebooklm.google.com/notebook/42d76a2f-c11d-4002-9286-1683c43d0ab0)**
2. **Review the [documentation](https://github.com/zsviczian/obsidian-excalidraw-plugin/wiki)** – your question may already be answered.
3. **[Search issues](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues) (including closed ones)** to see if your question has already been addressed.
4. **[Watch the Feature Walkthrough Video](https://youtu.be/P_Q6avJGoWI)**: As it infact answers 90% of the typical questions I receive
- type: markdown
attributes:
+3 -3
View File
@@ -11,9 +11,9 @@ body:
Before creating a bug report, please:
1. **Review recent [release notes](https://github.com/zsviczian/obsidian-excalidraw-plugin/releases)** – maybe there is already an answer.
2. **[Search issues](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues) (including closed ones)** to see if there is anything similar.
3. **[Watch the Feature Walkthrough Video](https://youtu.be/P_Q6avJGoWI)**: As it infact answers 90% of the typical questions I receive
4. **[Consult NotebookLM with your question](https://excalidraw-obsidian.online/WIKI/09+Video+Transcripts/Videos/Turn+any+YouTube+Channel+into+your+AI+Mentor+-+Obsidian+is+the+ultimate+automation+workbench+for+PKM)**
2. **[Consult NotebookLM with your question](https://notebooklm.google.com/notebook/42d76a2f-c11d-4002-9286-1683c43d0ab0)**
3. **[Search issues](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues) (including closed ones)** to see if there is anything similar.
4. **[Watch the Feature Walkthrough Video](https://youtu.be/P_Q6avJGoWI)**: As it infact answers 90% of the typical questions I receive
- type: markdown
attributes:
@@ -7,6 +7,8 @@ body:
value: |
🛠️ **Important: Please Read Before Submitting a Feature Request** 🛠️
Before you go further, please chat with [NotebookLM](https://notebooklm.google.com/notebook/42d76a2f-c11d-4002-9286-1683c43d0ab0), it may very well be that the feature you are looking for is already there, or you can find a suitable workaround.
I develop Excalidraw primarily as a hobby, and I prioritize features that I personally use regularly. Features I don't use often break without me noticing, which is why the plugin is as stable as it is—because I rely on it every day.
**Your task isn't just to describe the feature you want, but to sell me on the idea**. If I'm not convinced that the feature would significantly benefit my own workflow, it's unlikely I'll spend my free hobby time on it.
+7
View File
@@ -0,0 +1,7 @@
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
target-branch: "master"
+3
View File
@@ -21,3 +21,6 @@ yarn.lock
.DS_Store
.lock
.lock
# Obsidian files
Obsidian
+1 -1
View File
@@ -1 +1 @@
18
20
+2
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, please read my blog post [here](https://www.zsolt.blog/2021/03/showcasing-excalidraw.html) and/or watch the videos below.
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). If you are curious about the Visual PKM philosophy behind the plugin, consider my book [Sketch Your Mind](https://sketch-your-mind.com/) and the [Visual Thinking Workshops](https://visual-thinking-workshop.com/). Finally, keep the [Excalidraw Plugin Wiki](https://excalidraw-obsidian.online/) at hand—it is an essential companion.
## Video Walkthrough
<a href="https://youtu.be/P_Q6avJGoWI" target="_blank"><img src="https://github.com/zsviczian/obsidian-excalidraw-plugin/assets/14358394/da34bb33-7610-45e6-b36f-cb7a02a9141b" width="300"/></a>
<a href="https://youtu.be/o0exK-xFP3k" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/156931370-aa4d88de-c4a8-46cc-aeb2-dc09aa0bea39.jpg" width="300"/></a>
+2 -2
View File
@@ -1,5 +1,5 @@
import ExcalidrawPlugin from "src/core/main";
import { FillStyle, StrokeStyle, ExcalidrawElement, ExcalidrawBindableElement, FileId, NonDeletedExcalidrawElement, ExcalidrawImageElement, StrokeRoundness, RoundnessType } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { FillStyle, StrokeStyle, ExcalidrawElement, ExcalidrawBindableElement, FileId, NonDeletedExcalidrawElement, ExcalidrawImageElement, StrokeRoundness, RoundnessType } from "@zsviczian/excalidraw/types/element/src/types";
import { ColorMap, MimeType } from "./EmbeddedFileLoader";
import { Editor, OpenViewState, RequestUrlResponse, TFile, TFolder, WorkspaceLeaf } from "obsidian";
import * as obsidian_module from "obsidian";
@@ -11,7 +11,7 @@ import { ColorMaster } from "@zsviczian/colormaster";
import { TInput } from "@zsviczian/colormaster/types";
import { ClipboardData } from "@zsviczian/excalidraw/types/excalidraw/clipboard";
import { PaneTarget } from "src/utils/modifierkeyHelper";
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { EmbeddableMDCustomProps } from "./Dialogs/EmbeddableSettings";
import { AIRequest } from "../utils/AIUtils";
import { AddImageOptions, ImageInfo, SVGColorInfo } from "src/types/excalidrawAutomateTypes";
+2 -2
View File
@@ -1,5 +1,5 @@
import ExcalidrawPlugin from "src/core/main";
import { FillStyle, StrokeStyle, ExcalidrawElement, ExcalidrawBindableElement, FileId, NonDeletedExcalidrawElement, ExcalidrawImageElement, StrokeRoundness, RoundnessType } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { FillStyle, StrokeStyle, ExcalidrawElement, ExcalidrawBindableElement, FileId, NonDeletedExcalidrawElement, ExcalidrawImageElement, StrokeRoundness, RoundnessType } from "@zsviczian/excalidraw/types/element/src/types";
import { ColorMap, MimeType } from "./EmbeddedFileLoader";
import { Editor, OpenViewState, RequestUrlResponse, TFile, TFolder, WorkspaceLeaf } from "obsidian";
import * as obsidian_module from "obsidian";
@@ -11,7 +11,7 @@ import { ColorMaster } from "@zsviczian/colormaster";
import { TInput } from "@zsviczian/colormaster/types";
import { ClipboardData } from "@zsviczian/excalidraw/types/excalidraw/clipboard";
import { PaneTarget } from "src/utils/modifierkeyHelper";
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { EmbeddableMDCustomProps } from "./Dialogs/EmbeddableSettings";
import { AIRequest } from "../utils/AIUtils";
import { AddImageOptions, ImageInfo, SVGColorInfo } from "src/types/excalidrawAutomateTypes";
+8 -3
View File
@@ -23,8 +23,8 @@ const elements = ea.getViewSelectedElements().filter(
el.groupIds.some(id => id.startsWith(ShadowGroupMarker)) ||
(["line", "arrow"].includes(el.type) && el.roundness === null)
);
if(elements.length === 0) {
new Notice ("Select ellipses, rectangles or diamonds");
if(elements.length < 2) {
new Notice ("Select ellipses, rectangles, diamonds; or lines and arrows with sharp edges");
return;
}
@@ -69,10 +69,15 @@ const result = polyboolAction({
const polygonHierachy = subordinateInnerPolygons(result.regions);
drawPolygonHierachy(polygonHierachy);
ea.deleteViewElements(elements);
setPolygonTrue();
ea.addElementsToView(false,false,true);
return;
function setPolygonTrue() {
ea.getElements().filter(el=>el.type==="line").forEach(el => {
el.polygon = true;
});
}
function traceElement(element) {
const diamondPath = (diamond) => [
+204
View File
@@ -0,0 +1,204 @@
/*
Palm Guard: A mobile-friendly drawing mode for Excalidraw that prevents accidental palm touches by hiding UI controls and entering fullscreen mode. Perfect for drawing with a stylus on tablets.
Features:
- Enters fullscreen to maximize drawing space (configurable in plugin script settings)
- Hides all UI controls to prevent accidental taps
- Provides a minimal floating toolbar with toggle visibility button
- Enables a completely distraction-free canvas even on desktop devices by hiding the main toolbar and all chrome while keeping a tiny movable toggle control (addresses immersive canvas / beyond Zen Mode request)
- Draggable toolbar can be positioned anywhere on screen
- Exit Palm Guard mode with a single tap
- Press the hotkey you configured for this script in Obsidian's Hotkey settings (e.g., ALT+X) to toggle UI visibility; if no hotkey is set, use the on-screen toggle button.
![Palm Guard Script](https://youtu.be/A_udjVjgWN0)
```js
*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.14.2")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
async function run() {
if(window.excalidrawPalmGuard) {
window.excalidrawPalmGuard()
return;
}
const modal = new ea.FloatingModal(ea.plugin.app);
const FULLSCREEN = "Goto fullscreen?";
let settings = ea.getScriptSettings() || {};
if(!settings[FULLSCREEN]) {
settings[FULLSCREEN] = { value: true };
await ea.setScriptSettings(settings);
}
//added only to clean up settings if someone installed the initial version of the script
const HOTKEY_MODIFIERS = "PalmGuard Toggle UI Hotkey Modifiers";
const HOTKEY_KEY = "PalmGuard Toggle UI Hotkey Key";
if(settings[HOTKEY_MODIFIERS] || settings[HOTKEY_KEY]) {
delete settings[HOTKEY_MODIFIERS];
delete settings[HOTKEY_KEY];
await ea.setScriptSettings(settings);
}
const enableFullscreen = settings[FULLSCREEN].value;
// Initialize state
let uiHidden = true;
let currentIcon = "eye";
const toolbar = ea.targetView.contentEl.querySelector(".excalidraw > .Island");
let toolbarActive = toolbar?.style.display === "block";
let prevHiddenState = false;
// Function to toggle UI visibility
const toggleUIVisibility = (hidden) => {
if(hidden === prevHiddenState) return hidden;
prevHiddenState = hidden;
try{
const topBar = ea.targetView.containerEl.querySelector(".App-top-bar");
const bottomBar = ea.targetView.containerEl.querySelector(".App-bottom-bar");
const sidebarToggle = ea.targetView.containerEl.querySelector(".sidebar-toggle");
const plugins = ea.targetView.containerEl.querySelector(".plugins-container");
if(hidden) {
if (toolbarActive && (toolbar?.style.display === "none")) {
toolbarActive = false;
}
if (toolbarActive = toolbar?.style.display === "block") {
toolbarActive = true;
};
}
const display = hidden ? "none" : "";
if (topBar) topBar.style.display = display;
if (bottomBar) bottomBar.style.display = display;
if (sidebarToggle) sidebarToggle.style.display = display;
if (plugins) plugins.style.display = display;
if (toolbarActive) toolbar.style.display = hidden ? "none" : "block";
modal.modalEl.style.opacity = hidden ? "0.4" : "0.8";
} catch {};
return hidden;
};
// Enter fullscreen view mode
if(enableFullscreen) ea.targetView.gotoFullscreen();
setTimeout(()=>toggleUIVisibility(true),100);
// Create floating toolbar modal
Object.assign(modal.modalEl.style, {
width: "fit-content",
minWidth: "fit-content",
height: "fit-content",
minHeight: "fit-content",
paddingBottom: "4px",
paddingTop: "16px",
paddingRight: "4px",
paddingLeft: "4px"
});
modal.headerEl.style.display = "none";
// Configure modal
modal.titleEl.setText(""); // No title for minimal UI
// Create modal content
modal.contentEl.createDiv({ cls: "palm-guard-toolbar" }, div => {
const container = div.createDiv({
attr: {
style: "display: flex; flex-direction: column; background-color: var(--background-secondary); border-radius: 4px;"
}
});
// Button container
const buttonContainer = container.createDiv({
attr: {
style: "display: flex; flex-wrap: wrap; gap: 4px; justify-content: center;"
}
});
// Toggle UI visibility button
const toggleButton = buttonContainer.createEl("button", {
cls: "palm-guard-btn clickable-icon",
attr: {
style: "background-color: var(--interactive-accent); color: var(--text-on-accent);"
}
});
toggleButton.innerHTML = ea.obsidian.getIcon("eye").outerHTML;
// Keyboard hotkey listener (only acts if hotkey configured)
window.excalidrawPalmGuard = () => toggleButton.click();
toggleButton.addEventListener("click", () => {
uiHidden = !uiHidden;
toggleUIVisibility(uiHidden);
// Toggle icon
currentIcon = uiHidden ? "eye" : "eye-off";
toggleButton.innerHTML = ea.obsidian.getIcon(currentIcon).outerHTML;
});
// Exit button
const exitButton = buttonContainer.createEl("button", {
cls: "palm-guard-btn clickable-icon",
attr: {
style: "background-color: var(--background-secondary-alt); color: var(--text-normal);"
}
});
exitButton.innerHTML = ea.obsidian.getIcon("cross").outerHTML;
exitButton.addEventListener("click", () => {
modal.close();
});
// Add CSS
div.createEl("style", {
text: `
.palm-guard-btn:hover {
filter: brightness(1.1);
}
.modal-close-button {
display: none;
}
.palm-guard-btn {
display: flex;
justify-content: center;
align-items: center;
padding: 4px;
border-radius: 10%;
width: 2em;
height: 2em;
cursor: pointer;
}
`
});
});
const autocloseTimer = setInterval(()=>{
if(!ea.targetView) modal.close();
},1000);
// Handle modal close (exit Palm Guard mode)
modal.onClose = () => {
// Show all UI elements
toggleUIVisibility(false);
// Exit fullscreen
if(ea.targetView && enableFullscreen) ea.targetView.exitFullscreen();
clearInterval(autocloseTimer);
delete window.excalidrawPalmGuard;
};
// Open the modal
modal.open();
// Position the modal in the top left initially
setTimeout(() => {
const modalEl = modal.modalEl;
const rect = ea.targetView.contentEl.getBoundingClientRect();
if (modalEl) {
modalEl.style.left = `${rect.left+10}px`;
modalEl.style.top = `${rect.top+10}px`;
}
}, 100);
}
run();
+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="skip"><path d="M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2"/><path d="M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2"/><path d="M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8"/><path d="M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15"/></svg>

After

Width:  |  Height:  |  Size: 459 B

+864
View File
@@ -0,0 +1,864 @@
/*
Export Excalidraw to PDF Pages: Define printable page areas using frames, then export each frame as a separate page in a multi-page PDF. Perfect for turning your Excalidraw drawings into printable notes, handouts, or booklets. Supports standard and custom page sizes, margins, and easy frame arrangement.
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-01.png)
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-02.png)
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-03.png)
![Marker Frames](https://youtu.be/DqDnzCOoYMc)
![Printable Layout Wizard](https://youtu.be/29EWeglRm7s)
```js
*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.15.0")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
if(window.excalidrawPrintableLayoutWizardModal) {
window.excalidrawPrintableLayoutWizardModal.open();
return;
}
// Help text for the script
const HELP_TEXT = `
**Easily split your Excalidraw drawing into printable pages!**
If you find this script helpful, consider [buying me a coffee](https://ko-fi.com/zsolt). Thank you.
---
### How it works
- **Define Pages:** Use frames to mark out each page area in your drawing. You can create the first frame with this script (choose a standard size or orientation), or draw your own frame for a custom page size.
- **Add More Pages:** Select a frame, then use the arrow buttons to add new frames next to it. All new frames will match the size of the selected one.
- **Rename Frames:** You can rename frames as you like. When exporting to PDF, pages will be ordered alphabetically by frame name.
---
### Important Notes
- **Same Size & Orientation:** All frames must have the same size and orientation (e.g., all A4 Portrait) to export to PDF. Excalidraw currently does not support PDFs with different-sized pages.
- **Custom Sizes:** If you draw your own frame, the PDF will use that exact size—great for custom page layouts!
- **Margins:** If you set a margin, the page size stays the same, but your content will shrink to fit inside the printable area.
- **No Frame Borders/Titles in Print:** Frame borders and frame titles will *not* appear in the PDF.
- **No Frame Clipping:** The script disables frame clipping for this drawing.
- **Templates:** You can save a template document with prearranged frames (even locked ones) for reuse.
- **Lock Frames:** Frames only define print areas—they don't "contain" elements. Locking frames is recommended to prevent accidental movement.
- **Outside Content:** Anything outside the frames will *not* appear in the PDF.
---
### Printing
- **Export to PDF:** Click the printer button to export each frame as a separate page in a PDF.
- **Order:** Pages are exported in alphabetical order of frame names.
---
### Settings
You can also access script settings at the bottom of Excalidraw Plugin settings. The script stores your preferences for:
- Locking new frames after creation
- Zooming to new frames
- Closing the dialog after adding a frame
- Default page size and orientation
- Print margin
---
**Tip:** For more on templates, see [Mastering Excalidraw Templates](https://youtu.be/jgUpYznHP9A). For referencing pages in markdown, see [Image Fragments](https://youtu.be/sjZfdqpxqsg) and [Image Block References](https://youtu.be/yZQoJg2RCKI).
![Marker Frames](https://youtu.be/DqDnzCOoYMc)
![Printable Layout Wizard](https://youtu.be/29EWeglRm7s)
`;
async function run() {
modal = new ea.FloatingModal(ea.plugin.app);
window.excalidrawPrintableLayoutWizardModal = modal;
modal.contentEl.empty();
let shouldRestart = false;
// Enable frame rendering
const st = ea.getExcalidrawAPI().getAppState();
let {enabled, clip, name, outline, markerName, markerEnabled} = st.frameRendering;
if(!enabled || !name || !outline || !markerEnabled || !markerName) {
ea.viewUpdateScene({
appState: {
frameRendering: {
enabled: true,
clip: clip,
name: true,
outline: true,
markerName: true,
markerEnabled: true
}
}
});
}
// Page size options (using standard sizes from ExcalidrawAutomate)
const PAGE_SIZES = [
"A0", "A1", "A2", "A3", "A4", "A5", "A6",
"Letter", "Legal", "Tabloid", "Ledger"
];
const PAGE_ORIENTATIONS = ["portrait", "landscape"];
// Margin sizes in points
const MARGINS = {
"none": 0,
"tiny": 10,
"normal": 60,
};
// Initialize settings
let settings = ea.getScriptSettings();
let dirty = false;
// Define setting keys
const PAGE_SIZE = "Page size";
const ORIENTATION = "Page orientation";
const MARGIN = "Print-margin";
const LOCK_FRAME = "Lock frame after it is created";
const SHOULD_ZOOM = "Should zoom after adding page";
const SHOULD_CLOSE = "Should close after adding page";
const PRINT_EMPTY = "Print empty pages";
const PRINT_MARKERS_ONLY = "Print only marker frames";
// Set default values on first run
if (!settings[PAGE_SIZE]) {
settings = {};
settings[PAGE_SIZE] = { value: "A4", valueset: PAGE_SIZES };
settings[ORIENTATION] = { value: "portrait", valueset: PAGE_ORIENTATIONS };
settings[MARGIN] = { value: "none", valueset: Object.keys(MARGINS)};
settings[SHOULD_ZOOM] = { value: false };
settings[SHOULD_CLOSE] = { value: false };
settings[LOCK_FRAME] = { value: true };
settings[PRINT_EMPTY] = { value: false };
settings[PRINT_MARKERS_ONLY] = { value: true };
dirty = true;
}
//once off correction. In the first version I incorrectly used valueSet with wrong casing.
if(settings[PAGE_SIZE].valueSet) {
settings[PAGE_SIZE].valueset = settings[PAGE_SIZE].valueSet;
delete settings[PAGE_SIZE].valueSet;
settings[ORIENTATION].valueset = settings[ORIENTATION].valueSet;
delete settings[ORIENTATION].valueSet;
settings[MARGIN].valueset = settings[MARGIN].valueSet;
delete settings[MARGIN].valueSet;
dirty = true;
}
if(!settings[LOCK_FRAME]) {
settings[LOCK_FRAME] = { value: true };
dirty = true;
}
if(!settings[PRINT_EMPTY]) {
settings[PRINT_EMPTY] = { value: false };
dirty = true;
}
if(!settings[PRINT_MARKERS_ONLY]) {
settings[PRINT_MARKERS_ONLY] = { value: true };
dirty = true;
}
let lockFrame = settings[LOCK_FRAME].value;
let shouldClose = settings[SHOULD_CLOSE].value;
let shouldZoom = settings[SHOULD_ZOOM].value;
let printEmptyPages = settings[PRINT_EMPTY].value;
let printMarkersOnly = settings[PRINT_MARKERS_ONLY].value;
const getSortedFrames = () => {
return ea.getViewElements()
.filter(el => isEligibleFrame(el))
.sort((a, b) => {
const nameA = a.name || "";
const nameB = b.name || "";
return nameA.localeCompare(nameB);
});
};
// Find existing page frames and determine next page number
const findExistingPages = (selectLastFrame = false) => {
const frameElements = getSortedFrames();
// Extract page numbers from frame names
const pageNumbers = frameElements
.map(frame => {
const match = frame.name?.match(/(?:Page\s+)?(\d+)/i);
return match ? parseInt(match[1]) : 0;
})
.filter(num => !isNaN(num));
// Find the highest page number
const nextPageNumber = pageNumbers.length > 0
? Math.max(...pageNumbers) + 1
: 1;
if(selectLastFrame && frameElements.length > 0) {
ea.selectElementsInView([frameElements[frameElements.length-1]]);
}
return {
frames: frameElements,
nextPageNumber: nextPageNumber
};
};
const isEligibleFrame = (el) => el.type === "frame" && (printMarkersOnly ? el.frameRole === "marker" : true);
// Check if there are frames in the scene and if a frame is selected
let existingFrames = ea.getViewElements().filter(el => isEligibleFrame(el));
let selectedFrame = ea.getViewSelectedElements().find(el => isEligibleFrame(el));
const hasFrames = existingFrames.length > 0;
if(hasFrames && !selectedFrame) {
if(st.activeLockedId && existingFrames.find(f=>f.id === st.activeLockedId)) {
selectedFrame = existingFrames.find(f=>f.id === st.activeLockedId);
ea.viewUpdateScene({ appState: { activeLockedId: null }});
ea.selectElementsInView([selectedFrame]);
} else {
findExistingPages(true);
selectedFrame = ea.getViewSelectedElements().find(el => isEligibleFrame(el));
}
}
const hasSelectedFrame = !!selectedFrame;
// rotation is now a temporary UI state controlled by the center button
let rotateOnAdd = false;
let centerRotateBtn = null;
const setRotateBtnActive = (active) => {
if (!centerRotateBtn) return;
centerRotateBtn.classList.toggle("is-accent", active);
centerRotateBtn.setAttribute("aria-pressed", active ? "true" : "false");
};
// Show notice if there are frames but none selected
if (hasFrames && !hasSelectedFrame) {
new Notice("Select a frame before running the script", 7000);
return;
}
// Create the first frame
const createFirstFrame = async (pageSize, orientation) => {
// Use ExcalidrawAutomate's built-in function to get page dimensions
const dimensions = ea.getPagePDFDimensions(pageSize, orientation);
if (!dimensions) {
new Notice("Invalid page size selected");
return;
}
// Save settings when creating first frame
if (settings[PAGE_SIZE].value !== pageSize) {
settings[PAGE_SIZE].value = pageSize;
dirty = true;
}
if (settings[ORIENTATION].value !== orientation) {
settings[ORIENTATION].value = orientation;
dirty = true;
}
// Format page number with leading zero
const pageName = "01";
// Calculate position to center the frame
const appState = ea.getExcalidrawAPI().getAppState();
const x = (appState.width - dimensions.width) / 2;
const y = (appState.height - dimensions.height) / 2;
return await addFrameElement(x, y, dimensions.width, dimensions.height, pageName, true);
};
// Add new page frame
const addPage = async (direction, pageSize, orientation) => {
selectedFrame = ea.getViewSelectedElements().find(el => isEligibleFrame(el));
if (!selectedFrame) {
const { activeLockedId } = ea.getExcalidrawAPI().getAppState();
if(activeLockedId) {
selectedFrame = ea.getViewElements().find(el=>el.id === activeLockedId && isEligibleFrame(el));
}
if (!selectedFrame) return;
}
ea.viewUpdateScene({appState: {activeLockedId: null}});
const { frames, nextPageNumber } = findExistingPages();
// Get dimensions from selected frame, support optional rotation
const dimensions = {
width: rotateOnAdd ? selectedFrame.height : selectedFrame.width,
height: rotateOnAdd ? selectedFrame.width : selectedFrame.height
};
// Format page number with leading zero
const pageName = `${nextPageNumber.toString().padStart(2, '0')}`;
// Calculate position based on direction and selected frame
let x = 0;
let y = 0;
switch (direction) {
case "right":
x = selectedFrame.x + selectedFrame.width;
y = selectedFrame.y;
break;
case "left":
x = selectedFrame.x - dimensions.width;
y = selectedFrame.y;
break;
case "down":
x = selectedFrame.x;
y = selectedFrame.y + selectedFrame.height;
break;
case "up":
x = selectedFrame.x;
y = selectedFrame.y - dimensions.height;
break;
}
const added = await addFrameElement(x, y, dimensions.width, dimensions.height, pageName);
// reset the rotate toggle after adding the frame
rotateOnAdd = false;
setRotateBtnActive(false);
return added;
};
addFrameElement = async (x, y, width, height, pageName, repositionToCursor = false) => {
const frameId = ea.addFrame(x, y, width, height, pageName);
ea.getElement(frameId).frameRole = "marker";
if(lockFrame) {
ea.getElement(frameId).locked = true;
}
await ea.addElementsToView(repositionToCursor);
const addedFrame = ea.getViewElements().find(el => el.id === frameId);
if(shouldZoom) {
ea.viewZoomToElements(true, [addedFrame]);
} else {
ea.selectElementsInView([addedFrame]);
}
//ready for the next frame
ea.clear();
selectedFrame = addedFrame;
if(shouldClose) {
modal.close();
}
return addedFrame;
}
const translateToZero = ({ x, y, width, height }, padding=0) => {
const top = y, left = x, right = x + width, bottom = y + height;
const {topX, topY, width:w, height:h} = ea.getBoundingBox(ea.getViewElements());
const newTop = top - (topY - padding);
const newLeft = left - (topX - padding);
const newBottom = bottom - (topY - padding);
const newRight = right - (topX - padding);
return {
top: newTop,
left: newLeft,
bottom: newBottom,
right: newRight,
};
}
// NEW: detect if any non-frame element overlaps the given area
const hasElementsInArea = (area) => ea.getElementsInArea(ea.getViewElements(), area).length>0;
const checkFrameSizes = (frames) => {
if (frames.length <= 1) return true;
const referenceWidth = frames[0].width;
const referenceHeight = frames[0].height;
return frames.every(frame =>
Math.abs(frame.width - referenceWidth) < 1 &&
Math.abs(frame.height - referenceHeight) < 1
);
};
const printToPDF = async (marginSize) => {
const margin = MARGINS[marginSize] || 0;
// Save margin setting
if (settings[MARGIN].value !== marginSize) {
settings[MARGIN].value = marginSize;
dirty = true;
}
// Get all frame elements and sort by name
const frames = getSortedFrames();
if (frames.length === 0) {
new Notice("No frames found to print");
return;
}
// Create a notice during processing
const notice = new Notice("Preparing PDF, please wait...", 0);
// Create SVGs for each frame
const svgPages = [];
let placeholderRects = [];
ea.clear();
for (const frame of frames) {
ea.style.opacity = 0;
ea.style.roughness = 0;
ea.style.fillStyle = "solid";
ea.style.backgroundColor = "black"
ea.style.strokeWidth = 0.01;
ea.addRect(frame.x, frame.y, frame.width, frame.height);
}
const svgScene = await ea.createViewSVG({
withBackground: true,
theme: st.theme,
//frameRendering: { enabled: false, name: false, outline: false, clip: false },
padding: 0,
selectedOnly: false,
skipInliningFonts: false,
embedScene: false,
elementsOverride: ea.getViewElements().concat(ea.getElements()),
});
ea.clear();
for (const frame of frames) {
// NEW: skip empty frames unless user opted to print them
if(!printEmptyPages && !hasElementsInArea(frame)) continue;
const { top, left, bottom, right } = translateToZero(frame);
//always create the new SVG in the main Obsidian workspace (not the popout window, if present)
const host = window.createDiv();
host.innerHTML = svgScene.outerHTML;
const clonedSVG = host.firstElementChild;
const width = Math.abs(left-right);
const height = Math.abs(top-bottom);
clonedSVG.setAttribute("viewBox", `${left} ${top} ${width} ${height}`);
clonedSVG.setAttribute("width", `${width}`);
clonedSVG.setAttribute("height", `${height}`);
svgPages.push(clonedSVG);
}
// NEW: abort if nothing to print
if(svgPages.length === 0) {
notice.hide();
new Notice("No pages to print (all selected frames are empty)");
notice.hide();
return;
}
// Use dimensions from the first frame
const width = frames[0].width;
const height = frames[0].height;
// Create PDF
await ea.createPDF({
SVG: svgPages,
scale: { fitToPage: true },
pageProps: {
dimensions: {},
//dimensions: { width, height },
backgroundColor: "#ffffff",
margin: {
left: margin,
right: margin,
top: margin,
bottom: margin
},
alignment: "center"
},
filename: ea.targetView.file.basename + "-pages.pdf"
});
notice.hide();
};
// -----------------------
// Create a floating modal
// -----------------------
modal.titleEl.setText("Page Management");
modal.titleEl.style.textAlign = "center";
modal.onClose = async () => {
delete window.excalidrawPrintableLayoutWizardModal;
if (dirty) {
await ea.setScriptSettings(settings);
}
ea.viewUpdateScene({
appState: {
frameRendering: {enabled, clip, name, outline, markerName, markerEnabled}
}
});
if(shouldRestart) setTimeout(()=>run());
};
// Create modal content
modal.contentEl.createDiv({ cls: "excalidraw-page-manager" }, div => {
const container = div.createDiv({
attr: {
style: "display: flex; flex-direction: column; gap: 15px; padding: 10px;"
}
});
// Help section
const helpDiv = container.createDiv({
attr: {
style: "margin-bottom: 10px;"
}
});
helpDiv.createEl("details", {}, (details) => {
details.createEl("summary", {
text: "Help & Information",
attr: {
style: "cursor: pointer; font-weight: bold; margin-bottom: 10px;"
}
});
details.createEl("div", {
attr: {
style: "padding: 10px; border: 1px solid var(--background-modifier-border); border-radius: 4px; margin-top: 8px; font-size: 0.9em; max-height: 300px; overflow-y: auto;"
}
}, div => {
ea.obsidian.MarkdownRenderer.render(ea.plugin.app, HELP_TEXT, div, "", ea.plugin)
});
});
// Tabs (show only when frames exist)
let framesTabEl, printingTabEl, tabsHeaderEl, marginDropdown;
if (hasFrames) {
tabsHeaderEl = container.createDiv({
attr: { style: "display:flex; gap:8px; border-bottom:1px solid var(--background-modifier-border); padding-bottom:0;" }
});
tabsHeaderEl.addClass("tabs-header"); // NEW
const framesTabBtn = tabsHeaderEl.createEl("button", {
text: "Frames",
attr: { style: "padding:8px 12px; cursor:pointer;" }
});
framesTabBtn.addClass("tab-btn"); // NEW
const printingTabBtn = tabsHeaderEl.createEl("button", {
text: "Printing",
attr: { style: "padding:8px 12px; cursor:pointer;" }
});
printingTabBtn.addClass("tab-btn"); // NEW
const tabsBody = container.createDiv();
tabsBody.addClass("tab-panels"); // NEW
framesTabEl = tabsBody.createDiv({ attr: { style: "display:block;" } });
framesTabEl.addClass("tab-panel"); // NEW
printingTabEl = tabsBody.createDiv({ attr: { style: "display:none;" } });
printingTabEl.addClass("tab-panel"); // NEW
const activate = (tab) => {
if (tab === "frames") {
framesTabEl.style.display = "";
printingTabEl.style.display = "none";
framesTabBtn.classList.add("is-active");
printingTabBtn.classList.remove("is-active");
} else {
framesTabEl.style.display = "none";
printingTabEl.style.display = "";
framesTabBtn.classList.remove("is-active");
printingTabBtn.classList.add("is-active");
}
};
framesTabBtn.addEventListener("click", () => {
window.excalidrawPrintLayoutWizard = "frames";
activate("frames")
});
printingTabBtn.addEventListener("click", () => {
window.excalidrawPrintLayoutWizard = "printing";
activate("printing")
});
activate(window.excalidrawPrintLayoutWizard ?? "frames");
} else {
// No frames yet, only frames tab content
framesTabEl = container.createDiv();
}
const createOptionsContainerCommonControls = (optionsContainer) => {
new ea.obsidian.Setting(optionsContainer)
.setName("Lock")
.setDesc("Lock the new frame element after it is created.")
.addToggle(toggle => {
toggle.setValue(lockFrame).onChange(value => {
lockFrame = value;
if (settings[LOCK_FRAME].value !== value) {
settings[LOCK_FRAME].value = value; dirty = true;
}
});
});
new ea.obsidian.Setting(optionsContainer)
.setName("Zoom to new frame")
.setDesc("Automatically zoom to the newly created frame")
.addToggle(toggle => {
toggle.setValue(shouldZoom).onChange(value => {
shouldZoom = value;
if (settings[SHOULD_ZOOM].value !== value) {
settings[SHOULD_ZOOM].value = value; dirty = true;
}
});
});
new ea.obsidian.Setting(optionsContainer)
.setName("Close after adding")
.setDesc("Close this dialog after adding a new frame")
.addToggle(toggle => {
toggle.setValue(shouldClose).onChange(value => {
shouldClose = value;
if (settings[SHOULD_CLOSE].value !== value) {
settings[SHOULD_CLOSE].value = value; dirty = true;
}
});
});
new ea.obsidian.Setting(optionsContainer)
.setName("Use only Marker Frames")
.setDesc("When off, all frames will be printed (not just marker frames)")
.addToggle(toggle => {
toggle.setValue(printMarkersOnly).onChange(value => {
printMarkersOnly = value;
if (settings[PRINT_MARKERS_ONLY].value !== value) {
settings[PRINT_MARKERS_ONLY].value = value;
dirty = true;
shouldRestart = true;
modal.close();
}
});
});
}
// FRAMES TAB CONTENT
// When no frames yet: initial size/orientation inputs and Create First Frame button
if (!hasFrames) {
const settingsContainer = framesTabEl.createDiv({
attr: {
// four columns: label + input, label + input
style: "display: grid; grid-template-columns: auto 1fr auto 1fr; gap: 10px; align-items: center;"
}
});
// Page Size
settingsContainer.createEl("label", { text: "Page Size:" });
const pageSizeDropdown = settingsContainer.createEl("select", {
cls: "dropdown",
attr: { style: "width: 100%;" }
});
PAGE_SIZES.forEach(size => pageSizeDropdown.createEl("option", { text: size, value: size }));
pageSizeDropdown.value = settings[PAGE_SIZE].value;
// Orientation
settingsContainer.createEl("label", { text: "Orientation:" });
const orientationDropdown = settingsContainer.createEl("select", {
cls: "dropdown",
attr: { style: "width: 100%;" }
});
PAGE_ORIENTATIONS.forEach(orientation => orientationDropdown.createEl("option", { text: orientation, value: orientation }));
orientationDropdown.value = settings[ORIENTATION].value;
const optionsContainer = framesTabEl.createDiv({ attr: { style: "margin-top: 10px;" } });
createOptionsContainerCommonControls(optionsContainer);
// Create First Frame button
const buttonContainer = framesTabEl.createDiv({
attr: { style: "display: grid; grid-template-columns: 1fr; gap: 10px; margin-top: 10px;" }
});
const createFirstBtn = buttonContainer.createEl("button", {
cls: "page-btn",
attr: { style: "height: 40px; background-color: var(--interactive-accent); color: var(--text-on-accent);" }
});
createFirstBtn.textContent = "Create First Frame";
createFirstBtn.addEventListener("click", async () => {
const tmpShouldClose = shouldClose;
shouldClose = true;
await createFirstFrame(pageSizeDropdown.value, orientationDropdown.value);
shouldClose = tmpShouldClose;
if(!shouldClose) {
shouldRestart = true;
modal.close()
}
});
} else {
// hasFrames: frame-management options + arrow buttons
const optionsContainer = framesTabEl.createDiv({ attr: { style: "margin-top: 10px;" } });
createOptionsContainerCommonControls(optionsContainer);
// Arrow buttons with center rotate toggle
const buttonContainer = framesTabEl.createDiv({
attr: {
style: "display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-top: 10px;"
}
});
const upBtn = buttonContainer.createEl("button", {
cls: "page-btn",
attr: { style: "grid-column: 2; grid-row: 1; height: 40px;" }
});
upBtn.innerHTML = ea.obsidian.getIcon("arrow-big-up").outerHTML;
upBtn.addEventListener("click", async () => { await addPage("up"); });
buttonContainer.createDiv({ attr: { style: "grid-column: 3; grid-row: 1;" } });
const leftBtn = buttonContainer.createEl("button", {
cls: "page-btn",
attr: { style: "grid-column: 1; grid-row: 2; height: 40px;" }
});
leftBtn.innerHTML = ea.obsidian.getIcon("arrow-big-left").outerHTML;
leftBtn.addEventListener("click", async () => { await addPage("left"); });
// Center toggle: Rotate next page
centerRotateBtn = buttonContainer.createEl("button", {
cls: "page-btn",
attr: { style: "grid-column: 2; grid-row: 2; height: 40px;" }
});
centerRotateBtn.textContent = "Rotate next page";
centerRotateBtn.addEventListener("click", () => {
rotateOnAdd = !rotateOnAdd;
setRotateBtnActive(rotateOnAdd);
});
setRotateBtnActive(rotateOnAdd);
const rightBtn = buttonContainer.createEl("button", {
cls: "page-btn",
attr: { style: "grid-column: 3; grid-row: 2; height: 40px;" }
});
rightBtn.innerHTML = ea.obsidian.getIcon("arrow-big-right").outerHTML;
rightBtn.addEventListener("click", async () => { await addPage("right"); });
const downBtn = buttonContainer.createEl("button", {
cls: "page-btn",
attr: { style: "grid-column: 2; grid-row: 3; height: 40px;" }
});
downBtn.innerHTML = ea.obsidian.getIcon("arrow-big-down").outerHTML;
downBtn.addEventListener("click", async () => { await addPage("down"); });
buttonContainer.createDiv({ attr: { style: "grid-column: 1; grid-row: 3;" } });
}
// PRINTING TAB CONTENT (only when hasFrames)
if (hasFrames && printingTabEl) {
const marginContainer = printingTabEl.createDiv({
attr: {
style: "display: grid; grid-template-columns: auto 1fr; gap: 10px; align-items: center; margin-top: 6px;"
}
});
marginContainer.createEl("label", { text: "Print Margin:" });
marginDropdown = marginContainer.createEl("select", { cls: "dropdown", attr: { style: "width: 100%;" } });
Object.keys(MARGINS).forEach(margin => marginDropdown.createEl("option", { text: margin, value: margin }));
marginDropdown.value = settings[MARGIN].value;
const printingOptions = printingTabEl.createDiv({ attr: { style: "margin-top: 10px;" } });
new ea.obsidian.Setting(printingOptions)
.setName(PRINT_EMPTY)
.setDesc("Include frames with no content in the PDF")
.addToggle(toggle => {
toggle.setValue(printEmptyPages).onChange(value => {
printEmptyPages = value;
if(settings[PRINT_EMPTY].value !== value) {
settings[PRINT_EMPTY].value = value;
dirty = true;
}
});
});
const printBtnRow = printingTabEl.createDiv({ attr: { style: "margin-top: 10px; display:flex; justify-content:flex-start;" } });
const printBtn = printBtnRow.createEl("button", {
cls: "page-btn",
attr: { style: "height: 40px; background-color: var(--interactive-accent);" }
});
printBtn.innerHTML = ea.obsidian.getIcon("printer").outerHTML;
printBtn.addEventListener("click", async () => { await printToPDF(marginDropdown.value); });
}
// CSS
div.createEl("style", {
text: `
.page-btn {
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
border-radius: 4px;
}
.page-btn:hover {
background-color: var(--interactive-hover);
}
.dropdown {
height: 30px;
background-color: var(--background-secondary);
color: var(--text-normal);
border-radius: 4px;
border: 1px solid var(--background-modifier-border);
padding: 0 10px;
}
.is-active {
background-color: var(--background-modifier-hover);
border-radius: 4px;
}
/* Tabs styling - NEW */
.tabs-header {
gap: 8px;
border-bottom: 1px solid var(--background-modifier-border);
}
.tabs-header .tab-btn {
background: var(--background-primary);
color: var(--text-normal);
border: 1px solid var(--background-modifier-border);
border-bottom: none;
border-top-left-radius: 6px;
border-top-right-radius: 6px;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
padding: 8px 12px;
margin-bottom: -1px; /* sit on top of the panel border */
}
.tabs-header .tab-btn:hover {
background: var(--background-modifier-hover);
}
.tabs-header .tab-btn.is-active {
background: var(--background-secondary);
color: var(--text-normal);
position: relative;
z-index: 2;
}
.tab-panels {
border: 1px solid var(--background-modifier-border);
border-radius: 0 6px 6px 6px; /* merge with active tab */
padding: 12px;
background: var(--background-primary);
}
/* accent styling for center rotate toggle when active */
.page-btn.is-accent {
background-color: var(--interactive-accent);
color: var(--text-on-accent);
}
.page-btn.is-accent:hover {
background-color: var(--interactive-accent-hover, var(--interactive-accent));
}
`
});
});
modal.open();
}
run();
+1
View File
@@ -0,0 +1 @@
<svg class="skip" 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"><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><path d="M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6"/><rect x="6" y="14" width="12" height="8" rx="1"/></svg>

After

Width:  |  Height:  |  Size: 386 B

+97 -76
View File
@@ -7,21 +7,27 @@ Scribble Helper can improve handwriting and add links. It lets you create and ed
```javascript
*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.8.25")) {
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.11.0")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
// ------------------------------
// Constants and initialization
// ------------------------------
const helpLINK = "https://youtu.be/BvYkOaly-QM";
const DBLCLICKTIMEOUT = 300;
const maxWidth = 600;
const padding = 6;
const api = ea.getExcalidrawAPI();
const win = ea.targetView.ownerWindow;
// Initialize global variables
if(!win.ExcalidrawScribbleHelper) win.ExcalidrawScribbleHelper = {};
if(typeof win.ExcalidrawScribbleHelper.penOnly === "undefined") {
win.ExcalidrawScribbleHelper.penOnly = false;
}
let windowOpen = false; //to prevent the modal window to open again while writing with scribble
let prevZoomValue = api.getAppState().zoom.value; //used to avoid trigger on pinch zoom
@@ -49,8 +55,10 @@ if(typeof win.ExcalidrawScribbleHelper.action === "undefined") {
}
//---------------------------------------
// Color Palette for stroke color setting
// Helper Functions
//---------------------------------------
// Color Palette for stroke color setting
// https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.6.8
const defaultStrokeColors = [
"#000000", "#343a40", "#495057", "#c92a2a", "#a61e4d",
@@ -58,7 +66,7 @@ const defaultStrokeColors = [
"#087f5b", "#2b8a3e", "#5c940d", "#e67700", "#d9480f"
];
const loadColorPalette = () => {
function loadColorPalette() {
const st = api.getAppState();
const strokeColors = new Set();
let strokeColorPalette = st.colorPalette?.elementStroke ?? defaultStrokeColors;
@@ -79,18 +87,8 @@ const loadColorPalette = () => {
return strokeColors;
}
//----------------------------------------------------------
// Define variables to cache element location on first click
//----------------------------------------------------------
// if a single element is selected when the action is started, update that existing text
let containerElements = ea.getViewSelectedElements()
.filter(el=>["arrow","rectangle","ellipse","line","diamond"].contains(el.type));
let selectedTextElements = ea.getViewSelectedElements().filter(el=>el.type==="text");
//-------------------------------------------
// Functions to add and remove event listners
//-------------------------------------------
const addEventHandler = (handler) => {
// Event handler management
function addEventHandler(handler) {
if(win.ExcalidrawScribbleHelper.eventHandler) {
win.removeEventListner("pointerdown", handler);
}
@@ -99,40 +97,53 @@ const addEventHandler = (handler) => {
win.ExcalidrawScribbleHelper.window = win;
}
const removeEventHandler = (handler) => {
function removeEventHandler(handler) {
win.removeEventListener("pointerdown",handler);
delete win.ExcalidrawScribbleHelper.eventHandler;
delete win.ExcalidrawScribbleHelper.window;
}
//Stop the script if scribble helper is clicked and no eligable element is selected
let silent = false;
if (win.ExcalidrawScribbleHelper?.eventHandler) {
removeEventHandler(win.ExcalidrawScribbleHelper.eventHandler);
delete win.ExcalidrawScribbleHelper.eventHandler;
delete win.ExcalidrawScribbleHelper.window;
if(!(containerElements.length === 1 || selectedTextElements.length === 1)) {
new Notice ("Scribble Helper was stopped",1000);
return;
// Edit existing text element function
async function editExistingTextElement(elements) {
windowOpen = true;
ea.copyViewElementsToEAforEditing(elements);
const el = ea.getElements()[0];
ea.style.strokeColor = el.strokeColor;
const text = await utils.inputPrompt({
header: "Edit text",
placeholder: "",
value: elements[0].rawText,
//buttons: undefined,
lines: 5,
displayEditorButtons: true,
customComponents: customControls,
blockPointerInputOutsideModal: true,
controlsOnTop: true
});
windowOpen = false;
if(!text) return;
el.strokeColor = ea.style.strokeColor;
el.originalText = text;
el.text = text;
el.rawText = text;
if(el.autoResize) {
ea.refreshTextElementSize(el.id);
}
await ea.addElementsToView(false,false);
if(el.containerId) {
const containers = ea.getViewElements().filter(e=>e.id === el.containerId);
api.updateContainerSize(containers);
ea.selectElementsInView(containers);
}
silent = true;
}
// ----------------------
// Custom dialog controls
// ----------------------
if (typeof win.ExcalidrawScribbleHelper.penOnly === "undefined") {
win.ExcalidrawScribbleHelper.penOnly = undefined;
}
if (typeof win.ExcalidrawScribbleHelper.penDetected === "undefined") {
win.ExcalidrawScribbleHelper.penDetected = false;
}
let timer = Date.now();
let eventHandler = () => {};
const customControls = (container) => {
// Custom dialog UI components
function customControls (container) {
const helpDIV = container.createDiv();
helpDIV.innerHTML = `<a href="${helpLINK}" target="_blank">Click here for help</a>`;
helpDIV.style.paddingBottom = "0.25em";
const viewBackground = api.getAppState().viewBackgroundColor;
const el1 = new ea.obsidian.Setting(container)
.setName(`Text color`)
@@ -152,9 +163,10 @@ const customControls = (container) => {
el1.nameEl.style.color = ea.style.strokeColor;
el1.nameEl.style.background = viewBackground;
el1.nameEl.style.fontWeight = "bold";
el1.settingEl.style.padding = "0.25em 0";
const el2 = new ea.obsidian.Setting(container)
.setName(`Trigger editor by pen double tap only`)
.setDesc(`Trigger editor by pen double tap only`)
.addToggle((toggle) => toggle
.setValue(win.ExcalidrawScribbleHelper.penOnly)
.onChange(value => {
@@ -162,13 +174,23 @@ const customControls = (container) => {
})
)
el2.settingEl.style.border = "none";
el2.settingEl.style.padding = "0.25em 0";
el2.settingEl.style.display = win.ExcalidrawScribbleHelper.penDetected ? "" : "none";
}
//----------------------------------------------------------
// Cache element location on first click
//----------------------------------------------------------
// if a single element is selected when the action is started, update that existing text
let containerElements = ea.getViewSelectedElements()
.filter(el=>["arrow","rectangle","ellipse","line","diamond"].contains(el.type));
let selectedTextElements = ea.getViewSelectedElements().filter(el=>el.type==="text");
// -------------------------------
// Click / dbl click event handler
// Main Click / dbl click event handler
// -------------------------------
eventHandler = async (evt) => {
let timer = Date.now();
async function eventHandler(evt) {
if(windowOpen) return;
if(ea.targetView !== app.workspace.activeLeaf.view) removeEventHandler(eventHandler);
if(evt && evt.target && !evt.target.hasClass("excalidraw__canvas")) return;
@@ -252,7 +274,7 @@ eventHandler = async (evt) => {
},
{
caption: "☱",
tooltip: "Add as Wrapped Text (rectangle with transparent border and background)",
tooltip: "Add as Wrapped Text",
action: () => {
win.ExcalidrawScribbleHelper.action="Wrap";
if(settings["Default action"].value!=="Wrap") {
@@ -266,6 +288,7 @@ eventHandler = async (evt) => {
if(win.ExcalidrawScribbleHelper.action !== "Text") actionButtons.push(actionButtons.shift());
if(win.ExcalidrawScribbleHelper.action === "Wrap") actionButtons.push(actionButtons.shift());
// Apply styles from current app state
ea.style.strokeColor = st.currentItemStrokeColor ?? ea.style.strokeColor;
ea.style.roughness = st.currentItemRoughness ?? ea.style.roughness;
ea.setStrokeSharpness(st.currentItemRoundness === "round" ? 0 : st.currentItemRoundness)
@@ -281,9 +304,18 @@ eventHandler = async (evt) => {
ea.style.verticalAlign = "middle";
windowOpen = true;
const text = await utils.inputPrompt (
"Edit text", "", "", containerID?undefined:actionButtons, 5, true, customControls, true
);
const text = await utils.inputPrompt ({
header: "Edit text",
placeholder: "",
value: "",
buttons: containerID?undefined:actionButtons,
lines: 5,
displayEditorButtons: true,
customComponents: customControls,
blockPointerInputOutsideModal: true,
controlsOnTop: true
});
windowOpen = false;
if(!text || text.trim() === "") return;
@@ -297,8 +329,11 @@ eventHandler = async (evt) => {
const textEl = ea.getElement(textId);
if(!container && (win.ExcalidrawScribbleHelper.action === "Wrap")) {
ea.style.backgroundColor = "transparent";
ea.style.strokeColor = "transparent";
textEl.autoResize = false;
textEl.width = Math.min(textEl.width, maxWidth);
ea.addElementsToView(false, false, true);
addEventHandler(eventHandler);
return;
}
if(!container && (win.ExcalidrawScribbleHelper.action === "Sticky")) {
@@ -342,36 +377,22 @@ eventHandler = async (evt) => {
ea.selectElementsInView(containers);
};
// ---------------------
// Edit Existing Element
// ---------------------
const editExistingTextElement = async (elements) => {
windowOpen = true;
ea.copyViewElementsToEAforEditing(elements);
const el = ea.getElements()[0];
ea.style.strokeColor = el.strokeColor;
const text = await utils.inputPrompt(
"Edit text","",elements[0].rawText,undefined,5,true,customControls,true
);
windowOpen = false;
if(!text) return;
el.strokeColor = ea.style.strokeColor;
el.originalText = text;
el.text = text;
el.rawText = text;
ea.refreshTextElementSize(el.id);
await ea.addElementsToView(false,false);
if(el.containerId) {
const containers = ea.getViewElements().filter(e=>e.id === el.containerId);
api.updateContainerSize(containers);
ea.selectElementsInView(containers);
//---------------------
// Script entry point
//---------------------
//Stop the script if scribble helper is clicked and no eligable element is selected
let silent = false;
if (win.ExcalidrawScribbleHelper?.eventHandler) {
removeEventHandler(win.ExcalidrawScribbleHelper.eventHandler);
delete win.ExcalidrawScribbleHelper.eventHandler;
delete win.ExcalidrawScribbleHelper.window;
if(!(containerElements.length === 1 || selectedTextElements.length === 1)) {
new Notice ("Scribble Helper was stopped",1000);
return;
}
silent = true;
}
//--------------
// Start actions
//--------------
if(!win.ExcalidrawScribbleHelper?.eventHandler) {
if(!silent) new Notice(
"To create a new text element,\ndouble-tap the screen.\n\n" +
+17 -21
View File
@@ -7,28 +7,23 @@ This script modifies the color lightness/hue/saturation/transparency of selected
- The color of SVG elements and nested Excalidraw drawings will only be mapped. When mapping colors, the original image remains unchanged, only a mapping table is created and the image is recolored during rendering of your Excalidraw screen. In case you want to make manual changes you can also edit the mapping in Markdown View Mode under `## Embedded Files`
If you select only a single SVG or nested Excalidraw element, then the script offers an additional feature. You can map colors one by one in the image.
```js*/
```js
*/
const HELP_TEXT = `
<ul>
<li dir="auto">Select SVG images, nested Excalidraw drawings and/or regular Excalidraw elements</li>
<li dir="auto">For a single selected image, you can map colors individually in the color mapping section</li>
<li dir="auto">For Excalidraw elements: stroke and background colors are modified permanently</li>
<li dir="auto">For SVG/nested drawings: original files stay unchanged, color mapping is stored under <code>## Embedded Files</code></li>
<li dir="auto">Using color maps helps maintain links between drawings while allowing different color themes</li>
<li dir="auto">Sliders work on relative scale - the amount of change is applied to current values</li>
<li dir="auto">Unlike Excalidraw's opacity setting which affects the whole element:
<ul>
<li dir="auto">Shade Master can set different opacity for stroke vs background</li>
<li dir="auto">Note: SVG/nested drawing colors are mapped at color name level, thus "black" is different from "#000000"</li>
<li dir="auto">Additionally if the same color is used as fill and stroke the color can only be mapped once</li>
</ul>
</li>
<li dir="auto">This is an experimental script - contributions welcome on GitHub via PRs</li>
</ul>
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/ISuORbVKyhQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
- Select SVG images, nested Excalidraw drawings and/or regular Excalidraw elements
- For a single selected image, you can map colors individually in the color mapping section
- For Excalidraw elements: stroke and background colors are modified permanently
- For SVG/nested drawings: original files stay unchanged, color mapping is stored under \`## Embedded Files\`
- Using color maps helps maintain links between drawings while allowing different color themes
- Sliders work on relative scale - the amount of change is applied to current values
- Unlike Excalidraw's opacity setting which affects the whole element:
- Shade Master can set different opacity for stroke vs background
- **Note:** SVG/nested drawing colors are mapped at color name level, thus "black" is different from "#000000"
- Additionally if the same color is used as fill and stroke the color can only be mapped once
- This is an experimental script - contributions welcome on GitHub via PRs
![](https://www.youtube.com/embed/ISuORbVKyhQ)
`;
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.7.2")) {
@@ -343,7 +338,8 @@ function showModal() {
const helpDetailsDiv = helpDiv.createEl("div", {
attr: { style: "margin-top: 0em; " }
});
helpDetailsDiv.innerHTML = HELP_TEXT;
//helpDetailsDiv.innerHTML = HELP_TEXT;
await ea.obsidian.MarkdownRenderer.render(ea.plugin.app, HELP_TEXT, helpDetailsDiv, "", ea.plugin);
const component = new ea.obsidian.Setting(contentEl)
.setName(FORMAT)
+3 -2
View File
@@ -2,8 +2,8 @@
This script splits an ellipse at any point where a line intersects it. If no lines are selected, it will use every line that intersects the ellipse. Otherwise, it will only use the selected lines. If there is no intersecting line, the ellipse will be converted into a line object.
There is also the option to close the object along the cut, which will close the cut in the shape of the line.
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-splitEllipse-demo1.jpg)
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-splitEllipse-demo2.jpg)
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-splitEllipse-demo1.png)
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-splitEllipse-demo2.png)
Tip: To use an ellipse as the cutting object, you first have to use this script on it, since it will convert the ellipse into a line.
@@ -54,6 +54,7 @@ angles.forEach((angle, key) => {
const lineId = ea.addLine(points);
const line = ea.getElement(lineId);
if (closeObject && cuttingLine) line.polygon = true;
line.frameId = ellipse.frameId;
line.groupIds = ellipse.groupIds;
});
-49
View File
@@ -1,49 +0,0 @@
/*
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/text-arch.jpg)
Fit a text to the arch of a circle. The script will prompt you for the radius of the circle and then split your text to individual letters and place each letter to the arch defined by the radius. Setting a lower radius value will increase the arching of the text. Note that the arched-text will no longer be editable as a text element and it will no longer function as a markdown link. Emojis are currently not supported.
```javascript
*/
el = ea.getViewSelectedElement();
if(!el || el.type!=="text") {
new Notice("Please select a text element");
return;
}
ea.style.fontSize = el.fontSize;
ea.style.fontFamily = el.fontFamily;
ea.style.strokeColor = el.strokeColor;
ea.style.opacity = el.opacity;
const r = parseInt (await utils.inputPrompt("The radius of the arch you'd like to fit the text to","number","150"));
const archAbove = await utils.suggester(["Arch above","Arch below"],[true,false]);
if(isNaN(r)) {
new Notice("The radius is not a number");
return;
}
circlePoint = (angle) => archAbove
? [
r * Math.sin(angle),
-r * Math.cos(angle)
]
: [
-r * Math.sin(angle),
r * Math.cos(angle)
];
let rot = (archAbove ? -0.5 : 0.5) * ea.measureText(el.text).width/r;
let objectIDs = [];
for(i=0;i<el.text.length;i++) {
const character = el.text.substring(i,i+1);
const width = ea.measureText(character).width;
ea.style.angle = rot;
const [x,y] = circlePoint(rot);
rot += (archAbove ? 1 : -1) *width / r;
objectIDs.push(ea.addText(x,y,character));
}
ea.addToGroup(objectIDs);
ea.addElementsToView(true, false, true);
File diff suppressed because it is too large. Load diff
File renamed without changes.

Before

Width:  |  Height:  |  Size: 327 B

After

Width:  |  Height:  |  Size: 327 B

+476
View File
@@ -0,0 +1,476 @@
/**
* Converts an ellipse element to a line element
* @param {Object} ellipse - The ellipse element to convert
* @param {number} pointDensity - Optional number of points to generate (defaults to 64)
* @returns {string} The ID of the created line element
```js*/
function ellipseToLine(ellipse, pointDensity = 64) {
if (!ellipse || ellipse.type !== "ellipse") {
throw new Error("Input must be an ellipse element");
}
// Calculate points along the ellipse perimeter
const stepSize = (Math.PI * 2) / pointDensity;
const points = drawEllipse(
ellipse.x,
ellipse.y,
ellipse.width,
ellipse.height,
ellipse.angle,
0,
Math.PI * 2,
stepSize
);
// Save original styling to apply to the new line
const originalStyling = {
strokeColor: ellipse.strokeColor,
strokeWidth: ellipse.strokeWidth,
backgroundColor: ellipse.backgroundColor,
fillStyle: ellipse.fillStyle,
roughness: ellipse.roughness,
strokeSharpness: ellipse.strokeSharpness,
frameId: ellipse.frameId,
groupIds: [...ellipse.groupIds],
opacity: ellipse.opacity
};
// Use current style
const prevStyle = {...ea.style};
// Apply ellipse styling to the line
ea.style.strokeColor = originalStyling.strokeColor;
ea.style.strokeWidth = originalStyling.strokeWidth;
ea.style.backgroundColor = originalStyling.backgroundColor;
ea.style.fillStyle = originalStyling.fillStyle;
ea.style.roughness = originalStyling.roughness;
ea.style.strokeSharpness = originalStyling.strokeSharpness;
ea.style.opacity = originalStyling.opacity;
// Create the line and close it
const lineId = ea.addLine(points);
const line = ea.getElement(lineId);
// Make it a polygon to close the path
line.polygon = true;
// Transfer grouping and frame information
line.frameId = originalStyling.frameId;
line.groupIds = originalStyling.groupIds;
// Restore previous style
ea.style = prevStyle;
return lineId;
// Helper function from the Split Ellipse script
function drawEllipse(x, y, width, height, angle = 0, start = 0, end = Math.PI*2, step = Math.PI/32) {
const ellipse = (t) => {
const spanningVector = rotateVector([width/2*Math.cos(t), height/2*Math.sin(t)], angle);
const baseVector = [x+width/2, y+height/2];
return addVectors([baseVector, spanningVector]);
}
if(end <= start) end = end + Math.PI*2;
let points = [];
const almostEnd = end - step/2;
for (let t = start; t < almostEnd; t = t + step) {
points.push(ellipse(t));
}
points.push(ellipse(end));
return points;
}
function rotateVector(vec, ang) {
var cos = Math.cos(ang);
var sin = Math.sin(ang);
return [vec[0] * cos - vec[1] * sin, vec[0] * sin + vec[1] * cos];
}
function addVectors(vectors) {
return vectors.reduce((acc, vec) => [acc[0] + vec[0], acc[1] + vec[1]], [0, 0]);
}
}
/**
* Converts a rectangle element to a line element
* @param {Object} rectangle - The rectangle element to convert
* @param {number} pointDensity - Optional number of points to generate for curved segments (defaults to 16)
* @returns {string} The ID of the created line element
*/
function rectangleToLine(rectangle, pointDensity = 16) {
if (!rectangle || rectangle.type !== "rectangle") {
throw new Error("Input must be a rectangle element");
}
// Save original styling to apply to the new line
const originalStyling = {
strokeColor: rectangle.strokeColor,
strokeWidth: rectangle.strokeWidth,
backgroundColor: rectangle.backgroundColor,
fillStyle: rectangle.fillStyle,
roughness: rectangle.roughness,
strokeSharpness: rectangle.strokeSharpness,
frameId: rectangle.frameId,
groupIds: [...rectangle.groupIds],
opacity: rectangle.opacity
};
// Use current style
const prevStyle = {...ea.style};
// Apply rectangle styling to the line
ea.style.strokeColor = originalStyling.strokeColor;
ea.style.strokeWidth = originalStyling.strokeWidth;
ea.style.backgroundColor = originalStyling.backgroundColor;
ea.style.fillStyle = originalStyling.fillStyle;
ea.style.roughness = originalStyling.roughness;
ea.style.strokeSharpness = originalStyling.strokeSharpness;
ea.style.opacity = originalStyling.opacity;
// Calculate points for the rectangle perimeter
const points = generateRectanglePoints(rectangle, pointDensity);
// Create the line and close it
const lineId = ea.addLine(points);
const line = ea.getElement(lineId);
// Make it a polygon to close the path
line.polygon = true;
// Transfer grouping and frame information
line.frameId = originalStyling.frameId;
line.groupIds = originalStyling.groupIds;
// Restore previous style
ea.style = prevStyle;
return lineId;
// Helper function to generate rectangle points with optional rounded corners
function generateRectanglePoints(rectangle, pointDensity) {
const { x, y, width, height, angle = 0 } = rectangle;
const centerX = x + width / 2;
const centerY = y + height / 2;
// If no roundness, create a simple rectangle
if (!rectangle.roundness) {
const corners = [
[x, y], // top-left
[x + width, y], // top-right
[x + width, y + height], // bottom-right
[x, y + height], // bottom-left
[x,y] //origo
];
// Apply rotation if needed
if (angle !== 0) {
return corners.map(point => rotatePoint(point, [centerX, centerY], angle));
}
return corners;
}
// Handle rounded corners
const points = [];
// Calculate corner radius using Excalidraw's algorithm
const cornerRadius = getCornerRadius(Math.min(width, height), rectangle);
const clampedRadius = Math.min(cornerRadius, width / 2, height / 2);
// Corner positions
const topLeft = [x + clampedRadius, y + clampedRadius];
const topRight = [x + width - clampedRadius, y + clampedRadius];
const bottomRight = [x + width - clampedRadius, y + height - clampedRadius];
const bottomLeft = [x + clampedRadius, y + height - clampedRadius];
// Add top-left corner arc
points.push(...createArc(
topLeft[0], topLeft[1], clampedRadius, Math.PI, Math.PI * 1.5, pointDensity));
// Add top edge
points.push([x + clampedRadius, y], [x + width - clampedRadius, y]);
// Add top-right corner arc
points.push(...createArc(
topRight[0], topRight[1], clampedRadius, Math.PI * 1.5, Math.PI * 2, pointDensity));
// Add right edge
points.push([x + width, y + clampedRadius], [x + width, y + height - clampedRadius]);
// Add bottom-right corner arc
points.push(...createArc(
bottomRight[0], bottomRight[1], clampedRadius, 0, Math.PI * 0.5, pointDensity));
// Add bottom edge
points.push([x + width - clampedRadius, y + height], [x + clampedRadius, y + height]);
// Add bottom-left corner arc
points.push(...createArc(
bottomLeft[0], bottomLeft[1], clampedRadius, Math.PI * 0.5, Math.PI, pointDensity));
// Add left edge
points.push([x, y + height - clampedRadius], [x, y + clampedRadius]);
// Apply rotation if needed
if (angle !== 0) {
return points.map(point => rotatePoint(point, [centerX, centerY], angle));
}
return points;
}
// Helper function to create an arc of points
function createArc(centerX, centerY, radius, startAngle, endAngle, pointDensity) {
const points = [];
const angleStep = (endAngle - startAngle) / pointDensity;
for (let i = 0; i <= pointDensity; i++) {
const angle = startAngle + i * angleStep;
const x = centerX + radius * Math.cos(angle);
const y = centerY + radius * Math.sin(angle);
points.push([x, y]);
}
return points;
}
// Helper function to rotate a point around a center
function rotatePoint(point, center, angle) {
const sin = Math.sin(angle);
const cos = Math.cos(angle);
// Translate point to origin
const x = point[0] - center[0];
const y = point[1] - center[1];
// Rotate point
const xNew = x * cos - y * sin;
const yNew = x * sin + y * cos;
// Translate point back
return [xNew + center[0], yNew + center[1]];
}
}
function getCornerRadius(x, element) {
const fixedRadiusSize = element.roundness?.value ?? 32;
const CUTOFF_SIZE = fixedRadiusSize / 0.25;
if (x <= CUTOFF_SIZE) {
return x * 0.25;
}
return fixedRadiusSize;
}
/**
* Converts a diamond element to a line element
* @param {Object} diamond - The diamond element to convert
* @param {number} pointDensity - Optional number of points to generate for curved segments (defaults to 16)
* @returns {string} The ID of the created line element
*/
function diamondToLine(diamond, pointDensity = 16) {
if (!diamond || diamond.type !== "diamond") {
throw new Error("Input must be a diamond element");
}
// Save original styling to apply to the new line
const originalStyling = {
strokeColor: diamond.strokeColor,
strokeWidth: diamond.strokeWidth,
backgroundColor: diamond.backgroundColor,
fillStyle: diamond.fillStyle,
roughness: diamond.roughness,
strokeSharpness: diamond.strokeSharpness,
frameId: diamond.frameId,
groupIds: [...diamond.groupIds],
opacity: diamond.opacity
};
// Use current style
const prevStyle = {...ea.style};
// Apply diamond styling to the line
ea.style.strokeColor = originalStyling.strokeColor;
ea.style.strokeWidth = originalStyling.strokeWidth;
ea.style.backgroundColor = originalStyling.backgroundColor;
ea.style.fillStyle = originalStyling.fillStyle;
ea.style.roughness = originalStyling.roughness;
ea.style.strokeSharpness = originalStyling.strokeSharpness;
ea.style.opacity = originalStyling.opacity;
// Calculate points for the diamond perimeter
const points = generateDiamondPoints(diamond, pointDensity);
// Create the line and close it
const lineId = ea.addLine(points);
const line = ea.getElement(lineId);
// Make it a polygon to close the path
line.polygon = true;
// Transfer grouping and frame information
line.frameId = originalStyling.frameId;
line.groupIds = originalStyling.groupIds;
// Restore previous style
ea.style = prevStyle;
return lineId;
function generateDiamondPoints(diamond, pointDensity) {
const { x, y, width, height, angle = 0 } = diamond;
const cx = x + width / 2;
const cy = y + height / 2;
// Diamond corners
const top = [cx, y];
const right = [x + width, cy];
const bottom = [cx, y + height];
const left = [x, cy];
if (!diamond.roundness) {
const corners = [top, right, bottom, left, top];
if (angle !== 0) {
return corners.map(pt => rotatePoint(pt, [cx, cy], angle));
}
return corners;
}
// Clamp radius
const r = Math.min(
getCornerRadius(Math.min(width, height) / 2, diamond),
width / 2,
height / 2
);
// For a diamond, the rounded corner is a *bezier* between the two adjacent edge points, not a circular arc.
// Excalidraw uses a quadratic bezier for each corner, with the control point at the corner itself.
// Calculate edge directions
function sub(a, b) { return [a[0] - b[0], a[1] - b[1]]; }
function add(a, b) { return [a[0] + b[0], a[1] + b[1]]; }
function norm([x, y]) {
const len = Math.hypot(x, y);
return [x / len, y / len];
}
function scale([x, y], s) { return [x * s, y * s]; }
// For each corner, move along both adjacent edges by r to get arc endpoints
// Order: top, right, bottom, left
const corners = [top, right, bottom, left];
const next = [right, bottom, left, top];
const prev = [left, top, right, bottom];
// For each corner, calculate the two points where the straight segments meet the arc
const arcPoints = [];
for (let i = 0; i < 4; ++i) {
const c = corners[i];
const n = next[i];
const p = prev[i];
const toNext = norm(sub(n, c));
const toPrev = norm(sub(p, c));
arcPoints.push([
add(c, scale(toPrev, r)), // start of arc (from previous edge)
add(c, scale(toNext, r)), // end of arc (to next edge)
c // control point for bezier
]);
}
// Helper: quadratic bezier between p0 and p2 with control p1
function bezier(p0, p1, p2, density) {
const pts = [];
for (let i = 0; i <= density; ++i) {
const t = i / density;
const mt = 1 - t;
pts.push([
mt*mt*p0[0] + 2*mt*t*p1[0] + t*t*p2[0],
mt*mt*p0[1] + 2*mt*t*p1[1] + t*t*p2[1]
]);
}
return pts;
}
// Build path: for each corner, straight line to arc start, then bezier to arc end using corner as control
let pts = [];
for (let i = 0; i < 4; ++i) {
const prevArc = arcPoints[(i + 3) % 4];
const arc = arcPoints[i];
if (i === 0) {
pts.push(arc[0]);
} else {
pts.push(arc[0]);
}
// Quadratic bezier from arc[0] to arc[1] with control at arc[2] (the corner)
pts.push(...bezier(arc[0], arc[2], arc[1], pointDensity));
}
pts.push(arcPoints[0][0]); // close
if (angle !== 0) {
return pts.map(pt => rotatePoint(pt, [cx, cy], angle));
}
return pts;
}
// Helper function to create an arc between two points
function createArcBetweenPoints(startPoint, endPoint, centerX, centerY, pointDensity) {
const startAngle = Math.atan2(startPoint[1] - centerY, startPoint[0] - centerX);
const endAngle = Math.atan2(endPoint[1] - centerY, endPoint[0] - centerX);
// Ensure angles are in correct order for arc drawing
let adjustedEndAngle = endAngle;
if (endAngle < startAngle) {
adjustedEndAngle += 2 * Math.PI;
}
const points = [];
const angleStep = (adjustedEndAngle - startAngle) / pointDensity;
// Start with the straight line to arc start
points.push(startPoint);
// Create arc points
for (let i = 1; i < pointDensity; i++) {
const angle = startAngle + i * angleStep;
const distance = Math.hypot(startPoint[0] - centerX, startPoint[1] - centerY);
const x = centerX + distance * Math.cos(angle);
const y = centerY + distance * Math.sin(angle);
points.push([x, y]);
}
// Add the end point of the arc
points.push(endPoint);
return points;
}
// Helper function to rotate a point around a center
function rotatePoint(point, center, angle) {
const sin = Math.sin(angle);
const cos = Math.cos(angle);
// Translate point to origin
const x = point[0] - center[0];
const y = point[1] - center[1];
// Rotate point
const xNew = x * cos - y * sin;
const yNew = x * sin + y * cos;
// Translate point back
return [xNew + center[0], yNew + center[1]];
}
}
const el = ea.getViewSelectedElement();
switch (el.type) {
case "rectangle":
rectangleToLine(el);
break;
case "ellipse":
ellipseToLine(el);
break;
case "diamond":
diamondToLine(el);
break;
}
ea.addElementsToView();
+1 -1
View File
@@ -1 +1 @@
[{"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":1682228345043},{"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":1735420748Line 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":1747585400113},{"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
+60 -7
View File
@@ -26,6 +26,36 @@ I would love to include your contribution in the script library. If you have a s
# List of available scripts
## Editors Picks
These are the scripts I use most often. I tried to order them by importance, but usefulness is situational—some days Crop Vintage Mask is as helpful as Deconstruct Selected Elements. I do deconstruct drawings daily; the entries lower in the Editors’ Picks list are still valuable, just needed less frequently.
| | |
|----|-----|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.svg"/></div>|[[#Deconstruct selected elements into new drawing]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Slideshow.svg"/></div>|[[#Slideshow]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Shade%20Master.svg"/></div>|[[#Shade Master]]|
|<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/Rename%20Image.svg"/></div>|[[#Rename Image]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Select%20Elements%20of%20Type.svg"/></div>|[[#Select Elements of Type]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Select%20Similar%20Elements.svg"/></div>|[[#Select Similar Elements]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Boolean%20Operations.svg"/></div>|[[#Boolean Operations]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Split%20Ellipse.svg"/></div>|[[#Split Ellipse]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20to%20Path.svg"/></div>|[[#Text to Path]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Dimensions.svg"/></div>|[[#Set Dimensions]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.svg"/></div>|[[#Set Stroke Width of Selected Elements]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Scribble%20Helper.svg"/></div>|[[#Scribble Helper]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Split%20text%20by%20lines.svg"/></div>|[[#Split text by lines]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20Aura.svg"/></div>|[[#Text Aura]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Golden%20Ratio.svg"/></div>|[[#Golden Ratio]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Printable%20Layout%20Wizard.svg"/></div>|[[#Printable Layout Wizard]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Concatenate%20lines.svg"></div>|[[#Concatenate lines]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Repeat%20Elements.svg"/></div>|[[#Repeat Elements]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.svg"/></div>|[[#Set background color of unclosed line object by adding a shadow clone]]|
|<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/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]]|
## Layout and Organization
**Keywords**: Design, Placement, Arrangement, Structure, Formatting, Alignment
@@ -47,6 +77,7 @@ I would love to include your contribution in the script library. If you have a s
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Golden%20Ratio.svg"/></div>|[[#Golden Ratio]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Grid%20Selected%20Images.svg"/></div>|[[#Grid selected images]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20format.svg"/></div>|[[#Mindmap format]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Printable%20Layout%20Wizard.svg"/></div>|[[#Printable Layout Wizard]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Zoom%20to%20Fit%20Selected%20Elements.svg"/></div>|[[#Zoom to Fit Selected Elements]]|
## Connectors and Arrows
@@ -73,8 +104,8 @@ I would love to include your contribution in the script library. If you have a s
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Font%20Family.svg"/></div>|[[#Set Font Family]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Text%20Alignment.svg"/></div>|[[#Set Text Alignment]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Split%20text%20by%20lines.svg"/></div>|[[#Split text by lines]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20Arch.svg"/></div>|[[#Text Arch]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20Aura.svg"/></div>|[[#Text Aura]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20to%20Path.svg"/></div>|[[#Text to Path]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20to%20Sticky%20Notes.svg"/></div>|[[#Text to Sticky Notes]]|
## Styling and Appearance
@@ -123,6 +154,7 @@ I would love to include your contribution in the script library. If you have a s
|<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]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Rename%20Image.svg"/></div>|[[#Rename Image]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Repeat%20Elements.svg"/></div>|[[#Repeat Elements]]|
@@ -467,6 +499,14 @@ 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/Palette%20loader.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Design your palette at <a href="http://paletton.com/" target="_blank">paletton.com</a> Once you are happy with your colors, click Tables/Export in the bottom right of the screen. Then click "Color swatches/as Sketch Palette", and copy the contents of the page to a markdown file in the palette folder of your vault (default is Excalidraw/Palette)<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-sketch-palette-loader-1.jpg'></td></tr></table>
## Palm Guard
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Palm%20Guard.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/Palm%20Guard.md'>File on GitHub</a></td></tr>
<tr valign='top'><td class="label">Description</td><td class="data">Mobile & desktop palm‑rejection and distraction‑free drawing mode: optionally enters fullscreen, hides ALL Excalidraw UI chrome (top toolbar, side / bottom bars, plugin panels) for a clean / zen / immersive / kiosk / focus mode canvas. Provides a tiny draggable micro toolbar (toggle visibility + exit) so you gain maximum drawing area while preventing accidental palm taps. Uses the hotkey you assign in Obsidian’s Hotkey settings for this script to instantly show / hide controls (if no hotkey is set, use the on‑screen toggle). Ideal for stylus sketching, presentations, screen recording, split‑view space saving, or anyone searching for: palm rejection, hide toolbar, hide UI controls, clean mode, distraction free Excalidraw.<br><iframe width="400" height="225" src="https://www.youtube.com/embed/A_udjVjgWN0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br><a href='https://youtu.be/A_udjVjgWN0' target='_blank'>Link to video on YouTube</a></td></tr></table>
## PDF Page Text to Clipboard
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/PDF%20Page%20Text%20to%20Clipboard.md
@@ -596,18 +636,24 @@ 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/Split%20text%20by%20lines.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Split lines of text into separate text elements for easier reorganization<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-split-lines.jpg'></td></tr></table>
## Text Arch
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20Arch.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/Text%20Arch.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Fit a text to the arch of a circle. The script will prompt you for the radius of the circle and then split your text to individual letters and place each letter to the arch defined by the radius. Setting a lower radius value will increase the arching of the text. Note that the arched-text will no longer be editable as a text element and it will no longer function as a markdown link. Emojis are currently not supported.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/text-arch.jpg'></td></tr></table>
## Text Aura
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20Aura.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/Text%20Aura.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Select a single text element, or a text element in a container. The container must have a transparent background.<br>The script will add an aura to the text by adding 4 copies of the text each with the inverted stroke color of the original text element and with a very small X and Y offset. The resulting 4 + 1 (original) text elements or containers will be grouped.<br>If you copy a color string on the clipboard before running the script, the script will use that color instead of the inverted color.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-aura.jpg'></td></tr></table>
## Text to Path
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20to%20Path.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/Text%20to%20Path.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script allows you to fit a text element along a selected path: line, arrow, freedraw, ellipse, rectangle, or diamond. You can select either a path or a text element, or both:<br><br>
- If only a path is selected, you will be prompted to provide the text.<br>
- If only a text element is selected and it was previously fitted to a path, the script will use the original path if it is still present in the scene.<br>
- If both a text and a path are selected, the script will fit the text to the selected path.<br><br>
If the path is a perfect circle, you will be prompted to choose whether to fit the text above or below the circle.<br><br>
After fitting, the text will no longer be editable as a standard text element or function as a markdown link. Emojis are not supported.<br>
<img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-to-path.jpg'></td></tr></table>
## Toggle Grid
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Toggle%20Grid.md
@@ -626,6 +672,13 @@ 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/Uniform%20size.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data"><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-uniform-size.jpg"><br>The script will standardize the sizes of rectangles, diamonds and ellipses adjusting all the elements to match the largest width and height within the group.</td></tr></table>
# Printable Layout Wizard
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Printable%20Layout%20Wizard.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/Printable%20Layout%20Wizard.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Export Excalidraw to PDF Pages: Define printable page areas using frames, then export each frame as a separate page in a multi-page PDF. Perfect for turning your Excalidraw drawings into printable notes, handouts, or booklets. Supports standard and custom page sizes, margins, and easy frame arrangement.<br><iframe width="400" height="225" src="https://www.youtube.com/embed/29EWeglRm7s" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br><a href='https://youtu.be/29EWeglRm7s' target='_blank'>Link to video on YouTube</a><br><iframe width="400" height="225" src="https://www.youtube.com/embed/DqDnzCOoYMc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br><a href='https://youtu.be/DqDnzCOoYMc' target='_blank'>Link to video on YouTube</a><br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-01.png" style="max-width: 400px;"><br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-02.png" style="max-width: 400px;"></td></tr></table>
## Zoom to Fit Selected Elements
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Zoom%20to%20Fit%20Selected%20Elements.md
Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

+3 -3
View File
@@ -1,10 +1,10 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.10.0",
"minAppVersion": "1.1.6",
"version": "2.15.3",
"minAppVersion": "1.5.7",
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
"author": "Zsolt Viczian",
"authorUrl": "https://zsolt.blog",
"authorUrl": "https://excalidraw-obsidian.online",
"isDesktopOnly": false
}
+4 -4
View File
@@ -1,12 +1,12 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.10.0",
"minAppVersion": "1.1.6",
"version": "2.15.3",
"minAppVersion": "1.5.7",
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
"author": "Zsolt Viczian",
"authorUrl": "https://www.zsolt.blog",
"authorUrl": "https://excalidraw-obsidian.online",
"fundingUrl": "https://ko-fi.com/zsolt",
"helpUrl": "https://github.com/zsviczian/obsidian-excalidraw-plugin#readme",
"isDesktopOnly": false
}
}
+2058 -1720
View File
File diff suppressed because it is too large. Load diff
+11 -6
View File
@@ -16,15 +16,16 @@
"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"
"dev:all": "npm run dev:mathjax && npm run dev",
"doc": "node scripts/generate-script-library.js"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"dependencies": {
"@popperjs/core": "^2.11.8",
"@zsviczian/excalidraw": "0.18.0-6",
"chroma-js": "^2.4.2",
"@zsviczian/excalidraw": "0.18.0-37",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"@zsviczian/colormaster": "^1.2.2",
"gl-matrix": "^3.4.3",
@@ -59,7 +60,7 @@
"@rollup/plugin-replace": "^5.0.2",
"@rollup/plugin-typescript": "^12.1.2",
"@rollup/plugin-json": "^6.1.0",
"@types/chroma-js": "^2.4.0",
"@types/chroma-js": "^3.1.1",
"@types/js-beautify": "^1.14.0",
"@types/js-yaml": "^4.0.9",
"@types/node": "^20.10.5",
@@ -89,5 +90,9 @@
"resolutions": {
"@typescript-eslint/typescript-estree": "5.3.0"
},
"prettier": "@excalidraw/prettier-config"
"prettier": "@excalidraw/prettier-config",
"engines": {
"node": ">=20.0.0",
"npm": ">=10.0.0"
}
}
+2 -2
View File
@@ -49,7 +49,7 @@ const jsxRuntimeShim = `
const mathjaxtosvg_pkg = isLib ? "" : fs.readFileSync("./MathjaxToSVG/dist/index.js", "utf8");
const LANGUAGES = ['ru', 'zh-cn']; //english is not compressed as it is always loaded by default
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(";")) {
@@ -101,7 +101,7 @@ if (!isLib) {
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/styles.production.css", "utf8")
: fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/styles.development.css", "utf8");
const plugin_styles = fs.readFileSync("./styles.css", "utf8");
const styles = plugin_styles + excalidraw_styles;
const styles = excalidraw_styles + plugin_styles;
cssnano()
.process(styles) // Process the CSS
.then(result => {
+105
View File
@@ -0,0 +1,105 @@
/* eslint-disable no-console */
const fs = require('fs');
const path = require('path');
const ROOT = path.resolve(__dirname, '..');
const EA_SCRIPTS_DIR = path.join(ROOT, 'ea-scripts');
const INDEX_NEW = path.join(EA_SCRIPTS_DIR, 'index-new.md');
const DIST_DIR = path.join(ROOT, 'dist');
const OUTPUT_FILE = path.join(DIST_DIR, 'Excalidraw Script Library.md');
const INTRO = `# Excalidraw Script Library
This file is an automatically generated knowledge base intended for Retrieval Augmented Generation (RAG) and other AI-assisted workflows (e.g. NotebookLM or local embeddings tools).
Its purpose:
- Provide a single, query-friendly corpus of all Excalidraw Automate scripts.
- Serve as a practical pattern and snippet library for developers learning Excalidraw Automate.
- Preserve original source side by side with the higher-level index (index-new.md) to improve semantic recall.
- Enable AI tools to answer questions about how to manipulate the Excalidraw canvas, elements, styling, or integration features by referencing real, working examples.
Content structure:
1. Intro (this section)
2. The curated script overview (index-new.md)
3. Raw source of every *.md script in /ea-scripts (each fenced code block is auto-closed to ensure well‑formed aggregation)
Generated on: ${new Date().toISOString()}
---
`;
/**
* Returns true if content contains at least one line starting with ```
* and has an odd number of fences (unbalanced).
*/
function needsClosingFence(content) {
const fenceCount = (content.match(/^```/gm) || []).length;
return fenceCount > 0 && fenceCount % 2 === 1;
}
function main() {
console.log('[script-library] Generating Excalidraw Script Library...');
if (!fs.existsSync(EA_SCRIPTS_DIR)) {
console.error('ea-scripts directory not found:', EA_SCRIPTS_DIR);
process.exit(1);
}
if (!fs.existsSync(INDEX_NEW)) {
console.error('index-new.md not found:', INDEX_NEW);
process.exit(1);
}
if (!fs.existsSync(DIST_DIR)) {
fs.mkdirSync(DIST_DIR, { recursive: true });
}
let output = INTRO;
console.log('[script-library] Adding index-new.md');
const indexNewContent = fs.readFileSync(INDEX_NEW, 'utf8');
output += `<!-- BEGIN index-new.md -->\n${indexNewContent.trim()}\n<!-- END index-new.md -->\n\n`;
output += `---\n\n# Script Sources\n`;
// Collect *.md files (non-recursive) excluding index-new.md
const files = fs
.readdirSync(EA_SCRIPTS_DIR, { withFileTypes: true })
.filter(
(d) =>
d.isFile() &&
d.name.endsWith('.md') &&
d.name.toLowerCase() !== 'index-new.md'
)
.map((d) => d.name)
.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
for (const file of files) {
const full = path.join(EA_SCRIPTS_DIR, file);
let content = fs.readFileSync(full, 'utf8');
output += `\n---\n\n## ${file}\n`;
output += `<!-- Source: ea-scripts/${file} -->\n\n`;
// Normalize line endings
content = content.replace(/\r\n/g, '\n');
output += content.trimEnd() + '\n';
if (needsClosingFence(content)) {
output += '```\n';
console.log(`[script-library] Added missing closing fence to ${file}`);
} else {
console.log(`[script-library] Added ${file} (no fence fix needed)`);
}
}
fs.writeFileSync(OUTPUT_FILE, output, 'utf8');
console.log('[script-library] Wrote:', OUTPUT_FILE);
console.log('[script-library] Done.');
}
if (require.main === module) {
try {
main();
} catch (e) {
console.error('[script-library] Failed:', e);
process.exit(1);
}
}
+3 -1
View File
@@ -1,4 +1,4 @@
import { Copy, Crop, Globe, RotateCcw, Scan, Settings, TextSelect } from "lucide-react";
import { Bookmark, Camera, Copy, Crop, Globe, RotateCcw, Scan, Settings, TextSelect } from "lucide-react";
import * as React from "react";
import { PenStyle } from "src/types/penTypes";
@@ -31,6 +31,8 @@ export const ICONS = {
Copy: (<Copy /> ),
Globe: (<Globe />),
Crop: (<Crop />),
Bookmark: (<Bookmark />),
Camera: (<Camera />),
ZoomToSelectedElement: (<Scan />),
Properties: (<Settings />),
ZoomToSection: (
+134 -6
View File
@@ -125,20 +125,148 @@
* @returns {string} - The new filepath for the image including full vault path and extension.
*
* Example usage:
* ```
* onImageFilePathHook: (data) => {
* const { currentImageName, drawingFilePath } = data;
* const ext = currentImageName.split('.').pop();
* // Generate a new filepath based on the drawing file name and other criteria
* return `${drawingFileName} - ${currentImageName || 'image'}.${ext}`;
* }
* ```
* onImageFilePathHook: (data: {
*
* Signiture:
* onImageFilePathHook: (data: {
* currentImageName: string; // Excalidraw generated name of the image, or the name received from the file system.
* drawingFilePath: string; // The full filepath of the Excalidraw file where the image is being used.
* }) => string = null;
*/
//ea.onImageFilePathHook = (data) => {};
// ea.onImageFilePathHook = (data) => { console.log(data); };
/**
* If set, this callback is triggered when the Excalidraw image is being exported to
* .svg, .png, or .excalidraw.
* You can use this callback to customize the naming and path of the images. This allows
* you to place images into an assets folder.
*
* If the function returns null or undefined, the normal Excalidraw operation will continue
* with the currentImageName and in the same folder as the Excalidraw file
* If a filepath is returned, that will be used. Include the full Vault filepath and filename
* with the file extension.
* !!!! If an image already exists on the path, that will be overwritten. When returning
* your own image path, you must take care of unique filenames (if that is a requirement) !!!!
* The current image name is the name generated by Excalidraw:
* - my-drawing.png
* - my-drawing.svg
* - my-drawing.excalidraw
* - my-drawing.dark.svg
* - my-drawing.light.svg
* - my-drawing.dark.png
* - my-drawing.light.png
*
* @param data - An object containing the following properties:
* @property {string} exportFilepath - Default export filepath for the image.
* @property {string} excalidrawFile - TFile: The Excalidraw file being exported.
* @property {string} exportExtension - The file extension of the export (e.g., .dark.svg, .png, .excalidraw).
* @property {string} oldExcalidrawPath - If action === "move" The old path of the Excalidraw file, else undefined
* @property {string} action - The action being performed:
* "export" | "move" | "delete"
* move and delete reference the change to the Excalidraw file.
*
* @returns {string} - The new filepath for the image including full vault path and extension.
*
* action === "move" || action === "delete" is only possible if "keep in sync" is enabled
* in plugin export settings
*
* Example usage:
* onImageFilePathHook: (data) => {
* const { currentImageName, drawingFilePath, frontmatter } = data;
* // Generate a new filepath based on the drawing file name and other criteria
* const ext = currentImageName.split('.').pop();
* if(frontmatter && frontmatter["my-custom-field"]) {
* }
* return `${drawingFileName} - ${currentImageName || 'image'}.${ext}`;
* }
*
*/
/*ea.onImageExportPathHook = (data) => {
//debugger; //remove comment to debug using Developer Console
let {excalidrawFile, exportFilepath, exportExtension, oldExcalidrawPath, action} = data;
const frontmatter = app.metadataCache.getFileCache(excalidrawFile)?.frontmatter;
//console.log(data, frontmatter);
const excalidrawFilename = action === "move"
? ea.splitFolderAndFilename(excalidrawFile.name).filename
: excalidrawFile.name
if(excalidrawFilename.match(/^icon - /i)) {
const {folderpath, filename, basename, extension} = ea.splitFolderAndFilename(exportFilepath);
exportFilepath = "assets/icons/" + filename;
return exportFilepath;
}
if(excalidrawFilename.match(/^stickfigure - /i)) {
const {folderpath, filename, basename, extension} = ea.splitFolderAndFilename(exportFilepath);
exportFilepath = "assets/stickfigures/" + filename;
return exportFilepath;
}
if(excalidrawFilename.match(/^logo - /i)) {
const {folderpath, filename, basename, extension} = ea.splitFolderAndFilename(exportFilepath);
exportFilepath = "assets/logos/" + filename;
return exportFilepath;
}
// !!!! frontmatter will be undefined when action === "delete"
// this means if you base your logic on frontmatter properties, then
// plugin settings keep files in sync will break for those files when
// deleting the Excalidraw file. The images will not be deleted, or worst
// your logic might result in deleting other files. This hook gives you
// powerful control, but the hook function logic requires careful testing
// on your part.
//if(frontmatter && frontmatter["is-asset"]) { //custom frontmatter property
exportFilepath = ea.obsidian.normalizePath("assets/" + exportFilepath);
return exportFilepath;
//}
return exportFilepath;
};*/
/**
* Excalidraw supports auto-export of Excalidraw files to .png, .svg, and .excalidraw formats.
*
* Auto-export of Excalidraw files can be controlled at multiple levels.
* 1) In plugin settings where you can set up default auto-export applicable to all your Excalidraw files.
* 2) However, if you do not want to auto-export every file, you can also control auto-export
* at the file level using the 'excalidraw-autoexport' frontmatter property.
* 3) This hook gives you an additional layer of control over the auto-export process.
*
* This hook is triggered when an Excalidraw file is being saved.
*
* interface AutoexportConfig {
* png: boolean; // Whether to auto-export to PNG
* svg: boolean; // Whether to auto-export to SVG
* excalidraw: boolean; // Whether to auto-export to Excalidraw format
* theme: "light" | "dark" | "both"; // The theme to use for the export
* }
*
* @param {Object} data - The data for the hook.
* @param {AutoexportConfig} data.autoexportConfig - The current autoexport configuration.
* @param {TFile} data.excalidrawFile - The Excalidraw file being auto-exported.
* @returns {AutoexportConfig | null} - Return a modified AutoexportConfig to override the export behavior, or null to use the default.
*/
/*ea.onTriggerAutoexportHook = (data) => {
let {autoexportConfig, excalidrawFile} = data;
const frontmatter = app.metadataCache.getFileCache(excalidrawFile)?.frontmatter;
//console.log(data, frontmatter);
//logic based on filepath and frontmatter
if(excalidrawFile.name.match(/^(?:icon|stickfigure|logo) - /i)) {
autoexportConfig.theme = "light";
autoexportConfig.svg = true;
autoexportConfig.png = false;
autoexportConfig.excalidraw = false;
return autoexportConfig;
}
return autoexportConfig;
};*/
/**
* If set, this callback is triggered whenever the active canvas color changes
@@ -147,5 +275,5 @@
* view: ExcalidrawView, //the excalidraw view
* color: string,
* ) => void = null;
*/
//ea.onCanvasColorChangeHook = (ea, view, color) => {};
*/
//ea.onCanvasColorChangeHook = (ea, view, color) => {};
+63 -29
View File
@@ -1,8 +1,8 @@
import { customAlphabet } from "nanoid";
import { ExcalidrawLib } from "../types/excalidrawLib";
import { moment } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
import { DeviceType } from "src/types/types";
import { errorHandler } from "../utils/ErrorHandler";
//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;
@@ -79,7 +79,7 @@ export const obsidianToExcalidrawMap: { [key: string]: string } = {
'ur': 'ur-PK', // Assuming Pakistan for Urdu
'vi': 'vi-VN',
'zh': 'zh-CN',
'zh-TW': 'zh-TW',
'zh-tw': 'zh-TW',
};
@@ -106,33 +106,65 @@ export let {
getCSSFontDefinition,
loadSceneFonts,
loadMermaid,
syncInvalidIndices,
} = excalidrawLib;
export function updateExcalidrawLib() {
({
sceneCoordsToViewportCoords,
viewportCoordsToSceneCoords,
determineFocusDistance,
intersectElementWithLine,
getCommonBoundingBox,
getMaximumGroups,
measureText,
getLineHeight,
wrapText,
getFontString,
getBoundTextMaxWidth,
exportToSvg,
exportToBlob,
mutateElement,
restore,
mermaidToExcalidraw,
getFontFamilyString,
getContainerElement,
refreshTextDimensions,
getCSSFontDefinition,
loadSceneFonts,
loadMermaid,
} = excalidrawLib);
try {
// First validate that excalidrawLib exists and has the expected methods
if (!excalidrawLib) {
throw new Error("excalidrawLib is undefined");
}
// Check that critical functions exist before assigning them
const requiredFunctions = [
'sceneCoordsToViewportCoords',
'viewportCoordsToSceneCoords',
'determineFocusDistance',
'intersectElementWithLine',
'getCommonBoundingBox',
'measureText',
'getLineHeight',
'restore'
];
for (const fnName of requiredFunctions) {
if (!(fnName in excalidrawLib) || typeof excalidrawLib[fnName as keyof typeof excalidrawLib] !== 'function') {
throw new Error(`Required function ${fnName} is missing from excalidrawLib`);
}
}
// If validation passes, update the exported functions
({
sceneCoordsToViewportCoords,
viewportCoordsToSceneCoords,
determineFocusDistance,
intersectElementWithLine,
getCommonBoundingBox,
getMaximumGroups,
measureText,
getLineHeight,
wrapText,
getFontString,
getBoundTextMaxWidth,
exportToSvg,
exportToBlob,
mutateElement,
restore,
mermaidToExcalidraw,
getFontFamilyString,
getContainerElement,
refreshTextDimensions,
getCSSFontDefinition,
loadSceneFonts,
loadMermaid,
syncInvalidIndices,
} = excalidrawLib);
} catch (error) {
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
}
}
export const FONTS_STYLE_ID = "excalidraw-custom-fonts";
@@ -202,9 +234,10 @@ export const IMAGE_TYPES = ["jpeg", "jpg", "png", "gif", "svg", "webp", "bmp", "
export const ANIMATED_IMAGE_TYPES = ["gif", "webp", "apng", "svg"];
export const EXPORT_TYPES = ["svg", "dark.svg", "light.svg", "png", "dark.png", "light.png"];
export const MAX_IMAGE_SIZE = 500;
export const VIDEO_TYPES = ["mp4", "webm", "ogv", "mov", "mkv"];
export const AUDIO_TYPES = ["mp3", "wav", "m4a", "3gp", "flac", "ogg", "oga", "opus"];
export const CARD_WIDTH = 400;
export const CARD_HEIGHT = 500;
export const VIDEO_TYPES = ["mp4","webm","ogv","mov","mkv","avi","m4v","wmv"];
export const AUDIO_TYPES = ["mp3","wav", "m4a", "3gp", "flac", "ogg", "oga", "opus", "aac", "aiff", "aif", "mid", "midi"];
export const CODE_TYPES = ["json", "css", "js"];
export const FRONTMATTER_KEYS:{[key:string]: {name: string, type: string, depricated?:boolean}} = {
@@ -230,6 +263,7 @@ export const FRONTMATTER_KEYS:{[key:string]: {name: string, type: string, depric
"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"},
};
export const CaptureUpdateAction = {
+1 -1
View File
@@ -7,4 +7,4 @@ window.navigator.clipboard.writeText(`export const startupScript = () => atob("$
console.log("String copied to clipboard");
*/
export const startupScript = () => atob("LyoKI2V4Y2x1ZGUKYGBganMqLwovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCB3aGVuIHRoZSB1c2VyIGNsb3NlcyBhbiBFeGNhbGlkcmF3IHZpZXcuCiAqICAgb25WaWV3VW5sb2FkSG9vazogKHZpZXc6IEV4Y2FsaWRyYXdWaWV3KSA9PiB2b2lkID0gbnVsbDsKICovCi8vZWEub25WaWV3VW5sb2FkSG9vayA9ICh2aWV3KSA9PiB7fTsKCi8qKgogKiBJZiBzZXQsIHRoaXMgY2FsbGJhY2sgaXMgdHJpZ2dlcmVkLCB3aGVuIHRoZSB1c2VyIGNoYW5nZXMgdGhlIHZpZXcgbW9kZS4KICogWW91IGNhbiB1c2UgdGhpcyBjYWxsYmFjayBpbiBjYXNlIHlvdSB3YW50IHRvIGRvIHNvbWV0aGluZyBhZGRpdGlvbmFsIHdoZW4gdGhlIHVzZXIgc3dpdGNoZXMgdG8gdmlldyBtb2RlIGFuZCBiYWNrLgogKiAgIG9uVmlld01vZGVDaGFuZ2VIb29rOiAoaXNWaWV3TW9kZUVuYWJsZWQ6Ym9vbGVhbiwgdmlldzogRXhjYWxpZHJhd1ZpZXcsIGVhOiBFeGNhbGlkcmF3QXV0b21hdGUpID0+IHZvaWQgPSBudWxsOwogKi8KLy9lYS5vblZpZXdNb2RlQ2hhbmdlSG9vayA9IChpc1ZpZXdNb2RlRW5hYmxlZCwgdmlldywgZWEpID0+IHt9OwoKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gdGhlIHVzZXIgaG92ZXJzIGEgbGluayBpbiB0aGUgc2NlbmUuCiAqIFlvdSBjYW4gdXNlIHRoaXMgY2FsbGJhY2sgaW4gY2FzZSB5b3Ugd2FudCB0byBkbyBzb21ldGhpbmcgYWRkaXRpb25hbCB3aGVuIHRoZSBvbkxpbmtIb3ZlciBldmVudCBvY2N1cnMuCiAqIFRoaXMgY2FsbGJhY2sgbXVzdCByZXR1cm4gYSBib29sZWFuIHZhbHVlLgogKiBJbiBjYXNlIHlvdSB3YW50IHRvIHByZXZlbnQgdGhlIGV4Y2FsaWRyYXcgb25MaW5rSG92ZXIgYWN0aW9uIHlvdSBtdXN0IHJldHVybiBmYWxzZSwgaXQgd2lsbCBzdG9wIHRoZSBuYXRpdmUgZXhjYWxpZHJhdyBvbkxpbmtIb3ZlciBtYW5hZ2VtZW50IGZsb3cuCiAqICAgb25MaW5rSG92ZXJIb29rOiAoCiAqICAgICBlbGVtZW50OiBOb25EZWxldGVkRXhjYWxpZHJhd0VsZW1lbnQsCiAqICAgICBsaW5rVGV4dDogc3RyaW5nLAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXcsCiAqICAgICBlYTogRXhjYWxpZHJhd0F1dG9tYXRlCiAqICAgKSA9PiBib29sZWFuID0gbnVsbDsKICovCi8vZWEub25MaW5rSG92ZXJIb29rID0gKGVsZW1lbnQsIGxpbmtUZXh0LCB2aWV3LCBlYSkgPT4ge307CiAgIAovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCwgd2hlbiB0aGUgdXNlciBjbGlja3MgYSBsaW5rIGluIHRoZSBzY2VuZS4KICogWW91IGNhbiB1c2UgdGhpcyBjYWxsYmFjayBpbiBjYXNlIHlvdSB3YW50IHRvIGRvIHNvbWV0aGluZyBhZGRpdGlvbmFsIHdoZW4gdGhlIG9uTGlua0NsaWNrIGV2ZW50IG9jY3Vycy4KICogVGhpcyBjYWxsYmFjayBtdXN0IHJldHVybiBhIGJvb2xlYW4gdmFsdWUuCiAqIEluIGNhc2UgeW91IHdhbnQgdG8gcHJldmVudCB0aGUgZXhjYWxpZHJhdyBvbkxpbmtDbGljayBhY3Rpb24geW91IG11c3QgcmV0dXJuIGZhbHNlLCBpdCB3aWxsIHN0b3AgdGhlIG5hdGl2ZSBleGNhbGlkcmF3IG9uTGlua0NsaWNrIG1hbmFnZW1lbnQgZmxvdy4KICogICBvbkxpbmtDbGlja0hvb2s6KAogKiAgICAgZWxlbWVudDogRXhjYWxpZHJhd0VsZW1lbnQsCiAqICAgICBsaW5rVGV4dDogc3RyaW5nLAogKiAgICAgZXZlbnQ6IE1vdXNlRXZlbnQsCiAqICAgICB2aWV3OiBFeGNhbGlkcmF3VmlldywKICogICAgIGVhOiBFeGNhbGlkcmF3QXV0b21hdGUKICogICApID0+IGJvb2xlYW4gPSBudWxsOwogKi8KLy9lYS5vbkxpbmtDbGlja0hvb2sgPSAoZWxlbWVudCxsaW5rVGV4dCxldmVudCwgdmlldywgZWEpID0+IHt9OwogICAKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gRXhjYWxpZHJhdyByZWNlaXZlcyBhbiBvbkRyb3AgZXZlbnQuIAogKiBZb3UgY2FuIHVzZSB0aGlzIGNhbGxiYWNrIGluIGNhc2UgeW91IHdhbnQgdG8gZG8gc29tZXRoaW5nIGFkZGl0aW9uYWwgd2hlbiB0aGUgb25Ecm9wIGV2ZW50IG9jY3Vycy4KICogVGhpcyBjYWxsYmFjayBtdXN0IHJldHVybiBhIGJvb2xlYW4gdmFsdWUuCiAqIEluIGNhc2UgeW91IHdhbnQgdG8gcHJldmVudCB0aGUgZXhjYWxpZHJhdyBvbkRyb3AgYWN0aW9uIHlvdSBtdXN0IHJldHVybiBmYWxzZSwgaXQgd2lsbCBzdG9wIHRoZSBuYXRpdmUgZXhjYWxpZHJhdyBvbkRyb3AgbWFuYWdlbWVudCBmbG93LgogKiAgIG9uRHJvcEhvb2s6IChkYXRhOiB7CiAqICAgICBlYTogRXhjYWxpZHJhd0F1dG9tYXRlOwogKiAgICAgZXZlbnQ6IFJlYWN0LkRyYWdFdmVudDxIVE1MRGl2RWxlbWVudD47CiAqICAgICBkcmFnZ2FibGU6IGFueTsgLy9PYnNpZGlhbiBkcmFnZ2FibGUgb2JqZWN0CiAqICAgICB0eXBlOiAiZmlsZSIgfCAidGV4dCIgfCAidW5rbm93biI7CiAqICAgICBwYXlsb2FkOiB7CiAqICAgICAgIGZpbGVzOiBURmlsZVtdOyAvL1RGaWxlW10gYXJyYXkgb2YgZHJvcHBlZCBmaWxlcwogKiAgICAgICB0ZXh0OiBzdHJpbmc7IC8vc3RyaW5nCiAqICAgICB9OwogKiAgICAgZXhjYWxpZHJhd0ZpbGU6IFRGaWxlOyAvL3RoZSBmaWxlIHJlY2VpdmluZyB0aGUgZHJvcCBldmVudAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXc7IC8vdGhlIGV4Y2FsaWRyYXcgdmlldyByZWNlaXZpbmcgdGhlIGRyb3AKICogICAgIHBvaW50ZXJQb3NpdGlvbjogeyB4OiBudW1iZXI7IHk6IG51bWJlciB9OyAvL3RoZSBwb2ludGVyIHBvc2l0aW9uIG9uIGNhbnZhcyBhdCB0aGUgdGltZSBvZiBkcm9wCiAqICAgfSkgPT4gYm9vbGVhbiA9IG51bGw7CiAqLwovL2VhLm9uRHJvcEhvb2sgPSAoZGF0YSkgPT4ge307CiAKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gRXhjYWxpZHJhdyByZWNlaXZlcyBhbiBvblBhc3RlIGV2ZW50LgogKiBZb3UgY2FuIHVzZSB0aGlzIGNhbGxiYWNrIGluIGNhc2UgeW91IHdhbnQgdG8gZG8gc29tZXRoaW5nIGFkZGl0aW9uYWwgd2hlbiB0aGUKICogb25QYXN0ZSBldmVudCBvY2N1cnMuCiAqIFRoaXMgY2FsbGJhY2sgbXVzdCByZXR1cm4gYSBib29sZWFuIHZhbHVlLgogKiBJbiBjYXNlIHlvdSB3YW50IHRvIHByZXZlbnQgdGhlIGV4Y2FsaWRyYXcgb25QYXN0ZSBhY3Rpb24geW91IG11c3QgcmV0dXJuIGZhbHNlLAogKiBpdCB3aWxsIHN0b3AgdGhlIG5hdGl2ZSBleGNhbGlkcmF3IG9uUGFzdGUgbWFuYWdlbWVudCBmbG93LgogKiAgIG9uUGFzdGVIb29rOiAoZGF0YTogewogKiAgICAgZWE6IEV4Y2FsaWRyYXdBdXRvbWF0ZTsKICogICAgIHBheWxvYWQ6IENsaXBib2FyZERhdGE7CiAqICAgICBldmVudDogQ2xpcGJvYXJkRXZlbnQ7CiAqICAgICBleGNhbGlkcmF3RmlsZTogVEZpbGU7IC8vdGhlIGZpbGUgcmVjZWl2aW5nIHRoZSBwYXN0ZSBldmVudAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXc7IC8vdGhlIGV4Y2FsaWRyYXcgdmlldyByZWNlaXZpbmcgdGhlIHBhc3RlCiAqICAgICBwb2ludGVyUG9zaXRpb246IHsgeDogbnVtYmVyOyB5OiBudW1iZXIgfTsgLy90aGUgcG9pbnRlciBwb3NpdGlvbiBvbiBjYW52YXMKICogICB9KSA9PiBib29sZWFuID0gbnVsbDsKICovCi8vZWEub25QYXN0ZUhvb2sgPSAoZGF0YSkgPT4ge307CgovKioKICogaWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCLine truncated
export const startupScript = () => atob("LyoKI2V4Y2x1ZGUKYGBganMqLwovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCB3aGVuIHRoZSB1c2VyIGNsb3NlcyBhbiBFeGNhbGlkcmF3IHZpZXcuCiAqICAgb25WaWV3VW5sb2FkSG9vazogKHZpZXc6IEV4Y2FsaWRyYXdWaWV3KSA9PiB2b2lkID0gbnVsbDsKICovCi8vZWEub25WaWV3VW5sb2FkSG9vayA9ICh2aWV3KSA9PiB7fTsKCi8qKgogKiBJZiBzZXQsIHRoaXMgY2FsbGJhY2sgaXMgdHJpZ2dlcmVkLCB3aGVuIHRoZSB1c2VyIGNoYW5nZXMgdGhlIHZpZXcgbW9kZS4KICogWW91IGNhbiB1c2UgdGhpcyBjYWxsYmFjayBpbiBjYXNlIHlvdSB3YW50IHRvIGRvIHNvbWV0aGluZyBhZGRpdGlvbmFsIHdoZW4gdGhlIHVzZXIgc3dpdGNoZXMgdG8gdmlldyBtb2RlIGFuZCBiYWNrLgogKiAgIG9uVmlld01vZGVDaGFuZ2VIb29rOiAoaXNWaWV3TW9kZUVuYWJsZWQ6Ym9vbGVhbiwgdmlldzogRXhjYWxpZHJhd1ZpZXcsIGVhOiBFeGNhbGlkcmF3QXV0b21hdGUpID0+IHZvaWQgPSBudWxsOwogKi8KLy9lYS5vblZpZXdNb2RlQ2hhbmdlSG9vayA9IChpc1ZpZXdNb2RlRW5hYmxlZCwgdmlldywgZWEpID0+IHt9OwoKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gdGhlIHVzZXIgaG92ZXJzIGEgbGluayBpbiB0aGUgc2NlbmUuCiAqIFlvdSBjYW4gdXNlIHRoaXMgY2FsbGJhY2sgaW4gY2FzZSB5b3Ugd2FudCB0byBkbyBzb21ldGhpbmcgYWRkaXRpb25hbCB3aGVuIHRoZSBvbkxpbmtIb3ZlciBldmVudCBvY2N1cnMuCiAqIFRoaXMgY2FsbGJhY2sgbXVzdCByZXR1cm4gYSBib29sZWFuIHZhbHVlLgogKiBJbiBjYXNlIHlvdSB3YW50IHRvIHByZXZlbnQgdGhlIGV4Y2FsaWRyYXcgb25MaW5rSG92ZXIgYWN0aW9uIHlvdSBtdXN0IHJldHVybiBmYWxzZSwgaXQgd2lsbCBzdG9wIHRoZSBuYXRpdmUgZXhjYWxpZHJhdyBvbkxpbmtIb3ZlciBtYW5hZ2VtZW50IGZsb3cuCiAqICAgb25MaW5rSG92ZXJIb29rOiAoCiAqICAgICBlbGVtZW50OiBOb25EZWxldGVkRXhjYWxpZHJhd0VsZW1lbnQsCiAqICAgICBsaW5rVGV4dDogc3RyaW5nLAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXcsCiAqICAgICBlYTogRXhjYWxpZHJhd0F1dG9tYXRlCiAqICAgKSA9PiBib29sZWFuID0gbnVsbDsKICovCi8vZWEub25MaW5rSG92ZXJIb29rID0gKGVsZW1lbnQsIGxpbmtUZXh0LCB2aWV3LCBlYSkgPT4ge307CiAgIAovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCwgd2hlbiB0aGUgdXNlciBjbGlja3MgYSBsaW5rIGluIHRoZSBzY2VuZS4KICogWW91IGNhbiB1c2UgdGhpcyBjYWxsYmFjayBpbiBjYXNlIHlvdSB3YW50IHRvIGRvIHNvbWV0aGluZyBhZGRpdGlvbmFsIHdoZW4gdGhlIG9uTGlua0NsaWNrIGV2ZW50IG9jY3Vycy4KICogVGhpcyBjYWxsYmFjayBtdXN0IHJldHVybiBhIGJvb2xlYW4gdmFsdWUuCiAqIEluIGNhc2UgeW91IHdhbnQgdG8gcHJldmVudCB0aGUgZXhjYWxpZHJhdyBvbkxpbmtDbGljayBhY3Rpb24geW91IG11c3QgcmV0dXJuIGZhbHNlLCBpdCB3aWxsIHN0b3AgdGhlIG5hdGl2ZSBleGNhbGlkcmF3IG9uTGlua0NsaWNrIG1hbmFnZW1lbnQgZmxvdy4KICogICBvbkxpbmtDbGlja0hvb2s6KAogKiAgICAgZWxlbWVudDogRXhjYWxpZHJhd0VsZW1lbnQsCiAqICAgICBsaW5rVGV4dDogc3RyaW5nLAogKiAgICAgZXZlbnQ6IE1vdXNlRXZlbnQsCiAqICAgICB2aWV3OiBFeGNhbGlkcmF3VmlldywKICogICAgIGVhOiBFeGNhbGlkcmF3QXV0b21hdGUKICogICApID0+IGJvb2xlYW4gPSBudWxsOwogKi8KLy9lYS5vbkxpbmtDbGlja0hvb2sgPSAoZWxlbWVudCxsaW5rVGV4dCxldmVudCwgdmlldywgZWEpID0+IHt9OwogICAKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gRXhjYWxpZHJhdyByZWNlaXZlcyBhbiBvbkRyb3AgZXZlbnQuIAogKiBZb3UgY2FuIHVzZSB0aGlzIGNhbGxiYWNrIGluIGNhc2UgeW91IHdhbnQgdG8gZG8gc29tZXRoaW5nIGFkZGl0aW9uYWwgd2hlbiB0aGUgb25Ecm9wIGV2ZW50IG9jY3Vycy4KICogVGhpcyBjYWxsYmFjayBtdXN0IHJldHVybiBhIGJvb2xlYW4gdmFsdWUuCiAqIEluIGNhc2UgeW91IHdhbnQgdG8gcHJldmVudCB0aGUgZXhjYWxpZHJhdyBvbkRyb3AgYWN0aW9uIHlvdSBtdXN0IHJldHVybiBmYWxzZSwgaXQgd2lsbCBzdG9wIHRoZSBuYXRpdmUgZXhjYWxpZHJhdyBvbkRyb3AgbWFuYWdlbWVudCBmbG93LgogKiAgIG9uRHJvcEhvb2s6IChkYXRhOiB7CiAqICAgICBlYTogRXhjYWxpZHJhd0F1dG9tYXRlOwogKiAgICAgZXZlbnQ6IFJlYWN0LkRyYWdFdmVudDxIVE1MRGl2RWxlbWVudD47CiAqICAgICBkcmFnZ2FibGU6IGFueTsgLy9PYnNpZGlhbiBkcmFnZ2FibGUgb2JqZWN0CiAqICAgICB0eXBlOiAiZmlsZSIgfCAidGV4dCIgfCAidW5rbm93biI7CiAqICAgICBwYXlsb2FkOiB7CiAqICAgICAgIGZpbGVzOiBURmlsZVtdOyAvL1RGaWxlW10gYXJyYXkgb2YgZHJvcHBlZCBmaWxlcwogKiAgICAgICB0ZXh0OiBzdHJpbmc7IC8vc3RyaW5nCiAqICAgICB9OwogKiAgICAgZXhjYWxpZHJhd0ZpbGU6IFRGaWxlOyAvL3RoZSBmaWxlIHJlY2VpdmluZyB0aGUgZHJvcCBldmVudAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXc7IC8vdGhlIGV4Y2FsaWRyYXcgdmlldyByZWNlaXZpbmcgdGhlIGRyb3AKICogICAgIHBvaW50ZXJQb3NpdGlvbjogeyB4OiBudW1iZXI7IHk6IG51bWJlciB9OyAvL3RoZSBwb2ludGVyIHBvc2l0aW9uIG9uIGNhbnZhcyBhdCB0aGUgdGltZSBvZiBkcm9wCiAqICAgfSkgPT4gYm9vbGVhbiA9IG51bGw7CiAqLwovL2VhLm9uRHJvcEhvb2sgPSAoZGF0YSkgPT4ge307CiAKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gRXhjYWxpZHJhdyByZWNlaXZlcyBhbiBvblBhc3RlIGV2ZW50LgogKiBZb3UgY2FuIHVzZSB0aGlzIGNhbGxiYWNrIGluIGNhc2UgeW91IHdhbnQgdG8gZG8gc29tZXRoaW5nIGFkZGl0aW9uYWwgd2hlbiB0aGUKICogb25QYXN0ZSBldmVudCBvY2N1cnMuCiAqIFRoaXMgY2FsbGJhY2sgbXVzdCByZXR1cm4gYSBib29sZWFuIHZhbHVlLgogKiBJbiBjYXNlIHlvdSB3YW50IHRvIHByZXZlbnQgdGhlIGV4Y2FsaWRyYXcgb25QYXN0ZSBhY3Rpb24geW91IG11c3QgcmV0dXJuIGZhbHNlLAogKiBpdCB3aWxsIHN0b3AgdGhlIG5hdGl2ZSBleGNhbGlkcmF3IG9uUGFzdGUgbWFuYWdlbWVudCBmbG93LgogKiAgIG9uUGFzdGVIb29rOiAoZGF0YTogewogKiAgICAgZWE6IEV4Y2FsaWRyYXdBdXRvbWF0ZTsKICogICAgIHBheWxvYWQ6IENsaXBib2FyZERhdGE7CiAqICAgICBldmVudDogQ2xpcGJvYXJkRXZlbnQ7CiAqICAgICBleGNhbGlkcmF3RmlsZTogVEZpbGU7IC8vdGhlIGZpbGUgcmVjZWl2aW5nIHRoZSBwYXN0ZSBldmVudAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXc7IC8vdGhlIGV4Y2FsaWRyYXcgdmlldyByZWNlaXZpbmcgdGhlIHBhc3RlCiAqICAgICBwb2ludGVyUG9zaXRpb246IHsgeDogbnVtYmVyOyB5OiBudW1iZXIgfTsgLy90aGUgcG9pbnRlciBwb3NpdGlvbiBvbiBjYW52YXMKICogICB9KSA9PiBib29sZWFuID0gbnVsbDsKICovCi8vZWEub25QYXN0ZUhvb2sgPSAoZGF0YSkgPT4ge307CgovKioKICogaWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCLine truncated
+1 -1
View File
@@ -2,7 +2,7 @@ import "obsidian";
//import { ExcalidrawAutomate } from "./ExcalidrawAutomate";
//export ExcalidrawAutomate from "./ExcalidrawAutomate";
//export {ExcalidrawAutomate} from "./ExcaildrawAutomate";
export type { ExcalidrawBindableElement, ExcalidrawElement, FileId, FillStyle, StrokeRoundness, StrokeStyle } from "@zsviczian/excalidraw/types/excalidraw/element/types";
export type { ExcalidrawBindableElement, ExcalidrawElement, FileId, FillStyle, StrokeRoundness, StrokeStyle } from "@zsviczian/excalidraw/types/element/src/types";
export type { Point } from "src/types/types";
export const getEA = (view?:any): any => {
try {
+47 -12
View File
@@ -40,11 +40,11 @@ import {
} from "../constants/constants";
import { ExcalidrawSettings, DEFAULT_SETTINGS, ExcalidrawSettingTab } from "./settings";
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
import { initExcalidrawAutomate } from "src/utils/excalidrawAutomateUtils";
import { initExcalidrawAutomate, insertLaTeXToView } from "src/utils/excalidrawAutomateUtils";
import { around, dedupe } from "monkey-around";
import { t } from "../lang/helpers";
import {
checkAndCreateFolder,
createOrOverwriteFile,
fileShouldDefaultAsExcalidraw,
getDrawingFilename,
getIMGFilename,
@@ -61,7 +61,7 @@ import {
getFontMetrics,
} from "../utils/utils";
import { foldExcalidrawSection, getExcalidrawViews, setExcalidrawView } from "../utils/obsidianUtils";
import { FileId } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
import { ScriptEngine } from "../shared/Scripts";
import { hoverEvent, initializeMarkdownPostProcessor, markdownPostProcessor, legacyExcalidrawPopoverObserver } from "./managers/MarkdownPostProcessor";
import { FieldSuggester } from "../shared/Suggesters/FieldSuggester";
@@ -88,6 +88,8 @@ import { PackageManager } from "./managers/PackageManager";
import ExcalidrawView from "../view/ExcalidrawView";
import { CommandManager } from "./managers/CommandManager";
import { EventManager } from "./managers/EventManager";
import { UniversalInsertFileModal } from "src/shared/Dialogs/UniversalInsertFileModal";
import en from "src/lang/locale/en";
declare const PLUGIN_VERSION:string;
declare const INITIAL_TIMESTAMP: number;
@@ -566,7 +568,7 @@ export default class ExcalidrawPlugin extends Plugin {
}
}
this.packageManager.getPackageMap().forEach(({excalidrawLib}) => {
(excalidrawLib as typeof ExcalidrawLib).registerLocalFont({metrics: fontMetrics as any, icon: null}, fourthFontDataURL);
(excalidrawLib as typeof ExcalidrawLib).registerLocalFont({metrics: fontMetrics as any}, fourthFontDataURL);
});
// Add fonts to open Obsidian documents
for(const ownerDocument of this.getOpenObsidianDocuments()) {
@@ -738,13 +740,7 @@ export default class ExcalidrawPlugin extends Plugin {
if (!data || data.startsWith("404: Not Found")) {
return null;
}
if (file) {
await this.app.vault.modify(file as TFile, data);
} else {
await checkAndCreateFolder(folder);
file = await this.app.vault.create(localPath, data);
}
return file;
return await createOrOverwriteFile(this.app, file?.path ?? localPath, data);
};
try {
@@ -894,7 +890,8 @@ export default class ExcalidrawPlugin extends Plugin {
normalizePath(file.path.substring(0, file.path.lastIndexOf(file.name))),
);
log(fname);
const result = await this.app.vault.create(
const result = await createOrOverwriteFile(
this.app,
fname,
FRONTMATTER + (await this.fileManager.exportSceneToMD(data, false)),
);
@@ -1078,6 +1075,19 @@ export default class ExcalidrawPlugin extends Plugin {
this.eventManager.onActiveLeafChangeHandler(leaf);
}
public setDebounceActiveLeafChangeHandler() {
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) {
@@ -1447,4 +1457,29 @@ export default class ExcalidrawPlugin extends Plugin {
public updateFileCache(file: TFile, frontmatter: FrontMatterCache) {
this.fileManager.updateFileCache(file, frontmatter);
}
//used by obsidianUtils in the Excalidraw Pacakge
//aweful coding, but does the job
public runAction(action: "anyFile" | "LaTeX" | "card") {
if(!this.activeExcalidrawView) return;
switch (action) {
case "anyFile":
this.activeExcalidrawView.setCurrentPositionToCenter();
const insertFileModal = new UniversalInsertFileModal(this, this.activeExcalidrawView);
insertFileModal.open();
break;
case "LaTeX":
insertLaTeXToView(this.activeExcalidrawView, true);
break;
case "card":
this.activeExcalidrawView.insertBackOfTheNoteCard(true);
break;
}
}
//used by obsidianUtils in the Excalidraw Pacakge
//aweful coding, but does the job
public getLabel(key: keyof typeof en): string {
return t(key);
}
}
+44 -30
View File
@@ -34,6 +34,7 @@ import { insertLaTeXToView, search } from "src/utils/excalidrawAutomateUtils";
import { templatePromt } from "../../shared/Dialogs/Prompt";
import { t } from "../../lang/helpers";
import {
createOrOverwriteFile,
getAliasWithSize,
getAnnotationFileNameAndFolder,
getCropFileNameAndFolder,
@@ -51,7 +52,7 @@ import {
getImageSize,
} from "../../utils/utils";
import { extractSVGPNGFileName, getActivePDFPageNumberFromPDFView, getAttachmentsFolderAndFilePath, isObsidianThemeDark, mergeMarkdownFiles, setExcalidrawView } from "../../utils/obsidianUtils";
import { ExcalidrawElement, ExcalidrawEmbeddableElement, ExcalidrawImageElement, ExcalidrawTextElement, FileId } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { ExcalidrawElement, ExcalidrawEmbeddableElement, ExcalidrawImageElement, ExcalidrawTextElement, FileId } from "@zsviczian/excalidraw/types/element/src/types";
import { ReleaseNotes } from "../../shared/Dialogs/ReleaseNotes";
import { ScriptInstallPrompt } from "../../shared/Dialogs/ScriptInstallPrompt";
import Taskbone from "../../shared/OCR/Taskbone";
@@ -64,12 +65,11 @@ import { EmbeddableSettings } from "../../shared/Dialogs/EmbeddableSettings";
import { processLinkText } from "../../utils/customEmbeddableUtils";
import { getEA } from "src/core";
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { carveOutImage, carveOutPDF, createImageCropperFile } from "../../utils/carveout";
import { showFrameSettings } from "../../shared/Dialogs/FrameSettings";
import { insertImageToView } from "../../utils/excalidrawViewUtils";
import ExcalidrawPlugin from "src/core/main";
import { get } from "http";
declare const PLUGIN_VERSION:string;
@@ -258,7 +258,7 @@ export class CommandManager {
new Notice("The compressed string is corrupted. Unable to decompress data.");
return;
}
await this.app.vault.modify(activeFile,header + decompressed + "\n```\n%%" + compressed[1]);
await createOrOverwriteFile(this.app, activeFile.path,header + decompressed + "\n```\n%%" + compressed[1]);
})();
}
@@ -355,7 +355,16 @@ export class CommandManager {
if(excalidrawFname.endsWith(".light.md")) {
excalidrawFile = this.app.metadataCache.getFirstLinkpathDest(excalidrawFname.replace(/\.light\.md$/,".md"), view.file.path);
}
if(!excalidrawFile) return false;
//handles the case if the png or svg is not in the same folder as the excalidraw file
if(!excalidrawFile) {
const basename = imgFile.basename.replace(/(?:\.dark|\.light)$/,"");
const candidates = this.app.vault.getMarkdownFiles().filter(f=>f.basename === basename);
if(candidates.length === 1) {
excalidrawFile = candidates[0];
} else {
return false;
}
}
}
if(checking) return true;
this.plugin.openDrawing(excalidrawFile, "new-tab", true);
@@ -700,7 +709,7 @@ export class CommandManager {
}
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (view) {
showFrameSettings(getEA(view));
showFrameSettings(view);
return true;
}
return false;
@@ -772,20 +781,19 @@ export class CommandManager {
checkCallback: (checking:boolean) => this.plugin.forceSaveActiveView(checking),
})
//removing raw mode. Not required. I never use it. Raw mode can still be enabled
//via document properties. Only showing command palette action if raw mode is enabled
this.addCommand({
id: "toggle-lock",
name: t("TOGGLE_LOCK"),
checkCallback: (checking: boolean) => {
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (checking) {
if (
Boolean(this.app.workspace.getActiveViewOfType(ExcalidrawView))
) {
return !(this.app.workspace.getActiveViewOfType(ExcalidrawView))
.compatibilityMode;
if (view) {
return !view.compatibilityMode && view.textMode === TextMode.raw;
}
return false;
}
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (view && !view.compatibilityMode) {
view.changeTextMode(
view.textMode === TextMode.parsed ? TextMode.raw : TextMode.parsed,
@@ -1038,8 +1046,13 @@ export class CommandManager {
x:Math.max(0,centerX - width/2 + view.ownerWindow.screenX),
y:Math.max(0,centerY - height/2 + view.ownerWindow.screenY),
}
const focusOnFileTab = this.settings.focusOnFileTab;
//override focusOnFileTab for popout windows
if(DEVICE.isDesktop) {
this.settings.focusOnFileTab = false;
}
this.plugin.openDrawing(ef.file, DEVICE.isMobile ? "new-tab":"popout-window", true, undefined, false, {x,y,width,height});
this.settings.focusOnFileTab = focusOnFileTab;
}
})
@@ -1267,7 +1280,7 @@ export class CommandManager {
if(!excalidrawView.excalidrawAPI) return false;
const embeddables = excalidrawView.getViewSelectedElements().filter(el=>el.type==="embeddable");
const imageEls = excalidrawView.getViewSelectedElements().filter(el=>el.type==="image");
const isPDF = (imageEls.length === 0 && embeddables.length === 1 && excalidrawView.getEmbeddableLeafElementById(embeddables[0].id)?.leaf?.view?.getViewType() === "pdf")
const isPDF = (imageEls.length === 0 && embeddables.length === 1 && excalidrawView.getEmbeddableLeafElementById(embeddables[0].id)?.node?.child?.file?.extension === "pdf")
const isImage = (imageEls.length === 1 && embeddables.length === 0)
if(!isPDF && !isImage) {
@@ -1276,7 +1289,7 @@ export class CommandManager {
return false;
}
const page = isPDF ? getActivePDFPageNumberFromPDFView(excalidrawView.getEmbeddableLeafElementById(embeddables[0].id)?.leaf?.view) : undefined;
const page = isPDF ? getActivePDFPageNumberFromPDFView(excalidrawView.getEmbeddableLeafElementById(embeddables[0].id)?.node?.child) : undefined;
if(isPDF && !page) {
return false;
}
@@ -1286,8 +1299,8 @@ export class CommandManager {
if(isPDF) {
const embeddableEl = embeddables[0] as ExcalidrawEmbeddableElement;
const ea = new ExcalidrawAutomate(this.plugin,excalidrawView);
const view = excalidrawView.getEmbeddableLeafElementById(embeddableEl.id)?.leaf?.view;
const pdfFile: TFile = view && (view instanceof FileView) ? view.file : undefined;
const view = excalidrawView.getEmbeddableLeafElementById(embeddableEl.id)?.node?.child;
const pdfFile: TFile = view?.file;
carveOutPDF(ea, embeddableEl, `${pdfFile?.path}#page=${page}`, pdfFile);
return;
}
@@ -1693,15 +1706,19 @@ export class CommandManager {
const PDFLink = this.plugin.getLastActivePDFPageLink(view.file);
if(!PDFLink) return false;
if(checking) return true;
const ea = getEA(view);
insertImageToView(
ea,
view.currentPosition,
PDFLink,
undefined,
undefined,
true,
);
(async()=>{
const ea = getEA(view) as ExcalidrawAutomate;
const id = await insertImageToView(
ea,
view.currentPosition,
PDFLink,
undefined,
undefined,
true,
);
ea.selectElementsInView([id]);
ea.destroy()
})();
},
});
@@ -1818,10 +1835,7 @@ export class CommandManager {
const template = await this.plugin.getBlankDrawing();
const target = await this.app.vault.read(activeFile);
const mergedTarget = mergeMarkdownFiles(template, target);
await this.app.vault.modify(
activeFile,
mergedTarget,
);
await createOrOverwriteFile(this.app, activeFile.path, mergedTarget);
setExcalidrawView(activeView.leaf);
})();
},
+15 -1
View File
@@ -1,5 +1,5 @@
import { WorkspaceLeaf, TFile, Editor, MarkdownView, MarkdownFileInfo, MetadataCache, App, EventRef, Menu, FileView } from "obsidian";
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import { getLink } from "../../utils/fileUtils";
import { editorInsertText, getExcalidrawViews, getParentOfClass, isUnwantedLeaf, setExcalidrawView } from "../../utils/obsidianUtils";
import ExcalidrawPlugin from "src/core/main";
@@ -21,6 +21,7 @@ export class EventManager {
private removeEventLisnters:(()=>void)[] = []; //only used if I register an event directly, not via Obsidian's registerEvent
private previouslyActiveLeaf: WorkspaceLeaf;
private splitViewLeafSwitchTimestamp: number = 0;
private debunceActiveLeafChangeHandlerTimer: number|null = null;
get settings() {
return this.plugin.settings;
@@ -103,6 +104,15 @@ export class EventManager {
this.plugin.registerEvent(this.plugin.app.workspace.on("editor-menu", this.onEditorMenuHandler.bind(this)));
}
public setDebounceActiveLeafChangeHandler() {
if(this.debunceActiveLeafChangeHandlerTimer) {
window.clearTimeout(this.debunceActiveLeafChangeHandlerTimer);
}
this.debunceActiveLeafChangeHandlerTimer = window.setTimeout(() => {
this.debunceActiveLeafChangeHandlerTimer = null;
}, 50);
}
private onLayoutChangeHandler() {
getExcalidrawViews(this.app).forEach(excalidrawView=>excalidrawView.refresh());
}
@@ -164,6 +174,10 @@ export class EventManager {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.onActiveLeafChangeHandler,`onActiveLeafChangeEventHandler`, leaf);
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/723
if(this.debunceActiveLeafChangeHandlerTimer) {
return;
}
//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)) {
+146 -29
View File
@@ -6,10 +6,11 @@ import { changeThemeOfExcalidrawMD, ExcalidrawData, getMarkdownDrawingSection }
import ExcalidrawView, { getTextMode } from "src/view/ExcalidrawView";
import ExcalidrawPlugin from "src/core/main";
import { DEBUGGING } from "src/utils/debugHelper";
import { checkAndCreateFolder, download, getIMGFilename, getLink, getListOfTemplateFiles, getNewUniqueFilepath } from "src/utils/fileUtils";
import { checkAndCreateFolder, createFileAndAwaitMetacacheUpdate, download, getIMGFilename, getLink, getListOfTemplateFiles, getNewUniqueFilepath } from "src/utils/fileUtils";
import { PaneTarget } from "src/utils/modifierkeyHelper";
import { getExcalidrawViews, getNewOrAdjacentLeaf, isObsidianThemeDark, openLeaf } from "src/utils/obsidianUtils";
import { errorlog, getExportTheme } from "src/utils/utils";
import { imageCache } from "src/shared/ImageCache";
export class PluginFileManager {
private plugin: ExcalidrawPlugin;
@@ -172,28 +173,71 @@ export class PluginFileManager {
? ""
: theme + ".";
const imageRelativePath = getIMGFilename(
excalidrawRelativePath,
theme+this.settings.embedType.toLowerCase(),
);
const imageFullpath = getIMGFilename(
const exportExtension = theme+this.settings.embedType.toLowerCase();
let imageFullpath = getIMGFilename(
file.path,
theme+this.settings.embedType.toLowerCase(),
exportExtension,
);
if(this.plugin.ea?.onImageExportPathHook) {
try {
imageFullpath = this.plugin.ea.onImageExportPathHook({
exportFilepath: imageFullpath,
exportExtension,
excalidrawFile: file,
action: "export",
}) ?? imageFullpath;
} catch (e) {
errorlog({where: "FileManager.embedDrawing", fn: this.plugin.ea.onImageExportPathHook, error: e});
}
}
const createFile = async (path: string):Promise<TFile> => {
return await createFileAndAwaitMetacacheUpdate(this.app, path,
this.settings.embedType === "SVG"
? `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="0" height="0"></svg>`
: new Uint8Array([
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG signature
0x00, 0x00, 0x00, 0x0D, // IHDR chunk length
0x49, 0x48, 0x44, 0x52, // IHDR
0x00, 0x00, 0x00, 0x01, // width: 1
0x00, 0x00, 0x00, 0x01, // height: 1
0x08, 0x06, 0x00, 0x00, 0x00, // bit depth: 8, color type: 6 (RGBA), compression: 0, filter: 0, interlace: 0
0x1F, 0x15, 0xC4, 0x89, // IHDR CRC
0x00, 0x00, 0x00, 0x0B, // IDAT chunk length
0x49, 0x44, 0x41, 0x54, // IDAT
0x78, 0x9C, 0x62, 0x00, 0x02, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, // compressed data (1x1 transparent pixel)
0x0A, 0x2D, 0xB4, // IDAT CRC
0x00, 0x00, 0x00, 0x00, // IEND chunk length
0x49, 0x45, 0x4E, 0x44, // IEND
0xAE, 0x42, 0x60, 0x82 // IEND CRC
]).buffer
);
}
let imgFile = this.app.vault.getFileByPath(imageFullpath);
if (!imgFile) {
imgFile = await createFile(imageFullpath);
}
const imageRelativePath = this.app.metadataCache.fileToLinktext(
imgFile,
activeView.file.path,
false,
);
//will hold incorrect value if theme==="", however in that case it won't be used
const otherTheme = theme === "dark." ? "light." : "dark.";
const otherImageRelativePath = theme === ""
//if the hook tinkers with the extension, then I cannot predict the other theme's extension
//it would become a messy heuristic to try to guess the other theme's extension
const otherImageRelativePath = ((theme === "") || !imageRelativePath.endsWith(exportExtension))
? null
: getIMGFilename(
excalidrawRelativePath,
otherTheme+this.settings.embedType.toLowerCase(),
);
: (imageRelativePath.substring(0, imageRelativePath.lastIndexOf(exportExtension)) + otherTheme+this.settings.embedType.toLowerCase());
const imgFile = this.app.vault.getAbstractFileByPath(imageFullpath);
if (!imgFile) {
await this.app.vault.create(imageFullpath, "");
await sleep(200); //wait for metadata cache to update
if(otherImageRelativePath) {
await createFile(
imgFile.path.substring(0, imgFile.path.lastIndexOf(exportExtension)) + otherTheme+this.settings.embedType.toLowerCase()
);
}
const inclCom = this.settings.embedMarkdownCommentLinks;
@@ -367,17 +411,43 @@ export class PluginFileManager {
if (!this.isExcalidrawFile(file)) {
return;
}
this.moveBAKFile(oldPath, file.path);
if (!this.settings.keepInSync) {
return;
}
[EXPORT_TYPES, "excalidraw"].flat().forEach(async (ext: string) => {
const oldIMGpath = getIMGFilename(oldPath, ext);
const imgFile = this.app.vault.getAbstractFileByPath(
normalizePath(oldIMGpath),
const imgMap = new Map<string, {oldImgPath: string, newImgPath: string}>();
[EXPORT_TYPES, "excalidraw"].flat().forEach(ext => {
let oldImgPath = getIMGFilename(oldPath, ext);
let newImgPath = getIMGFilename(file.path, ext);
if(this.plugin.ea?.onImageExportPathHook) {
try {
oldImgPath = this.plugin.ea.onImageExportPathHook({
exportFilepath: oldImgPath,
exportExtension: ext,
excalidrawFile: file,
oldExcalidrawPath: oldPath,
action: "move",
}) ?? oldImgPath;
newImgPath = this.plugin.ea.onImageExportPathHook({
exportFilepath: newImgPath,
exportExtension: ext,
excalidrawFile: file,
action: "export",
}) ?? newImgPath;
} catch (e) {
errorlog({where: "FileManager.renameEventHandler", fn: this.plugin.ea.onImageExportPathHook, error: e});
}
}
imgMap.set(ext, { oldImgPath, newImgPath });
});
imgMap.forEach((path, ext) => {
const imgFile = this.app.vault.getFileByPath(
normalizePath(path.oldImgPath),
);
if (imgFile && imgFile instanceof TFile) {
const newIMGpath = getIMGFilename(file.path, ext);
await this.app.fileManager.renameFile(imgFile, newIMGpath);
if (imgFile) {
this.app.fileManager.renameFile(imgFile, normalizePath(path.newImgPath));
}
});
}
@@ -453,6 +523,34 @@ export class PluginFileManager {
});
}
private async removeBAKFromCache(path: string) {
//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) {
return;
}
await imageCache.removeBAKFromCache(path);
}
private async moveBAKFile(oldPath: string, newPath: string) {
if(!oldPath || !newPath) {
return;
}
//this will not work in the short period when Obsidian is starting up, however
//this will only effect a very few files, statistically unlikely to cause
//much/any real user impact.
//a proper queuing feels overkill for this.
if(!imageCache.isReady()) {
return;
}
const backup = await imageCache.getBAKFromCache(oldPath);
if(backup) {
await imageCache.addBAKToCache(newPath, `${backup}`);
await this.removeBAKFromCache(oldPath);
}
}
/**
* watch file delete and delete corresponding .svg and .png
* @param file
@@ -473,7 +571,7 @@ export class PluginFileManager {
//close excalidraw view where this file is open
const excalidrawViews = getExcalidrawViews(this.app);
for (const excalidrawView of excalidrawViews) {
if (excalidrawView.file.path === file.path) {
if (file?.path && excalidrawView?.file?.path === file.path) {
await excalidrawView.leaf.setViewState({
type: VIEW_TYPE_EXCALIDRAW,
state: { file: null },
@@ -481,16 +579,35 @@ export class PluginFileManager {
}
}
this.removeBAKFromCache(file.path);
//delete PNG and SVG files as well
if (this.settings.keepInSync) {
const imgMap = new Map<string, string>();
[EXPORT_TYPES, "excalidraw"].flat().forEach(ext => {
let imgPath = getIMGFilename(file.path, ext);
if(this.plugin.ea?.onImageExportPathHook) {
try {
imgPath = this.plugin.ea.onImageExportPathHook({
exportFilepath: imgPath,
exportExtension: ext,
excalidrawFile: file,
action: "delete",
}) ?? imgPath;
} catch (e) {
errorlog({where: "FileManager.deleteEventHandler", fn: this.plugin.ea.onImageExportPathHook, error: e});
}
}
imgMap.set(ext, imgPath);
});
window.setTimeout(() => {
[EXPORT_TYPES, "excalidraw"].flat().forEach(async (ext: string) => {
const imgPath = getIMGFilename(file.path, ext);
const imgFile = this.app.vault.getAbstractFileByPath(
imgMap.forEach((imgPath: string, ext: string) => {
const imgFile = this.app.vault.getFileByPath(
normalizePath(imgPath),
);
if (imgFile && imgFile instanceof TFile) {
await this.app.vault.delete(imgFile);
if (imgFile) {
this.app.vault.delete(imgFile);
}
});
}, 500);
+4 -1
View File
@@ -710,7 +710,7 @@ const isTextOnlyEmbed = (internalEmbedEl: Element):boolean => {
if(!src) return true; //technically this does not mean this is a text only embed, but still should abort further processing
const fnameParts = getEmbeddedFilenameParts(src);
return !(fnameParts.hasArearef || fnameParts.hasGroupref || fnameParts.hasFrameref || fnameParts.hasClippedFrameref) &&
(fnameParts.hasBlockref || fnameParts.hasSectionref)
(fnameParts.hasBlockref || fnameParts.hasSectionref) && fnameParts.blockref !== "as-image"
}
const tmpObsidianWYSIWYG = async (
@@ -724,6 +724,9 @@ const tmpObsidianWYSIWYG = async (
const file = app.vault.getAbstractFileByPath(ctx.sourcePath);
if(!(file instanceof TFile)) return;
if(!plugin.isExcalidrawFile(file)) return;
if(ctx.frontmatter?.["excalidraw-embed-md"]) {
return;
}
//@ts-ignore
if (ctx.remainingNestLevel < 4) {
+9 -5
View File
@@ -3,6 +3,7 @@ import ExcalidrawPlugin from "src/core/main";
import { CustomMutationObserver } from "src/utils/debugHelper";
import { getExcalidrawViews, isObsidianThemeDark } from "src/utils/obsidianUtils";
import { App, Notice, TFile } from "obsidian";
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
export class ObserverManager {
private plugin: ExcalidrawPlugin;
@@ -130,7 +131,7 @@ export class ObserverManager {
return;
}
if (this.plugin.isExcalidrawFile(f)) {
el.insertBefore(
el.insertAfter(
createDiv({
cls: "nav-file-tag",
text: this.settings.experimentalFileTag,
@@ -183,17 +184,20 @@ export class ObserverManager {
//The user clicks settings, or "open another vault", or the command palette
const modalContainerObserverFn: MutationCallback = async (m: MutationRecord[]) => {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(modalContainerObserverFn,`ExcalidrawPlugin.modalContainerObserverFn`, m);
const view = this.plugin.activeExcalidrawView;
if (
(m.length !== 1) ||
(m[0].type !== "childList") ||
(m[0].addedNodes.length !== 1) ||
(!this.plugin.activeExcalidrawView) ||
this.plugin.activeExcalidrawView?.semaphores?.viewunload ||
(!this.plugin.activeExcalidrawView?.isDirty())
(!view) ||
view.semaphores?.viewunload ||
(!view.isDirty())
) {
return;
}
this.plugin.activeExcalidrawView.save();
const { errorMessage } = (view.excalidrawAPI as ExcalidrawImperativeAPI).getAppState();
if (!errorMessage) this.plugin.activeExcalidrawView.save();
};
this.modalContainerObserver = DEBUGGING
+180 -49
View File
@@ -4,77 +4,202 @@ import { Packages } from "../../types/types";
import { debug, DEBUGGING } from "../../utils/debugHelper";
import { Notice } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
import { errorHandler } from "../../utils/ErrorHandler";
import React from "react";
import ReactDOM from "react-dom";
declare let REACT_PACKAGES:string;
declare let react:any;
declare let reactDOM:any;
declare let react: typeof React;
declare let reactDOM:typeof ReactDOM;
declare let excalidrawLib: typeof ExcalidrawLib;
declare const unpackExcalidraw: Function;
export class PackageManager {
private packageMap: Map<Window, Packages> = new Map<Window, Packages>();
private EXCALIDRAW_PACKAGE: string;
private plugin: ExcalidrawPlugin;
private fallbackPackage: Packages | null = null;
constructor(plugin: ExcalidrawPlugin) {
this.plugin = plugin;
try {
this.EXCALIDRAW_PACKAGE = unpackExcalidraw();
excalidrawLib = window.eval.call(window,`(function() {${this.EXCALIDRAW_PACKAGE};return ExcalidrawLib;})()`);
// Use safe evaluation for unpacking the Excalidraw package
excalidrawLib = errorHandler.safeEval(
`(function() {${this.EXCALIDRAW_PACKAGE};return ExcalidrawLib;})()`,
"PackageManager constructor - excalidrawLib initialization",
window
);
if (!excalidrawLib) {
throw new Error("Failed to initialize excalidrawLib");
}
// Update the exported functions
updateExcalidrawLib();
this.setPackage(window,{react, reactDOM, excalidrawLib});
// Create a package with the loaded libraries
const initialPackage = {react, reactDOM, excalidrawLib};
// Validate the package before storing
if (this.validatePackage(initialPackage)) {
this.setPackage(window, initialPackage);
this.fallbackPackage = initialPackage; // Store a valid package as fallback
} else {
throw new Error("Invalid initial package");
}
} catch (e) {
new Notice("Error loading the Excalidraw package", 6000);
errorHandler.handleError(e, "PackageManager constructor");
new Notice("Error loading the Excalidraw package. Some features may not work correctly.", 10000);
console.error("Error loading the Excalidraw package", e);
}
plugin.logStartupEvent("Excalidraw package unpacked");
}
/**
* Validates that a package contains all required components
*/
private validatePackage(pkg: Packages): boolean {
if (!pkg) return false;
// Check that all components exist
if (!pkg.react || !pkg.reactDOM || !pkg.excalidrawLib) {
return false;
}
// Verify that excalidrawLib has essential methods
const lib = pkg.excalidrawLib;
return (
typeof lib === 'object' &&
lib !== null &&
typeof lib.restore === 'function' &&
typeof lib.exportToSvg === 'function'
);
}
/**
* Store a package for a specific window
*/
public setPackage(window: Window, pkg: Packages) {
this.packageMap.set(window, pkg);
if (this.validatePackage(pkg)) {
this.packageMap.set(window, pkg);
// Update fallback if we don't have one
if (!this.fallbackPackage) {
this.fallbackPackage = pkg;
}
} else {
errorHandler.handleError(
"Attempted to set invalid package",
"PackageManager.setPackage"
);
}
}
public getPackageMap() {
return this.packageMap;
}
public getPackage(win:Window):Packages {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.getPackage, `ExcalidrawPlugin.getPackage`, win);
/**
* Gets a package for a window, creating it if necessary
* with robust error handling
*/
public getPackage(win: Window): Packages {
try {
if ((process.env.NODE_ENV === 'development') && DEBUGGING) {
debug(this.getPackage, `PackageManager.getPackage`, win);
}
if(this.packageMap.has(win)) {
return this.packageMap.get(win);
// Return existing package if available
if (this.packageMap.has(win)) {
const pkg = this.packageMap.get(win);
if (this.validatePackage(pkg)) {
return pkg;
}
// If package exists but is invalid, delete it so we can recreate it
this.packageMap.delete(win);
}
// Create new package
return errorHandler.wrapWithTryCatch(() => {
// Use safe evaluation to load packages in the window context
const evalResult = errorHandler.safeEval<{react: typeof React, reactDOM: typeof ReactDOM, excalidrawLib: typeof ExcalidrawLib}>(
`(function() {
${REACT_PACKAGES + this.EXCALIDRAW_PACKAGE};
return {react: React, reactDOM: ReactDOM, excalidrawLib: ExcalidrawLib};
})()`,
"PackageManager.getPackage - package evaluation",
win
);
if (!evalResult || !this.validatePackage(evalResult)) {
throw new Error("Failed to create valid package");
}
const newPackage = {
react: evalResult.react,
reactDOM: evalResult.reactDOM,
excalidrawLib: evalResult.excalidrawLib
};
this.packageMap.set(win, newPackage);
return newPackage;
}, "PackageManager.getPackage", this.fallbackPackage);
} catch (error) {
errorHandler.handleError(error, "PackageManager.getPackage");
// Return fallback package if available to prevent data loss
if (this.fallbackPackage) {
return this.fallbackPackage;
}
// If no fallback, throw error to prevent undefined behavior
throw new Error("Failed to get package and no fallback available");
}
const {react:r, reactDOM:rd, excalidrawLib:e} = win.eval.call(win,
`(function() {
${REACT_PACKAGES + this.EXCALIDRAW_PACKAGE};
return {react:React,reactDOM:ReactDOM,excalidrawLib:ExcalidrawLib};
})()`);
this.packageMap.set(win,{react:r, reactDOM:rd, excalidrawLib:e});
return {react:r, reactDOM:rd, excalidrawLib:e};
}
public deletePackage(win: Window) {
const { react, reactDOM, excalidrawLib } = this.getPackage(win);
try {
const pkg = this.packageMap.get(win);
if (!pkg) return;
if (win.ExcalidrawLib === excalidrawLib) {
excalidrawLib.destroyObsidianUtils();
delete win.ExcalidrawLib;
const { react, reactDOM, excalidrawLib } = pkg;
if (win.ExcalidrawLib === excalidrawLib) {
// Safely clean up resources
errorHandler.wrapWithTryCatch(() => {
if (excalidrawLib && typeof excalidrawLib.destroyObsidianUtils === 'function') {
excalidrawLib.destroyObsidianUtils();
}
delete win.ExcalidrawLib;
}, "PackageManager.deletePackage - cleanup ExcalidrawLib");
}
if (win.React === react) {
errorHandler.wrapWithTryCatch(() => {
Object.keys(win.React || {}).forEach((key) => {
delete win.React[key];
});
delete win.React;
}, "PackageManager.deletePackage - cleanup React");
}
if (win.ReactDOM === reactDOM) {
errorHandler.wrapWithTryCatch(() => {
Object.keys(win.ReactDOM || {}).forEach((key) => {
delete win.ReactDOM[key];
});
delete win.ReactDOM;
}, "PackageManager.deletePackage - cleanup ReactDOM");
}
this.packageMap.delete(win);
} catch (error) {
errorHandler.handleError(error, "PackageManager.deletePackage");
}
if (win.React === react) {
Object.keys(win.React).forEach((key) => {
delete win.React[key];
});
delete win.React;
}
if (win.ReactDOM === reactDOM) {
Object.keys(win.ReactDOM).forEach((key) => {
delete win.ReactDOM[key];
});
delete win.ReactDOM;
}
this.packageMap.delete(win);
}
public setExcalidrawPackage(pkg: string) {
@@ -82,16 +207,22 @@ export class PackageManager {
}
public destroy() {
REACT_PACKAGES = "";
Object.values(this.packageMap).forEach((p: Packages) => {
delete p.excalidrawLib;
delete p.reactDOM;
delete p.react;
});
this.packageMap.clear();
this.EXCALIDRAW_PACKAGE = "";
react = null;
reactDOM = null;
excalidrawLib = null;
try {
REACT_PACKAGES = "";
Array.from(this.packageMap.entries()).forEach(([win, p]) => {
this.deletePackage(win);
});
this.packageMap.clear();
this.EXCALIDRAW_PACKAGE = "";
this.fallbackPackage = null;
react = null;
reactDOM = null;
excalidrawLib = null;
} catch (error) {
errorHandler.handleError(error, "PackageManager.destroy");
}
}
}
+264 -36
View File
@@ -3,8 +3,10 @@ import {
ButtonComponent,
DropdownComponent,
getIcon,
htmlToMarkdown,
Modifier,
normalizePath,
Notice,
PluginSettingTab,
Setting,
TextComponent,
@@ -18,6 +20,7 @@ import { DynamicStyle, GridSettings } from "src/types/types";
import { PreviewImageType } from "src/types/utilTypes";
import { setDynamicStyle } from "src/utils/dynamicStyling";
import {
createOrOverwriteFile,
getDrawingFilename,
getEmbedFilename,
} from "src/utils/fileUtils";
@@ -28,7 +31,7 @@ import {
setLeftHandedMode,
} from "src/utils/utils";
import { imageCache } from "src/shared/ImageCache";
import { ConfirmationPrompt } from "src/shared/Dialogs/Prompt";
import { MultiOptionConfirmationPrompt } from "src/shared/Dialogs/Prompt";
import { EmbeddableMDCustomProps } from "src/shared/Dialogs/EmbeddableSettings";
import { EmbeddalbeMDFileCustomDataSettingsComponent } from "src/shared/Dialogs/EmbeddableMDFileCustomDataSettingsComponent";
import { startupScript } from "src/constants/starutpscript";
@@ -43,8 +46,10 @@ import { HotkeyEditor } from "src/shared/Dialogs/HotkeyEditor";
import { getExcalidrawViews } from "src/utils/obsidianUtils";
import { createSliderWithText } from "src/utils/sliderUtils";
import { PDFExportSettingsComponent, PDFExportSettings } from "src/shared/Dialogs/PDFExportSettingsComponent";
import { ContentSearcher } from "src/shared/components/ContentSearcher";
export interface ExcalidrawSettings {
disableDoubleClickTextEditing: boolean;
folder: string;
cropFolder: string;
annotateFolder: string;
@@ -67,7 +72,9 @@ export interface ExcalidrawSettings {
drawingFilnameEmbedPostfix: string;
drawingFilenameDateTime: string;
useExcalidrawExtension: boolean;
cropSuffix: string;
cropPrefix: string;
annotateSuffix: string;
annotatePrefix: string;
annotatePreserveSize: boolean;
displaySVGInPreview: boolean; //No longer used since 1.9.13
@@ -91,6 +98,7 @@ export interface ExcalidrawSettings {
penModeDoubleTapEraser: boolean;
penModeSingleFingerPanning: boolean;
penModeCrosshairVisible: boolean;
panWithRightMouseButton: boolean; //mfuria #329
renderImageInMarkdownReadingMode: boolean,
renderImageInHoverPreviewForMDNotes: boolean,
renderImageInMarkdownToPDF: boolean,
@@ -99,6 +107,9 @@ export interface ExcalidrawSettings {
zoomToFitOnOpen: boolean;
zoomToFitOnResize: boolean;
zoomToFitMaxLevel: number;
zoomStep: number; // % increment per zoom action (e.g. mouse wheel)
zoomMin: number; // minimum zoom percentage
zoomMax: number; // maximum zoom percentage
openInAdjacentPane: boolean;
showSecondOrderLinks: boolean;
focusOnFileTab: boolean;
@@ -170,6 +181,7 @@ export interface ExcalidrawSettings {
defaultTrayMode: boolean;
previousRelease: string;
showReleaseNotes: boolean;
compareManifestToPluginVersion: boolean;
showNewVersionNotification: boolean;
//mathjaxSourceURL: string;
latexBoilerplate: string;
@@ -199,6 +211,7 @@ export interface ExcalidrawSettings {
markdownNodeOneClickEditing: boolean;
canvasImmersiveEmbed: boolean,
startupScriptPath: string,
aiEnabled: boolean,
openAIAPIToken: string,
openAIDefaultTextModel: string,
openAIDefaultVisionModel: string,
@@ -226,6 +239,7 @@ export interface ExcalidrawSettings {
declare const PLUGIN_VERSION:string;
export const DEFAULT_SETTINGS: ExcalidrawSettings = {
disableDoubleClickTextEditing: false,
folder: "Excalidraw",
cropFolder: "",
annotateFolder: "",
@@ -248,7 +262,9 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
drawingFilnameEmbedPostfix: " ",
drawingFilenameDateTime: "YYYY-MM-DD HH.mm.ss",
useExcalidrawExtension: true,
cropSuffix: "",
cropPrefix: CROPPED_PREFIX,
annotateSuffix: "",
annotatePrefix: ANNOTATED_PREFIX,
annotatePreserveSize: false,
displaySVGInPreview: undefined,
@@ -272,14 +288,18 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
penModeDoubleTapEraser: true,
penModeSingleFingerPanning: true,
penModeCrosshairVisible: true,
panWithRightMouseButton: false, //mfuria #329
renderImageInMarkdownReadingMode: false,
renderImageInHoverPreviewForMDNotes: false,
renderImageInMarkdownToPDF: false,
allowPinchZoom: false,
allowWheelZoom: false,
zoomToFitOnOpen: true,
zoomToFitOnResize: true,
zoomToFitOnResize: false,
zoomToFitMaxLevel: 2,
zoomStep: 0.05,
zoomMin: 0.1,
zoomMax: 30,
linkPrefix: "📍",
urlPrefix: "🌐",
parseTODO: false,
@@ -316,7 +336,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
experimentalFileTag: "✏️",
experimentalLivePreview: true,
fadeOutExcalidrawMarkup: false,
loadPropertySuggestions: true,
loadPropertySuggestions: false,
experimentalEnableFourthFont: false,
experimantalFourthFont: "Virgil",
addDummyTextElement: false,
@@ -346,6 +366,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
defaultTrayMode: true,
previousRelease: "0.0.0",
showReleaseNotes: true,
compareManifestToPluginVersion: true,
showNewVersionNotification: true,
//mathjaxSourceURL: "https://cdn.jsdelivr.net/npm/mathjax@3.2.1/es5/tex-svg.js",
latexBoilerplate: "\\color{blue}",
@@ -380,6 +401,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
DYNAMIC_COLOR: true,
COLOR: "#000000",
OPACITY: 50,
GRID_DIRECTION: {horizontal: true, vertical: true},
},
laserSettings: {
DECAY_LENGTH: 50,
@@ -400,6 +422,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
markdownNodeOneClickEditing: false,
canvasImmersiveEmbed: true,
startupScriptPath: "",
aiEnabled: true,
openAIAPIToken: "",
openAIDefaultTextModel: "gpt-3.5-turbo-1106",
openAIDefaultVisionModel: "gpt-4o",
@@ -594,6 +617,31 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
containerEl.addClass("excalidraw-settings");
this.containerEl.empty();
// ------------------------------------------------
// Search and Settings to Clipboard
// ------------------------------------------------
const notebookLMLinkContainer = createDiv("setting-item-description excalidraw-settings-links-container");
new ContentSearcher(containerEl, notebookLMLinkContainer);
notebookLMLinkContainer.createEl("a",{
href: "https://notebooklm.google.com/notebook/42d76a2f-c11d-4002-9286-1683c43d0ab0",
attr: {
"aria-label": t("NOTEBOOKLM_LINK_ARIA"),
"style": "margin: auto;"
}},
(a)=> {
//Lucide: message-circle-question-mark
a.innerHTML = `<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-message-circle-question-mark-icon lucide-message-circle-question-mark"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><path d="M12 17h.01"/></svg>${
t("NOTEBOOKLM_LINK_TEXT")
}`;
}
);
// ------------------------------------------------
// Promo links
// ------------------------------------------------
const coffeeDiv = containerEl.createDiv("coffee");
coffeeDiv.addClass("ex-coffee-div");
const coffeeLink = coffeeDiv.createEl("a", {
@@ -608,41 +656,53 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
const iconLinks = [
{
icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"></path><path d="M9 18c-4.51 2-5-2-7-2"></path></svg>`,
icon: getIcon("bug").outerHTML,
href: "https://github.com/zsviczian/obsidian-excalidraw-plugin/issues",
aria: "Report bugs and raise feature requsts on the plugin's GitHub page",
text: "Bugs and Feature Requests",
aria: t("LINKS_BUGS_ARIA"),
text: t("LINKS_BUGS"),
},
{
icon: getIcon("globe").outerHTML,
href: "https://excalidraw-obsidian.online/",
aria: t("LINKS_WIKI_ARIA"),
text: t("LINKS_WIKI"),
},
{
icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19c-2.3 0-6.4-.2-8.1-.6-.7-.2-1.2-.7-1.4-1.4-.3-1.1-.5-3.4-.5-5s.2-3.9.5-5c.2-.7.7-1.2 1.4-1.4C5.6 5.2 9.7 5 12 5s6.4.2 8.1.6c.7.2 1.2.7 1.4 1.4.3 1.1.5 3.4.5 5s-.2 3.9-.5 5c-.2.7-.7 1.2-1.4 1.4-1.7.4-5.8.6-8.1.6 0 0 0 0 0 0z"></path><polygon points="10 15 15 12 10 9"></polygon></svg>`,
icon: getIcon("youtube").outerHTML,
href: "https://www.youtube.com/@VisualPKM",
aria: "Check out my YouTube channel to learn about Visual Thinking and Excalidraw",
text: "Visual PKM on YouTube",
aria: t("LINKS_YT_ARIA"),
text: t("LINKS_YT"),
},
{
icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" stroke="none" strokeWidth="2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 640 512"><path d="M524.531,69.836a1.5,1.5,0,0,0-.764-.7A485.065,485.065,0,0,0,404.081,32.03a1.816,1.816,0,0,0-1.923.91,337.461,337.461,0,0,0-14.9,30.6,447.848,447.848,0,0,0-134.426,0,309.541,309.541,0,0,0-15.135-30.6,1.89,1.89,0,0,0-1.924-.91A483.689,483.689,0,0,0,116.085,69.137a1.712,1.712,0,0,0-.788.676C39.068,183.651,18.186,294.69,28.43,404.354a2.016,2.016,0,0,0,.765,1.375A487.666,487.666,0,0,0,176.02,479.918a1.9,1.9,0,0,0,2.063-.676A348.2,348.2,0,0,0,208.12,430.4a1.86,1.86,0,0,0-1.019-2.588,321.173,321.173,0,0,1-45.868-21.853,1.885,1.885,0,0,1-.185-3.126c3.082-2.309,6.166-4.711,9.109-7.137a1.819,1.819,0,0,1,1.9-.256c96.229,43.917,200.41,43.917,295.5,0a1.812,1.812,0,0,1,1.924.233c2.944,2.426,6.027,4.851,9.132,7.16a1.884,1.884,0,0,1-.162,3.126,301.407,301.407,0,0,1-45.89,21.83,1.875,1.875,0,0,0-1,2.611,391.055,391.055,0,0,0,30.014,48.815,1.864,1.864,0,0,0,2.063.7A486.048,486.048,0,0,0,610.7,405.729a1.882,1.882,0,0,0,.765-1.352C623.729,277.594,590.933,167.465,524.531,69.836ZM222.491,337.58c-28.972,0-52.844-26.587-52.844-59.239S193.056,219.1,222.491,219.1c29.665,0,53.306,26.82,52.843,59.239C275.334,310.993,251.924,337.58,222.491,337.58Zm195.38,0c-28.971,0-52.843-26.587-52.843-59.239S388.437,219.1,417.871,219.1c29.667,0,53.307,26.82,52.844,59.239C470.715,310.993,447.538,337.58,417.871,337.58Z"/></svg>`,
href: "https://discord.gg/DyfAXFwUHc",
aria: "Join the Visual Thinking Workshop Discord Server",
text: "Community on Discord",
aria: t("LINKS_DISCORD_ARIA"),
text: t("LINKS_DISCORD"),
},
{
icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 4s-.7 2.1-2 3.4c1.6 10-9.4 17.3-18 11.6 2.2.1 4.4-.6 6-2C3 15.5.5 9.6 3 5c2.2 2.6 5.6 4.1 9 4-.9-4.2 4-6.6 7-3.8 1.1 0 3-1.2 3-1.2z"></path></svg>`,
icon: getIcon("twitter").outerHTML,
href: "https://twitter.com/zsviczian",
aria: "Follow me on Twitter",
text: "Follow me on Twitter",
aria: t("LINKS_TWITTER"),
text: t("LINKS_TWITTER"),
},
{
icon: getIcon("graduation-cap").outerHTML,
href: "https://visual-thinking-workshop.com",
aria: "Learn about Visual PKM, Excalidraw, Obsidian, ExcaliBrain and more",
text: "Join the Visual Thinking Workshop",
}
aria: t("LINKS_VTW_ARIA"),
text: t("LINKS_VTW"),
},
{
icon: getIcon("book").outerHTML,
href: "https://sketch-your-mind.com",
aria: t("LINKS_BOOK_ARIA"),
text: t("LINKS_BOOK"),
},
];
const linksEl = containerEl.createDiv("setting-item-description excalidraw-settings-links-container");
iconLinks.forEach(({ icon, href, aria, text }) => {
linksEl.createEl("a",{href, attr: { "aria-label": aria }}, (a)=> {
a.innerHTML = icon + text;
a.innerHTML = icon + text;
});
});
@@ -668,6 +728,18 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}),
);
new Setting(detailsEl)
.setName(t("WARN_ON_MANIFEST_MISMATCH_NAME"))
.setDesc(fragWithHTML(t("WARN_ON_MANIFEST_MISMATCH_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.compareManifestToPluginVersion)
.onChange(async (value) => {
this.plugin.settings.compareManifestToPluginVersion = value;
this.applySettingsUpdate();
}),
);
new Setting(detailsEl)
.setName(t("NEWVERSION_NOTIFICATION_NAME"))
.setDesc(fragWithHTML(t("NEWVERSION_NOTIFICATION_DESC")))
@@ -680,6 +752,17 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}),
);
new Setting(detailsEl)
.setName(t("TOGGLE_SPLASHSCREEN"))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.showSplashscreen)
.onChange((value)=> {
this.plugin.settings.showSplashscreen = value;
this.applySettingsUpdate();
})
)
new Setting(detailsEl)
.setName(t("FOLDER_NAME"))
.setDesc(fragWithHTML(t("FOLDER_DESC")))
@@ -939,7 +1022,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("CROP_PREFIX_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: Cropped_ ")
.setPlaceholder("e.g.: cropped_")
.setValue(this.plugin.settings.cropPrefix)
.onChange(async (value) => {
this.plugin.settings.cropPrefix = value.replaceAll(
@@ -951,12 +1034,29 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}),
);
new Setting(detailsEl)
.setName(t("CROP_SUFFIX_NAME"))
.setDesc(fragWithHTML(t("CROP_SUFFIX_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: _cropped")
.setValue(this.plugin.settings.cropSuffix)
.onChange(async (value) => {
this.plugin.settings.cropSuffix = value.replaceAll(
/[<>:"/\\|?*]/g,
"_",
);
text.setValue(this.plugin.settings.cropSuffix);
this.applySettingsUpdate();
}),
);
new Setting(detailsEl)
.setName(t("ANNOTATE_PREFIX_NAME"))
.setDesc(fragWithHTML(t("ANNOTATE_PREFIX_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: Annotated_ ")
.setPlaceholder("e.g.: annotated_")
.setValue(this.plugin.settings.annotatePrefix)
.onChange(async (value) => {
this.plugin.settings.annotatePrefix = value.replaceAll(
@@ -967,7 +1067,24 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
}),
);
new Setting(detailsEl)
.setName(t("ANNOTATE_SUFFIX_NAME"))
.setDesc(fragWithHTML(t("ANNOTATE_SUFFIX_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: _annotated")
.setValue(this.plugin.settings.annotateSuffix)
.onChange(async (value) => {
this.plugin.settings.annotateSuffix = value.replaceAll(
/[<>:"/\\|?*]/g,
"_",
);
text.setValue(this.plugin.settings.annotateSuffix);
this.applySettingsUpdate();
}),
);
new Setting(detailsEl)
.setName(t("ANNOTATE_PRESERVE_SIZE_NAME"))
.setDesc(fragWithHTML(t("ANNOTATE_PRESERVE_SIZE_DESC")))
@@ -992,6 +1109,27 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
cls: "excalidraw-setting-h1",
});
let aiEl: HTMLElement;
new Setting(detailsEl)
.setName(t("AI_ENABLED_NAME"))
.setDesc(fragWithHTML(t("AI_ENABLED_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.aiEnabled??true)
.onChange(async (value) => {
aiEl.style.display = value ? "block" : "none";
this.plugin.settings.aiEnabled = value;
this.applySettingsUpdate();
}),
);
detailsEl = detailsEl.createDiv();
aiEl = detailsEl;
if(!(this.plugin.settings.aiEnabled??true)) {
detailsEl.style.display = "none";
}
new Setting(detailsEl)
.setName(t("AI_OPENAI_TOKEN_NAME"))
.setDesc(fragWithHTML(t("AI_OPENAI_TOKEN_DESC")))
@@ -1069,6 +1207,17 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
cls: "excalidraw-setting-h1",
});
new Setting(detailsEl)
.setName(t("ENABLE_DOUBLE_CLICK_TEXT_EDITING_NAME"))
.addToggle((toggle) =>
toggle
.setValue(!this.plugin.settings.disableDoubleClickTextEditing)
.onChange(async (value) => {
this.plugin.settings.disableDoubleClickTextEditing = !value;
this.applySettingsUpdate();
}),
);
const readingModeEl = new Setting(detailsEl)
.setName(t("SHOW_DRAWING_OR_MD_IN_READING_MODE_NAME"))
.setDesc(fragWithHTML(t("SHOW_DRAWING_OR_MD_IN_READING_MODE_DESC")))
@@ -1111,17 +1260,6 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
);
addIframe(detailsEl, "H8Njp7ZXYag",999);
new Setting(detailsEl)
.setName(t("TOGGLE_SPLASHSCREEN"))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.showSplashscreen)
.onChange((value)=> {
this.plugin.settings.showSplashscreen = value;
this.applySettingsUpdate();
})
)
detailsEl = displayDetailsEl.createEl("details");
detailsEl.createEl("summary", {
text: t("HOTKEY_OVERRIDE_HEAD"),
@@ -1241,9 +1379,24 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
detailsEl = displayDetailsEl.createEl("details");
detailsEl.createEl("summary", {
text: t("ZOOM_HEAD"),
text: t("ZOOM_AND_PAN_HEAD"), //mfuria #329
cls: "excalidraw-setting-h3",
});
//mfuria #329. Added setting for right-click panning
new Setting(detailsEl)
.setName(t("PAN_WITH_RIGHT_MOUSE_BUTTON_NAME"))
.setDesc(fragWithHTML(t("PAN_WITH_RIGHT_MOUSE_BUTTON_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.panWithRightMouseButton)
.onChange(async (value) => {
this.plugin.settings.panWithRightMouseButton = value;
this.applySettingsUpdate(true);
}),
);
new Setting(detailsEl)
.setName(t("DEFAULT_PINCHZOOM_NAME"))
.setDesc(fragWithHTML(t("DEFAULT_PINCHZOOM_DESC")))
@@ -1309,6 +1462,45 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}
})
createSliderWithText(detailsEl, {
name: t("ZOOM_STEP_NAME"),
desc: t("ZOOM_STEP_DESC"),
value: this.plugin.settings.zoomStep*100,
min: 1,
max: 25,
step: 1,
onChange: (value) => {
this.plugin.settings.zoomStep = value/100;
this.applySettingsUpdate();
}
})
createSliderWithText(detailsEl, {
name: t("ZOOM_MIN_NAME"),
desc: t("ZOOM_MIN_DESC"),
value: this.plugin.settings.zoomMin*100,
min: 1,
max: 50,
step: 1,
onChange: (value) => {
this.plugin.settings.zoomMin = value/100;
this.applySettingsUpdate();
}
})
createSliderWithText(detailsEl, {
name: t("ZOOM_MAX_NAME"),
desc: t("ZOOM_MAX_DESC"),
value: this.plugin.settings.zoomMax*100,
min: 500,
max: 6000,
step: 100,
onChange: (value) => {
this.plugin.settings.zoomMax = value/100;
this.applySettingsUpdate();
}
})
// ------------------------------------------------
// Pen
// ------------------------------------------------
@@ -1380,6 +1572,42 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
getExcalidrawViews(this.app).forEach(excalidrawView=>excalidrawView.updateGridColor());
};
const updateGridDirection = () => {
getExcalidrawViews(this.app).forEach(excalidrawView=>
excalidrawView.updateGridDirection(this.plugin.settings.gridSettings.GRID_DIRECTION));
}
new Setting(detailsEl)
.setName(t("GRID_DIRECTION_NAME"))
.setDesc(t("GRID_DIRECTION_DESC"))
.addToggle((toggle) =>
toggle
.setTooltip(t("GRID_HORIZONTAL"))
.setValue(this.plugin.settings.gridSettings.GRID_DIRECTION?.horizontal ?? true)
.onChange((value) => {
if(!this.plugin.settings.gridSettings.GRID_DIRECTION) {
this.plugin.settings.gridSettings.GRID_DIRECTION = { horizontal: true, vertical: true };
} //2.10.1 migration
this.plugin.settings.gridSettings.GRID_DIRECTION.horizontal = value;
this.applySettingsUpdate();
updateGridDirection();
}),
)
.addToggle((toggle) =>
toggle
.setTooltip(t("GRID_VERTICAL"))
.setValue(this.plugin.settings.gridSettings.GRID_DIRECTION?.vertical ?? true)
.onChange((value) => {
if(!this.plugin.settings.gridSettings.GRID_DIRECTION) {
this.plugin.settings.gridSettings.GRID_DIRECTION = { horizontal: true, vertical: true };
} //2.10.1 migration
this.plugin.settings.gridSettings.GRID_DIRECTION.vertical = value;
this.applySettingsUpdate();
updateGridDirection();
}),
);
// Dynamic color toggle
let gridColorSection: HTMLDivElement;
new Setting(detailsEl)
@@ -1974,7 +2202,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
button
.setButtonText(t("BACKUP_CACHE_CLEAR"))
.onClick(() => {
const confirmationPrompt = new ConfirmationPrompt(this.plugin,t("BACKUP_CACHE_CLEAR_CONFIRMATION"));
const confirmationPrompt = new MultiOptionConfirmationPrompt(this.plugin,t("BACKUP_CACHE_CLEAR_CONFIRMATION"));
confirmationPrompt.waitForClose.then((confirmed) => {
if (confirmed) {
imageCache.clearBackupCache();
@@ -2423,7 +2651,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
// Non-excalidraw.com supported features
// ------------------------------------------------
containerEl.createEl("hr", { cls: "excalidraw-setting-hr" });
containerEl.createDiv({ text: t("NONSTANDARD_DESC"), cls: "setting-item-description" });
containerEl.createDiv( { text: t("NONSTANDARD_DESC"), cls: "setting-item-description" });
detailsEl = this.containerEl.createEl("details");
const nonstandardDetailsEl = detailsEl;
detailsEl.createEl("summary", {
@@ -2802,7 +3030,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
: this.plugin.settings.startupScriptPath + ".md");
let f = this.app.vault.getAbstractFileByPath(startupPath);
if(!f) {
f = await this.app.vault.create(startupPath, startupScript());
f = await createOrOverwriteFile(this.app, startupPath, startupScript());
}
startupScriptButton.setButtonText(t("STARTUP_SCRIPT_BUTTON_OPEN"));
this.app.workspace.openLinkText(f.path,"",true);
+149
View File
@@ -0,0 +1,149 @@
/**
* Language Pack Diff Checker Script
*
* Purpose:
* Compare src/lang/locale/en.ts and a target language file (e.g. zh-cn.ts), output missing and extra keys.
* Output is color-coded:
* - Green: Key exists in en.ts but missing in the target language file
* - Red: Key exists in the target language file but not in en.ts
* - Yellow: The same key exists in both files but the line numbers are different
*
* Dependencies:
* Node.js environment, no extra dependencies required.
*
* Usage:
* 1. Open a terminal in this file's directory (or project root).
* 2. Run:
* node src/lang/langDiffWithEn.js zh-cn
* # or node src/lang/langDiffWithEn.js ja
* # The argument is the language file name (without extension), default is zh-cn
*
* Output:
* + (green): Key exists in en.ts but missing in the target language file
* - (red): Key exists in the target language file but not in en.ts
* ! (yellow): The same key exists in both files but the line numbers are different
* If there is no output, the two files have identical keys.
*/
/**
* 语言包差异检测脚本
*
* 用途:
* 比较 src/lang/locale/en.ts 与指定语言文件(如 zh-cn.ts)中的 key,输出缺失和多余的 key。
* 输出内容会用不同颜色区分:
* - 绿色:en.ts 有但目标语言缺失的 key
* - 红色:目标语言有但 en.ts 没有的 key
* - 黄色:相同的 key 所在的行号不相同
*
* 依赖:
* Node.js 环境,无需额外依赖。
*
* 用法:
* 1. 在命令行进入本文件所在目录(或项目根目录)。
* 2. 运行:
* node src/lang/langDiffWithEn.js zh-cn
* # 或 node src/lang/langDiffWithEn.js ja
* # 参数为语言文件名(不带扩展名),默认为 zh-cn
*
* 输出说明:
* + 开头(绿色):en.ts 有但目标语言缺失的 key
* - 开头(红色):目标语言有但 en.ts 没有的 key
* ! 开头(黄色):相同的 key 所在的行号不相同
* 若无输出则表示两个文件 key 完全一致。
*/
const fs = require("fs");
const path = require("path");
/**
* 读取 locale 文件夹下指定语言和 en.ts 文件,逐行解析键值和行号
* @param lang 语言文件名(不含扩展名),如 zh-cn
* @returns { en: Record<string, {value: string, line: number}>, lang: Record<string, {value: string, line: number}> }
*/
function readLocaleFiles(lang = "zh-cn") {
// 构造 locale 目录路径
const localeDir = path.join(__dirname, "./locale");
// 获取 en.ts 文件路径
const enFile = path.join(localeDir, "en.ts");
// 获取指定语言文件路径
const langFile = path.join(localeDir, `${lang}.ts`);
/**
* 解析指定的语言文件,提取每个 key 的值和所在行号
* @param file 文件路径
* @returns {Record<string, {value: string, line: number}>}
*/
const parse = (file) => {
// 读取文件内容并按行分割
const lines = fs.readFileSync(file, "utf8").split(/\r?\n/);
const result = {};
let inExport = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
// 检查是否进入 export default 块
if (!inExport && line.includes("export default")) {
inExport = true;
continue;
}
if (!inExport) continue;
// 匹配 key: "value", 格式的行
const m = line.match(/^\s*([A-Z0-9_]+)\s*:\s*.*?,?$/);
if (m) {
let key = m[1];
// 保存 key 及其所在行号
result[key] = i + 1;
}
}
return result;
};
// 返回 en 和指定语言的解析结果
return {
en: parse(enFile),
lang: parse(langFile),
};
}
/**
* 比较 en 和 lang 的 key/value,输出差异
*/
function diffLang(lang = "zh-cn") {
const { en, lang: l } = readLocaleFiles(lang);
const allKeys = new Set([...Object.keys(en), ...Object.keys(l)]);
const diffs = [];
for (const key of allKeys) {
if (!(key in en)) {
diffs.push(`- ${key}: ${l[key]}`);
} else if (!(key in l)) {
diffs.push(`+ ${key}: ${en[key]}`);
} else {
if (en[key] !== l[key]) {
diffs.push(`! ${key}: en: ${en[key]} <--> lang: ${l[key]}`);
}
}
}
return diffs;
}
// CLI
if (require.main === module) {
const lang = process.argv[2] || "zh-cn";
const diffs = diffLang(lang);
if (diffs.length === 0) {
console.log(`语言文件 ${lang} 与 en.ts 无差异`);
} else {
diffs.forEach((line) => {
if (line.startsWith("+")) {
// 绿色
console.log("\x1b[32m%s\x1b[0m", line);
} else if (line.startsWith("-")) {
// 红色
console.log("\x1b[31m%s\x1b[0m", line);
} else if (line.startsWith("!")) {
// 黄色
console.log("\x1b[33m%s\x1b[0m", line);
} else {
// 默认
console.log(line);
}
});
}
}
+148 -18
View File
@@ -44,7 +44,7 @@ export default {
TRANSCLUDE_MOST_RECENT: "Embed the most recently edited drawing",
TOGGLE_LEFTHANDED_MODE: "Toggle left-handed mode",
TOGGLE_SPLASHSCREEN: "Show splash screen in new drawings",
FLIP_IMAGE: "Open the back-of-the-note of the selected excalidraw image",
FLIP_IMAGE: "Open the back-of-the-note for the selected image in a popout window (flip the card)",
NEW_IN_NEW_PANE: "Create new drawing - IN AN ADJACENT WINDOW",
NEW_IN_NEW_TAB: "Create new drawing - IN A NEW TAB",
NEW_IN_ACTIVE_PANE: "Create new drawing - IN THE CURRENT ACTIVE WINDOW",
@@ -58,6 +58,10 @@ export default {
NEW_IN_POPOUT_WINDOW_EMBED: "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",
MARKER_FRAME_SHOW: "Show Marker Frames",
MARKER_FRAME_HIDE: "Hide Marker Frames",
MARKER_FRAME_TITLE_SHOW: "Show Marker Frame Titles",
MARKER_FRAME_TITLE_HIDE: "Hide Marker Frame Titles",
COPY_ELEMENT_LINK: "Copy [[link]] for selected element(s)",
COPY_DRAWING_LINK: "Copy ![[embed link]] for this drawing",
INSERT_LINK_TO_ELEMENT:
@@ -134,6 +138,14 @@ export default {
"2) Then create an empty drawing in a new pane by CTRL/CMD+clicking the Excalidraw ribbon button,\n" +
"3) and paste your work to the new document with CTRL/CMD+V.",
ARIA_LABEL_TRAY_MODE: "Tray-mode offers an alternative, more spacious canvas",
TRAY_TRAY_MODE: "Toggle tray-mode",
TRAY_SCRIPT_LIBRARY: "Script Library",
TRAY_SCRIPT_LIBRARY_ARIA: "Explore the Excalidraw Script Library",
TRAY_EXPORT: "Export Image...",
TRAY_EXPORT_ARIA: "Export image as PNG, SVG, or Excalidraw file",
TRAY_SAVE: "Save",
TRAY_SWITCH_TO_MD: "Open as Markdown",
TRAY_SWITCH_TO_MD_ARIA: "Switch to markdown view",
MASK_FILE_NOTICE: "This is a mask file. It is used to crop images and mask out parts of the image. Press and hold notice to open the help video.",
INSTALL_SCRIPT_BUTTON: "Install or update Excalidraw Scripts",
OPEN_AS_MD: "Open as Markdown",
@@ -158,6 +170,10 @@ 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",
BACKUP_DELETE: "Delete Backup",
BACKUP_CANCEL: "Cancel",
CACHE_NOT_READY: "I apologize for the inconvenience, but an error occurred while loading your file.<br><br><mark>Having a little patience can save you a lot of time...</mark><br><br>The plugin has a backup cache, but it appears that you have just started Obsidian. Initializing the Backup Cache may take some time, usually up to a minute or more depending on your device's performance. You will receive a notification in the top right corner when the cache initialization is complete.<br><br>Please press OK to attempt loading the file again and check if the cache has finished initializing. If you see a completely empty file behind this message, I recommend waiting until the backup cache is ready before proceeding. Alternatively, you can choose Cancel to manually correct your file.<br>",
OBSIDIAN_TOOLS_PANEL: "Obsidian Tools Panel",
ERROR_SAVING_IMAGE: "Unknown error occurred while fetching the image. It could be that for some reason the image is not available or rejected the fetch request from Obsidian",
@@ -188,11 +204,38 @@ export default {
SAVE_IS_TAKING_LONG: "Saving your previous file is taking a long time. Please wait...",
SAVE_IS_TAKING_VERY_LONG: "For better performance, consider splitting large drawings into several smaller files.",
//ContentSearcher.ts
SEARCH_COPIED_TO_CLIPBOARD: "Markdown ready on clipboard",
SEARCH_COPY_TO_CLIPBOARD_ARIA: "Copy the entire dialog to the clipboard as Markdown. Ideal for use with tools like ChatGPT to search and understand.",
SEARCH_SHOWHIDE_ARIA: "Show/Hide search bar",
SEARCH_NEXT: "Next",
SEARCH_PREVIOUS: "Previous",
//settings.ts
NOTEBOOKLM_LINK_ARIA: "Ask NotebookLM for help about the plugin. This model is pre-loaded with all my video transcripts, release notes and other helpful content. Chat with NotebookLM to explore my 250+ videos and the Excalidraw documentation.",
NOTEBOOKLM_LINK_TEXT: "Learn the Plugin. Access the NotebookLM knowledgebase.",
LINKS_BUGS_ARIA: "Report bugs and raise feature requsts on the plugin's GitHub page",
LINKS_BUGS: "Report Bugs",
LINKS_YT_ARIA: "Check out my YouTube channel to learn about Visual Thinking and Excalidraw",
LINKS_YT: "Learn on YouTube",
LINKS_DISCORD_ARIA: "Join the Visual Thinking Workshop Discord Server",
LINKS_DISCORD: "Join the Community",
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",
LINKS_WIKI_ARIA: "Explore the Excalidraw Plugin Wiki",
RELEASE_NOTES_NAME: "Display Release Notes after update",
RELEASE_NOTES_DESC:
"<b><u>Toggle ON:</u></b> Display release notes each time you update Excalidraw to a newer version.<br>" +
"<b><u>Toggle OFF:</u></b> Silent mode. You can still read release notes on <a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/releases'>GitHub</a>.",
WARN_ON_MANIFEST_MISMATCH_NAME: "Warn about incomplete plugin updates",
WARN_ON_MANIFEST_MISMATCH_DESC: "Checks that the installed Excalidraw executable matches the version shown in Obsidian's plugin list. If they don't match (often after partial sync), you'll see a warning and can update. Disable to stop checking.",
NEWVERSION_NOTIFICATION_NAME: "Plugin update notification",
NEWVERSION_NOTIFICATION_DESC:
"<b><u>Toggle ON:</u></b> Show a notification when a new version of the plugin is available.<br>" +
@@ -203,17 +246,25 @@ export default {
FOLDER_NAME: "Excalidraw folder (CAsE sEnsITive!)",
FOLDER_DESC:
"Default location for new drawings. If empty, drawings will be created in the Vault root.",
CROP_SUFFIX_NAME: "Crop file suffix",
CROP_SUFFIX_DESC:
"The last part of the filename for new drawings created when cropping an image. " +
"Leave empty if you don't need a suffix.",
CROP_PREFIX_NAME: "Crop file prefix",
CROP_PREFIX_DESC:
"The first part of the filename for new drawings created when cropping an image. " +
"If empty the default 'cropped_' will be used.",
"Leave empty if you don't need a prefix.",
ANNOTATE_SUFFIX_NAME: "Annotation file suffix",
ANNOTATE_SUFFIX_DESC:
"The last part of the filename for new drawings created when annotating an image. " +
"Leave empty if you don't need a suffix.",
ANNOTATE_PREFIX_NAME: "Annotation file prefix",
ANNOTATE_PREFIX_DESC:
"The first part of the filename for new drawings created when annotating an image. " +
"If empty the default 'annotated_' will be used.",
"Leave empty if you don't need a prefix.",
ANNOTATE_PRESERVE_SIZE_NAME: "Preserve image size when annotating",
ANNOTATE_PRESERVE_SIZE_DESC:
"When annotating an image in markdown the replacment image link will include the width of the original image.",
"When annotating an image in markdown the replacement image link will include the width of the original image.",
CROP_FOLDER_NAME: "Crop file folder (CaSE senSItive!)",
CROP_FOLDER_DESC:
"Default location for new drawings created when cropping an image. If empty, drawings will be created following the Vault attachments settings.",
@@ -233,7 +284,7 @@ export default {
"Template.md, the setting would be: Excalidraw/Template.md (or just Excalidraw/Template - you may omit the .md file extension). " +
"If you are using Excalidraw in compatibility mode, then your template must be a legacy Excalidraw file as well " +
"such as Excalidraw/Template.excalidraw. <br><b>Template Folder:</b> You can also set a folder as your template. " +
"In this case you will be prompted which tempalte to use when creating a new drawing.<br>" +
"In this case you will be prompted which template to use when creating a new drawing.<br>" +
"<b>Pro Tip:</b> If you are using the Obsidian Templater plugin, you can add Templater code to your different Excalidraw " +
"templates to automate configuration of your drawings.",
SCRIPT_FOLDER_NAME: "Excalidraw Automate script folder (CASE SeNSitiVE!)",
@@ -247,6 +298,8 @@ export default {
`While the OpenAI API is in beta, its use is strictly limited — as such we require you use your own API key. ` +
`You can create an OpenAI account, add a small credit (5 USD minimum), and generate your own API key. ` +
`Once API key is set, you can use the AI tools in Excalidraw.`,
AI_ENABLED_NAME: "Enable AI features",
AI_ENABLED_DESC: "You need to reopen Excalidraw for the changes to take effect.",
AI_OPENAI_TOKEN_NAME: "OpenAI API key",
AI_OPENAI_TOKEN_DESC:
"You can get your OpenAI API key from your <a href='https://platform.openai.com/api-keys'>OpenAI account</a>.",
@@ -305,7 +358,7 @@ export default {
"Excalidraw will also save the file when closing a workspace tab or navigating within Obsidian, but away from the active Excalidraw tab (i.e. tapping on the Obsidian ribbon or checking backlinks, etc.). " +
"Excalidraw will not be able to save your work when terminating Obsidian directly (i.e. swiping it away). Also note, that when you switch apps on a Mobile device, sometimes Android and iOS closes " +
"Obsidian in the background to save system resources. In such a case Excalidraw will not be able to save the latest changes.",
FILENAME_HEAD: "Filename",
FILENAME_HEAD: "Filename",
FILENAME_DESC:
"<p>Click this link for the <a href='https://momentjs.com/docs/#/displaying/format/'>" +
"date and time format reference</a>.</p>",
@@ -343,7 +396,7 @@ FILENAME_HEAD: "Filename",
LEFTHANDED_MODE_NAME: "Left-handed mode",
LEFTHANDED_MODE_DESC:
"Currently only has effect in tray-mode. If turned on, the tray will be on the right side." +
"<br><b><u>Toggle ON:</u></b> Left-handed mode.<br><b><u>Toggle OFF:</u></b> Right-handed moded",
"<br><b><u>Toggle ON:</u></b> Left-handed mode.<br><b><u>Toggle OFF:</u></b> Right-handed mode.",
IFRAME_MATCH_THEME_NAME: "Markdown embeds to match Excalidraw theme",
IFRAME_MATCH_THEME_DESC:
"<b><u>Toggle ON:</u></b> Set this to true if for example you are using Obsidian in dark-mode but use excalidraw with a light background. " +
@@ -369,6 +422,7 @@ FILENAME_HEAD: "Filename",
DEFAULT_PEN_MODE_NAME: "Pen mode",
DEFAULT_PEN_MODE_DESC:
"Should pen mode be automatically enabled when opening Excalidraw?",
ENABLE_DOUBLE_CLICK_TEXT_EDITING_NAME: "Enable double-click text create",
DISABLE_DOUBLE_TAP_ERASER_NAME: "Enable double-tap eraser in pen mode",
DISABLE_SINGLE_FINGER_PANNING_NAME: "Enable single-finger panning in pen mode",
SHOW_PEN_MODE_FREEDRAW_CROSSHAIR_NAME: "Show (+) crosshair in pen mode",
@@ -379,7 +433,8 @@ FILENAME_HEAD: "Filename",
SHOW_DRAWING_OR_MD_IN_HOVER_PREVIEW_DESC:
"...even if the file has the <b>excalidraw-open-md: true</b> frontmatter key.<br>" +
"When this setting is off and the file is set to open in md by default, the hover preview will show the " +
"markdown side of the document.",
"markdown side of the document.<br>" +
"Note: <b>excalidraw-open-md</b> is different from <b>excalidraw-embed-md</b>. If <b>excalidraw-embed-md</b> is set to true, the hover preview will always show the markdown side, regardless of this setting. To force image rendering when embedding, use <code>![[drawing#^as-image]]</code> in your markdown file.",
SHOW_DRAWING_OR_MD_IN_READING_MODE_NAME: "Render as image when in markdown reading mode of an Excalidraw file",
SHOW_DRAWING_OR_MD_IN_READING_MODE_DESC:
"When you are in markdown reading mode (aka. reading the back side of the drawing) should the Excalidraw drawing be rendered as an image? " +
@@ -396,10 +451,12 @@ FILENAME_HEAD: "Filename",
"⚠️ You must close and reopen the Excalidraw/markdown file for changes to take effect. ⚠️",
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 ` +
"conflict with Obsidian hotkey settings. The hotkey combinations you add below will override Obsidian's hotkey settings while useing Excalidraw, thus " +
"conflict with Obsidian hotkey settings. The hotkey combinations you add below will override Obsidian's hotkey settings while using Excalidraw, thus " +
`you can add <code>${labelCTRL()}+G</code> if you want to default to Group Object in Excalidraw instead of opening Graph View.`,
THEME_HEAD: "Theme and styling",
ZOOM_HEAD: "Zoom",
ZOOM_AND_PAN_HEAD: "Zoom and Pan",
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "Right-click drag to pan",
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC: "Right-click and drag to pan the canvas (Miro-style). Press 'm' to open the context menu.",
DEFAULT_PINCHZOOM_NAME: "Allow pinch zoom in pen mode",
DEFAULT_PINCHZOOM_DESC:
"Pinch zoom in pen mode when using the freedraw tool is disabled by default to prevent unwanted accidental zooming with your palm.<br>" +
@@ -418,6 +475,12 @@ FILENAME_HEAD: "Filename",
ZOOM_TO_FIT_MAX_LEVEL_NAME: "Zoom to fit max ZOOM level",
ZOOM_TO_FIT_MAX_LEVEL_DESC:
"Set the maximum level to which zoom to fit will enlarge the drawing. Minimum is 0.5 (50%) and maximum is 10 (1000%).",
ZOOM_STEP_NAME: "Zoom increment",
ZOOM_STEP_DESC: "Zoom increment (in percentage points) for actions like mouse wheel zoom. Smaller values give finer control but may require excessive scrolling. Default: 5%.",
ZOOM_MIN_NAME: "Minimum zoom",
ZOOM_MIN_DESC: "How far you can zoom out (fit more of the drawing on screen). Default: 10%. Values below 10% were historically unstable—lower with caution and reset to 10% if issues occur.",
ZOOM_MAX_NAME: "Maximum zoom",
ZOOM_MAX_DESC: "Upper zoom limit. Default: 3000%. Usually no need to change; included for completeness.",
PEN_HEAD: "Pen",
GRID_HEAD: "Grid",
GRID_DYNAMIC_COLOR_NAME: "Dynamic grid color",
@@ -427,6 +490,10 @@ FILENAME_HEAD: "Filename",
GRID_OPACITY_NAME: "Grid opacity",
GRID_OPACITY_DESC: "Grid opacity will also control the opacity of the binding box when binding an arrow to an element.<br>" +
"Set the opacity of the grid. 0 is transparent, 100 is opaque.",
GRID_DIRECTION_NAME: "Grid direction",
GRID_DIRECTION_DESC: "The first toggle shows/hides the horizontal grid, the second toggle shows/hides the vertical grid.",
GRID_HORIZONTAL: "Render horizontal grid",
GRID_VERTICAL: "Render vertical grid",
LASER_HEAD: "Laser pointer",
LASER_COLOR: "Laser pointer color",
LASER_DECAY_TIME_NAME: "Laser pointer decay time",
@@ -456,7 +523,7 @@ FILENAME_HEAD: "Filename",
FOCUS_ON_EXISTING_TAB_NAME: "Focus on Existing Tab",
FOCUS_ON_EXISTING_TAB_DESC: "When opening a link, Excalidraw will focus on the existing tab if the file is already open. " +
"Enabling this setting overrides 'Reuse Adjacent Pane' when the file is already open.",
"Enabling this setting overrides 'Reuse Adjacent Pane' when the file is already open except for the 'Open the back-of-the-note of the selected excalidraw image' command palette action.",
SECOND_ORDER_LINKS_NAME: "Show second-order links",
SECOND_ORDER_LINKS_DESC: "Show links when clicking on a link in Excalidraw. Second-order link are backlinks pointing to the link being clicked. " +
"When using image icons to connect similar notes, second order links allow you to get to related notes in one click instead of two. " +
@@ -527,7 +594,7 @@ FILENAME_HEAD: "Filename",
"Use the <code>http://iframely.server.crestify.com/iframely?url=</code> to get title of page when dropping a link into Excalidraw",
PDF_TO_IMAGE: "PDF to Image",
PDF_TO_IMAGE_SCALE_NAME: "PDF to Image conversion scale",
PDF_TO_IMAGE_SCALE_DESC: "Sets the resolution of the image that is generated from the PDF page. Higher resolution will result in bigger images in memory and consequently a higher load on your system (slower performance), but sharper imagee. " +
PDF_TO_IMAGE_SCALE_DESC: "Sets the resolution of the image that is generated from the PDF page. Higher resolution will result in bigger images in memory and consequently a higher load on your system (slower performance), but sharper image. " +
"Additionally, if you want to copy PDF pages (as images) to Excalidraw.com, the bigger image size may result in exceeding the 2MB limit on Excalidraw.com.",
EMBED_TOEXCALIDRAW_HEAD: "Embed files into Excalidraw",
EMBED_TOEXCALIDRAW_DESC: "In the Embed Files section of Excalidraw Settings, you can configure how various files are embedded into Excalidraw. This includes options for embedding interactive markdown files, PDFs, and markdown files as images.",
@@ -687,7 +754,7 @@ FILENAME_HEAD: "Filename",
DUMMY_TEXT_ELEMENT_LINT_SUPPORT_NAME: "Linter compatibility",
DUMMY_TEXT_ELEMENT_LINT_SUPPORT_DESC: "Excalidraw is sensitive to the file structure below <code># Excalidraw Data</code>. Automatic linting of documents can create errors in Excalidraw Data. " +
"While I've made some effort to make the data loading resilient to " +
"lint changes, this solution is not foolproof.<br><mark>The best is to avoid liniting or otherwise automatically changing Excalidraw documents using different plugins.</mark><br>" +
"lint changes, this solution is not foolproof.<br><mark>The best is to avoid linting or otherwise automatically changing Excalidraw documents using different plugins.</mark><br>" +
"Use this setting if for good reasons you have decided to ignore my recommendation and configured linting of Excalidraw files.<br> " +
"The <code>## Text Elements</code> section is sensitive to empty lines. A common linting approach is to add an empty line after section headings. In case of Excalidraw this will break/change the first text element in your drawing. " +
"To overcome this, you can enable this setting. When enabled, Excalidraw will add a dummy element to the beginning of <code>## Text Elements</code> that the linter can safely modify." ,
@@ -742,7 +809,7 @@ FILENAME_HEAD: "Filename",
"ExcalidrawAutomate is a scripting and automation API for Excalidraw. Unfortunately, the documentation of the API is sparse. " +
"I recommend reading the <a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/API/ExcalidrawAutomate.d.ts'>ExcalidrawAutomate.d.ts</a> file, " +
"visiting the <a href='https://zsviczian.github.io/obsidian-excalidraw-plugin/'>ExcalidrawAutomate How-to</a> page - though the information " +
"here has not been updated for a long while -, and finally to enable the field suggester below. The field suggester will show you the available " +
"here has not been updated for a long while -, and finally to enable the field suggester below. The field suggester will show you the available " +
"functions, their parameters and short description as you type. The field suggester is the most up-to-date documentation of the API.",
FIELD_SUGGESTER_NAME: "Enable Field Suggester",
FIELD_SUGGESTER_DESC:
@@ -804,10 +871,10 @@ FILENAME_HEAD: "Filename",
<strong>Note:</strong> If you're using Obsidian Sync and want to synchronize these font files across your devices, ensure that Obsidian Sync is set to synchronize "All other file types".`,
LOAD_CHINESE_FONTS_NAME: "Load Chinese fonts from file at startup",
LOAD_JAPANESE_FONTS_NAME: "Load Japanese fonts from file at startup",
LOAD_KOREAN_FONTS_NAME: "Load Korean fonts frome file at startup",
LOAD_KOREAN_FONTS_NAME: "Load Korean fonts from file at startup",
SCRIPT_SETTINGS_HEAD: "Settings for installed Scripts",
SCRIPT_SETTINGS_DESC: "Some of the Excalidraw Automate Scripts include settings. Settings are organized by script. Settings will only become visible in this list after you have executed the newly downloaded script once.",
TASKBONE_HEAD: "Taskbone Optical Character Recogntion",
TASKBONE_HEAD: "Taskbone Optical Character Recognition",
TASKBONE_DESC: "This is an experimental integration of optical character recognition into Excalidraw. Please note, that taskbone is an independent external service not provided by Excalidraw, nor the Excalidraw-Obsidian plugin project. " +
"The OCR service will grab legible text from freedraw lines and embedded pictures on your canvas and place the recognized text in the frontmatter of your drawing as well as onto clipboard. " +
"Having the text in the frontmatter will enable you to search in Obsidian for the text contents of these. " +
@@ -816,7 +883,7 @@ FILENAME_HEAD: "Filename",
TASKBONE_ENABLE_DESC: "By enabling this service your agree to the Taskbone <a href='https://www.taskbone.com/legal/terms/' target='_blank'>Terms and Conditions</a> and the " +
"<a href='https://www.taskbone.com/legal/privacy/' target='_blank'>Privacy Policy</a>.",
TASKBONE_APIKEY_NAME: "Taskbone API Key",
TASKBONE_APIKEY_DESC: "Taskbone offers a free service with a reasonable number of scans per month. If you want to use this feature more frequently, or you want to supoprt " +
TASKBONE_APIKEY_DESC: "Taskbone offers a free service with a reasonable number of scans per month. If you want to use this feature more frequently, or you want to support " +
"the developer of Taskbone (as you can imagine, there is no such thing as 'free', providing this awesome OCR service costs some money to the developer of Taskbone), you can " +
"purchase a paid API key from <a href='https://www.taskbone.com/' target='_blank'>taskbone.com</a>. In case you have purchased a key, simply overwrite this auto generated free-tier API-key with your paid key.",
@@ -859,9 +926,13 @@ FILENAME_HEAD: "Filename",
SCRIPT_EXECUTION_ERROR:
"Script execution error. Please find error message on the developer console.",
//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 regulary then you may download the fonts locally to your Vault. \n\n" +
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)",
FONT_INFO_TITLE: "Starting v2.5.3 fonts load from the Internet",
FONT_INFO_DETAILED: `
@@ -903,8 +974,12 @@ FILENAME_HEAD: "Filename",
//IFrameActionsMenu.tsx
NARROW_TO_HEADING: "Narrow to heading...",
PIN_VIEW: "Pin view",
DO_NOT_PIN_VIEW: "Do not pin view",
NARROW_TO_BLOCK: "Narrow to block...",
SHOW_ENTIRE_FILE: "Show entire file",
SELECT_SECTION: "Select section from document",
SELECT_VIEW: "Select view from base",
ZOOM_TO_FIT: "Zoom to fit",
RELOAD: "Reload original link",
OPEN_IN_BROWSER: "Open current link in browser",
@@ -954,6 +1029,7 @@ FILENAME_HEAD: "Filename",
PROMPT_BUTTON_INSERT_SPACE: "Insert space",
PROMPT_BUTTON_INSERT_LINK: "Insert markdown link to file",
PROMPT_BUTTON_UPPERCASE: "Uppercase",
PROMPT_BUTTON_SPECIAL_CHARS: "Special Characters",
PROMPT_SELECT_TEMPLATE: "Select a template",
//ModifierKeySettings
@@ -983,6 +1059,7 @@ FILENAME_HEAD: "Filename",
//Utils.ts
UPDATE_AVAILABLE: `A newer version of Excalidraw is available in Community Plugins.\n\nYou are using ${PLUGIN_VERSION}.\nThe latest is`,
SCRIPT_UPDATES_AVAILABLE: `Script updates available - check the script store.\n\n${DEVICE.isDesktop ? `This message is available in console.log (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}If you have organized scripts into subfolders under the script store folder and have multiple copies of the same script, you may need to clean up unused versions to clear this alert. For private copies of scripts that should not be updated, store them outside the script store folder.`,
ERROR_PNG_TOO_LARGE: "Error exporting PNG - PNG too large, try a smaller resolution",
//modifierkeyHelper.ts
@@ -1093,6 +1170,59 @@ FILENAME_HEAD: "Filename",
EXPORTDIALOG_PDF_PROGRESS_DONE: "Export complete",
EXPORTDIALOG_PDF_PROGRESS_ERROR: "Error exporting PDF, check developer console for details",
// Screenshot tab
EXPORTDIALOG_NOT_AVAILALBE: "Sorry, this feature is only available when the drawing is open in the main Obsidian workspace.",
EXPORTDIALOG_TAB_SCREENSHOT: "Screenshot",
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
PDF_EXPORT_DESKTOP_ONLY: "PDF export is only available on desktop",
//UniversalInsertFileModal.ts
UIFM_TITLE: "Insert File From Vault",
UIFM_SECTION_HEAD: "Select section heading",
UIFM_ANCHOR: "Anchor to 100% of original size",
UIFM_ANCHOR_DESC: "This is a pro feature, use it only if you understand how it works. If enabled even if you change the size of the imported image in Excalidraw, the next time you open the drawing this image will pop back to 100% size. This is useful when embedding an atomic Excalidraw idea into another note and preserving relative sizing of text and icons.",
UIFM_BTN_EMBEDDABLE: "as Embeddable",
UIFM_BTN_PDF: "as Pdf",
UIFM_BTN_IMAGE: "as Image",
//ReleaseNotes.ts
RN_WELCOME: "Welcome to Excalidraw",
//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" +
"Control via this file's 'excalidraw-embeddable-theme' document property (overrides plugin).\n\n" +
"Values: dark, light, auto=Excalidraw, default=Obsidian.",
//EmbeddableActionsMenu.tsx
BOOKMARK_PAGE: "Save current position in document",
CAPTURE_PAGE: "Capture current page as image",
//VersionMismatch.ts
//WARNING: Do not change the {VAL_RECORDED} and {VAL_ACTUAL} strings, they are replaced by the actual version values at runtime!
VERSION_MISMATCH_NOTICE: `The version recorded by Obsidian is <b>{VAL_RECORDED}</b>, but the installed Excalidraw code is <b>{VAL_ACTUAL}</b>.`,
VERSION_MISMATCH_HEADING: "Excalidraw version mismatch",
VERSION_MISMATCH_CAUSE: "This usually happens after a partial sync (e.g. Obsidian Sync Standard) where large files (main.js > 5MB) did not sync, so only <code>manifest.json</code> updated.",
VERSION_MISMATCH_OPTIONS: "Options:<br><b>1.</b> Re-download the plugin (recommended).<br><b>2.</b> Ignore for now.",
VERSION_MISMATCH_NOTE: "Note: Updating version info manually may affect tools that read manifest.json directly (e.g. Plugin Update Tracker, BRAT) until a full reinstall.",
VERSION_MISMATCH_DISABLE_NAME: "Disable future mismatch warnings",
VERSION_MISMATCH_DISABLE_DESC: "You can re-enable this under: Settings → Excalidraw → Basic → Warn about incomplete plugin updates.",
VERSION_MISMATCH_REDOWNLOAD: "Re-download plugin",
VERSION_MISMATCH_IGNORE: "Ignore",
};
+1212 -2
View File
File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -345,7 +345,9 @@ FILENAME_HEAD: "Имя файла",
"конфликтуют с настройками горячих клавиш Obsidian. Комбинации горячих клавиш, которые вы добавите ниже, отменят настройки горячих клавиш Obsidian при использовании Excalidraw, таким образом " +
`Вы можете добавить <code>${labelCTRL()}+G</code>, если хотите по умолчанию перейти к Группе Объектов в Excalidraw вместо открытия Режима просмотра Графиков.`,
THEME_HEAD: "Тема и стиль",
ZOOM_HEAD: "Масштабирование",
ZOOM_AND_PAN_HEAD: "Масштаб и панорамирование",
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "Перемещение холста правой кнопкой мыши (открыть меню с 'm')",
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC: "Когда этот параметр включен, вы можете перемещать холст, нажимая правую кнопку мыши и перетаскивая. Контекстное меню откроется с помощью клавиши 'm', если только вы не редактируете текст.",
DEFAULT_PINCHZOOM_NAME: "Разрешить масштабирование в режиме пера",
DEFAULT_PINCHZOOM_DESC:
"По умолчанию зуммирование в режиме пера при использовании инструмента «Свободное рисование» отключено, чтобы предотвратить нежелательное случайное масштабирование с помощью ладони.<br>" +
+609 -480
View File
File diff suppressed because it is too large. Load diff
+1212 -2
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -1,6 +1,6 @@
import { ExcalidrawElement, FileId } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { ExcalidrawElement, FileId } from "@zsviczian/excalidraw/types/element/src/types";
import { BinaryFileData } from "@zsviczian/excalidraw/types/excalidraw/types";
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { Notice } from "obsidian";
import { getEA } from "src/core";
+4 -4
View File
@@ -1,5 +1,5 @@
import { ExcalidrawEmbeddableElement } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
import { ExcalidrawEmbeddableElement } from "@zsviczian/excalidraw/types/element/src/types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { Modal, Notice, Setting, TFile, ToggleComponent } from "obsidian";
import { getEA } from "src/core";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
@@ -12,6 +12,7 @@ import { getYouTubeStartAt, isValidYouTubeStart, isYouTube, updateYouTubeStartTi
import { EmbeddalbeMDFileCustomDataSettingsComponent } from "./EmbeddableMDFileCustomDataSettingsComponent";
import { isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
import { CaptureUpdateAction } from "src/constants/constants";
export type EmbeddableMDCustomProps = {
useObsidianDefaults: boolean;
@@ -49,7 +50,7 @@ export class EmbeddableSettings extends Modal {
this.zoomValue = element.scale[0];
this.isYouTube = isYouTube(this.element.link);
this.notExcalidrawIsInternal = this.file && !this.view.plugin.isExcalidrawFile(this.file)
this.isMDFile = this.file && this.file.extension === "md"; // && !this.view.plugin.isExcalidrawFile(this.file);
this.isMDFile = this.file && this.file.extension.toLowerCase() === "md"; // && !this.view.plugin.isExcalidrawFile(this.file);
this.isLocalURI = this.element.link.startsWith("file://");
if(isYouTube) this.youtubeStart = getYouTubeStartAt(this.element.link);
@@ -225,7 +226,6 @@ export class EmbeddableSettings extends Modal {
if(dirty) {
(async() => {
await this.ea.addElementsToView();
//@ts-ignore
this.ea.viewUpdateScene({appState: {}, captureUpdate: CaptureUpdateAction.NEVER});
this.close(); //close should only run once update scene is done
})();
+160 -44
View File
@@ -6,9 +6,11 @@ import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import ExcalidrawView from "src/view/ExcalidrawView";
import ExcalidrawPlugin from "src/core/main";
import { fragWithHTML, getExportPadding, getExportTheme, getPNGScale, getWithBackground, shouldEmbedScene } from "src/utils/utils";
import { PageOrientation, PageSize, PDFPageAlignment, PDFPageMarginString, exportSVGToClipboard } from "src/utils/exportUtils";
import { PageOrientation, PageSize, PDFPageAlignment, PDFPageMarginString, exportSVGToClipboard, exportPNG, exportPNGToClipboard } from "src/utils/exportUtils";
import { t } from "src/lang/helpers";
import { PDFExportSettings, PDFExportSettingsComponent } from "./PDFExportSettingsComponent";
import { captureScreenshot } from "src/utils/screenshot";
import { exportImageToFile, getIMGFilename } from "src/utils/fileUtils";
@@ -34,7 +36,7 @@ export class ExportDialog extends Modal {
public saveToVault: boolean;
public pageSize: PageSize = "A4";
public pageOrientation: PageOrientation = "portrait";
private activeTab: "image" | "pdf" = "image";
private activeTab: "image" | "pdf" | "screenshot" = "image";
private contentContainer: HTMLDivElement;
private buttonContainerRow1: HTMLDivElement;
private buttonContainerRow2: HTMLDivElement;
@@ -43,6 +45,7 @@ export class ExportDialog extends Modal {
public customPaperColor: string = "#ffffff";
public alignment: PDFPageAlignment = "center";
public margin: PDFPageMarginString = "normal";
private scaleSetting:Setting;
constructor(
private plugin: ExcalidrawPlugin,
@@ -86,12 +89,28 @@ export class ExportDialog extends Modal {
this.containerEl.remove();
}
get isSelectedOnly(): boolean {
return this.hasSelectedElements && this.exportSelectedOnly;
}
updateBoundingBox() {
if(this.isSelectedOnly) {
this.boundingBox = this.ea.getBoundingBox(this.view.getViewSelectedElements());
} else {
this.boundingBox = this.ea.getBoundingBox(this.ea.getViewElements());
}
if(this.scaleSetting) {
this.scaleSetting.setDesc(this.size());
}
}
onOpen(): void {
this.containerEl.classList.add("excalidraw-release");
this.titleEl.setText(t("EXPORTDIALOG_TITLE"));
this.hasSelectedElements = this.view.getViewSelectedElements().length > 0;
//@ts-ignore
this.selectedOnlySetting.setVisibility(this.hasSelectedElements);
this.updateBoundingBox();
}
async onClose() {
@@ -113,11 +132,17 @@ export class ExportDialog extends Modal {
cls: `nav-button ${this.activeTab === "pdf" ? "is-active" : ""}`
});
const screenshotTab = tabContainer.createEl("button", {
text: t("EXPORTDIALOG_TAB_SCREENSHOT"),
cls: `nav-button ${this.activeTab === "screenshot" ? "is-active" : ""}`
});
// Tab click handlers
imageTab.onclick = () => {
this.activeTab = "image";
imageTab.addClass("is-active");
pdfTab.removeClass("is-active");
screenshotTab.removeClass("is-active");
this.renderContent();
};
@@ -125,8 +150,17 @@ export class ExportDialog extends Modal {
this.activeTab = "pdf";
pdfTab.addClass("is-active");
imageTab.removeClass("is-active");
screenshotTab.removeClass("is-active");
this.renderContent();
};
screenshotTab.onclick = () => {
this.activeTab = "screenshot";
screenshotTab.addClass("is-active");
imageTab.removeClass("is-active");
pdfTab.removeClass("is-active");
this.renderContent();
}
}
// Create content container
@@ -157,32 +191,62 @@ export class ExportDialog extends Modal {
this.buttonContainerRow1.empty();
this.buttonContainerRow2.empty();
if (this.activeTab === "image") {
this.createImageSettings();
this.createExportSettings();
this.createImageButtons();
} else {
this.createImageSettings();
this.createPDFSettings();
this.createPDFButton();
this.createHeader();
switch (this.activeTab) {
case "pdf":
this.createImageSettings();
this.createPDFSettings();
this.createPDFButton();
break;
case "screenshot":
if(this.view.isInMainObsidianWorkspace) {
this.createImageSettings(true);
this.createImageButtons(true);
}
break;
case "image":
default:
this.createImageSettings(false);
this.createExportSettings();
this.createImageButtons();
break;
}
}
private size ():DocumentFragment {
const width = Math.round(this.scale*this.boundingBox.width + this.padding*2);
const height = Math.round(this.scale*this.boundingBox.height + this.padding*2);
return fragWithHTML(`${t("EXPORTDIALOG_SIZE_DESC")}<br>${t("EXPORTDIALOG_SCALE_VALUE")} <b>${this.scale}</b><br>${t("EXPORTDIALOG_IMAGE_SIZE")} <b>${width}x${height}</b>`);
}
private createHeader() {
switch (this.activeTab) {
case "pdf":
this.contentContainer.createEl("h1",{text: t("EXPORTDIALOG_PDF_SETTINGS")});
//this.contentContainer.createEl("p",{text: t("EXPORTDIALOG_PDF_DESC")});
break;
case "screenshot":
this.contentContainer.createEl("h1",{text: t("EXPORTDIALOG_TAB_SCREENSHOT")});
if(this.view.isInMainObsidianWorkspace) {
this.contentContainer.createEl("p",{text: t("EXPORTDIALOG_SCREENSHOT_DESC")})
} else {
this.contentContainer.createEl("p",{text: t("EXPORTDIALOG_NOT_AVAILALBE")})
}
break;
case "image":
default:
this.contentContainer.createEl("h1",{text: t("EXPORTDIALOG_IMAGE_SETTINGS")});
this.contentContainer.createEl("p",{text: t("EXPORTDIALOG_IMAGE_DESC")})
break;
}
}
private createImageSettings() {
let scaleSetting:Setting;
private createImageSettings(isScreenshot: boolean = false) {
let paddingSetting: Setting;
this.contentContainer.createEl("h1",{text: t("EXPORTDIALOG_IMAGE_SETTINGS")});
this.contentContainer.createEl("p",{text: t("EXPORTDIALOG_IMAGE_DESC")})
this.createSaveSettingsDropdown();
const size = ():DocumentFragment => {
const width = Math.round(this.scale*this.boundingBox.width + this.padding*2);
const height = Math.round(this.scale*this.boundingBox.height + this.padding*2);
return fragWithHTML(`${t("EXPORTDIALOG_SIZE_DESC")}<br>${t("EXPORTDIALOG_SCALE_VALUE")} <b>${this.scale}</b><br>${t("EXPORTDIALOG_IMAGE_SIZE")} <b>${width}x${height}</b>`);
}
const padding = ():DocumentFragment => {
return fragWithHTML(`${t("EXPORTDIALOG_CURRENT_PADDING")} <b>${this.padding}</b>`);
}
@@ -196,21 +260,21 @@ export class ExportDialog extends Modal {
.setValue(this.padding)
.onChange(value => {
this.padding = value;
scaleSetting.setDesc(size());
this.scaleSetting.setDesc(this.size());
paddingSetting.setDesc(padding());
})
})
scaleSetting = new Setting(this.contentContainer)
this.scaleSetting = new Setting(this.contentContainer)
.setName(t("EXPORTDIALOG_SCALE"))
.setDesc(size())
.setDesc(this.size())
.addSlider(slider =>
slider
.setLimits(0.2,7,0.1)
.setValue(this.scale)
.onChange(value => {
this.scale = value;
scaleSetting.setDesc(size());
this.scaleSetting.setDesc(this.size());
})
)
@@ -226,17 +290,19 @@ export class ExportDialog extends Modal {
})
)
new Setting(this.contentContainer)
.setName(t("EXPORTDIALOG_BACKGROUND"))
.addDropdown(dropdown =>
dropdown
.addOption("transparent", t("EXPORTDIALOG_BACKGROUND_TRANSPARENT"))
.addOption("with-color", t("EXPORTDIALOG_BACKGROUND_USE_COLOR"))
.setValue(this.transparent?"transparent":"with-color")
.onChange(value => {
this.transparent = value === "transparent";
})
)
if(!isScreenshot) {
new Setting(this.contentContainer)
.setName(t("EXPORTDIALOG_BACKGROUND"))
.addDropdown(dropdown =>
dropdown
.addOption("transparent", t("EXPORTDIALOG_BACKGROUND_TRANSPARENT"))
.addOption("with-color", t("EXPORTDIALOG_BACKGROUND_USE_COLOR"))
.setValue(this.transparent?"transparent":"with-color")
.onChange(value => {
this.transparent = value === "transparent";
})
)
}
this.selectedOnlySetting = new Setting(this.contentContainer)
.setName(t("EXPORTDIALOG_SELECTED_ELEMENTS"))
@@ -247,8 +313,11 @@ export class ExportDialog extends Modal {
.setValue(this.exportSelectedOnly?"selected":"all")
.onChange(value => {
this.exportSelectedOnly = value === "selected";
this.updateBoundingBox();
})
);
//@ts-ignore
this.selectedOnlySetting.setVisibility(this.hasSelectedElements);
}
private createExportSettings() {
@@ -295,14 +364,29 @@ export class ExportDialog extends Modal {
).render();
}
private createImageButtons() {
private createImageButtons(isScreenshot: boolean = false) {
if(DEVICE.isDesktop) {
const bPNG = this.buttonContainerRow1.createEl("button", {
text: t("EXPORTDIALOG_PNGTOFILE"),
cls: "excalidraw-export-button"
});
bPNG.onclick = () => {
this.view.exportPNG(this.embedScene, this.hasSelectedElements && this.exportSelectedOnly);
if(isScreenshot) {
//allow dialog to close before taking screenshot
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);
}
});
} else {
this.view.exportPNG(this.embedScene, this.isSelectedOnly);
}
this.close();
};
}
@@ -312,7 +396,22 @@ export class ExportDialog extends Modal {
cls: "excalidraw-export-button"
});
bPNGVault.onclick = () => {
this.view.savePNG(this.view.getScene(this.hasSelectedElements && this.exportSelectedOnly));
if(isScreenshot) {
//allow dialog to close before taking screenshot
setTimeout(async () => {
const png = await captureScreenshot(this.view, {
zoom: this.scale,
margin: this.padding,
selectedOnly: this.isSelectedOnly,
theme: this.theme
});
if(png) {
exportImageToFile(this.view, getIMGFilename(this.view.file.path,"png"), png, ".png");
}
});
} else {
this.view.savePNG({scene: this.view.getScene(this.isSelectedOnly)});
}
this.close();
};
@@ -321,10 +420,27 @@ export class ExportDialog extends Modal {
cls: "excalidraw-export-button"
});
bPNGClipboard.onclick = async () => {
this.view.exportPNGToClipboard(this.embedScene, this.hasSelectedElements && this.exportSelectedOnly);
if(isScreenshot) {
//allow dialog to close before taking screenshot
setTimeout(async () => {
const png = await captureScreenshot(this.view, {
zoom: this.scale,
margin: this.padding,
selectedOnly: this.isSelectedOnly,
theme: this.theme
});
if(png) {
exportPNGToClipboard(png);
}
});
} else {
this.view.exportPNGToClipboard(this.embedScene, this.isSelectedOnly);
}
this.close();
};
if(isScreenshot) return;
if(DEVICE.isDesktop) {
const bExcalidraw = this.buttonContainerRow2.createEl("button", {
text: t("EXPORTDIALOG_EXCALIDRAW"),
@@ -340,7 +456,7 @@ export class ExportDialog extends Modal {
cls: "excalidraw-export-button"
});
bSVG.onclick = () => {
this.view.exportSVG(this.embedScene, this.hasSelectedElements && this.exportSelectedOnly);
this.view.exportSVG(this.embedScene, this.isSelectedOnly);
this.close();
};
}
@@ -350,7 +466,7 @@ export class ExportDialog extends Modal {
cls: "excalidraw-export-button"
});
bSVGVault.onclick = () => {
this.view.saveSVG(this.view.getScene(this.hasSelectedElements && this.exportSelectedOnly));
this.view.saveSVG({scene: this.view.getScene(this.isSelectedOnly)});
this.close();
};
@@ -359,7 +475,7 @@ export class ExportDialog extends Modal {
cls: "excalidraw-export-button"
});
bSVGClipboard.onclick = async () => {
const svg = await this.view.getSVG(this.embedScene, this.hasSelectedElements && this.exportSelectedOnly);
const svg = await this.view.getSVG(this.embedScene, this.isSelectedOnly);
exportSVGToClipboard(svg);
this.close();
};
@@ -392,7 +508,7 @@ export class ExportDialog extends Modal {
});
bPDFExport.onclick = () => {
this.view.exportPDF(
this.hasSelectedElements && this.exportSelectedOnly,
this.isSelectedOnly,
this.pageSize,
this.pageOrientation
);
+208
View File
@@ -0,0 +1,208 @@
import { App, Modal } from "obsidian";
export class FloatingModal extends Modal {
private dragging = false;
private offsetX = 0;
private offsetY = 0;
private pointerDownHandler: (e: PointerEvent | TouchEvent) => void;
private pointerMoveHandler: (e: PointerEvent | TouchEvent) => void;
private pointerUpHandler: () => void;
private disableKeyCapture = true; // new flag: when true, let keystrokes pass through to workspace
private previousActive: HTMLElement | null = null; // stores element focused before opening
private escListener: (e: KeyboardEvent) => void;
private modalKeydownStopHandler: (e: KeyboardEvent) => void; // store handler so we can remove it
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.escListener = this.handleEscKey.bind(this);
this.modalKeydownStopHandler = (ev: KeyboardEvent) => ev.stopPropagation();
}
private handlePointerDown(e: PointerEvent | TouchEvent): void {
// Get the target element
const target = e.target as HTMLElement;
// Ignore if clicking on interactive elements
if (
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement ||
target instanceof HTMLSelectElement ||
target instanceof HTMLButtonElement ||
target.closest(".clickable-icon")
) {
return;
}
// For touch events, prevent default behavior to avoid Obsidian's handling
if (e.type === "touchstart") {
e.preventDefault();
e.stopPropagation();
if ((e as TouchEvent).touches.length !== 1) return;
const touch = (e as TouchEvent).touches[0];
this.dragging = true;
const { modalEl } = this;
this.offsetX = touch.clientX - modalEl.getBoundingClientRect().left;
this.offsetY = touch.clientY - modalEl.getBoundingClientRect().top;
// Add touch-specific event listeners
document.addEventListener("touchmove", this.pointerMoveHandler as (e: TouchEvent) => void, {
passive: false,
});
document.addEventListener("touchend", this.pointerUpHandler);
document.addEventListener("touchcancel", this.pointerUpHandler);
} else {
// Handle pointer events
this.dragging = true;
const { modalEl } = this;
const pointerEvent = e as PointerEvent;
this.offsetX = pointerEvent.clientX - modalEl.getBoundingClientRect().left;
this.offsetY = pointerEvent.clientY - modalEl.getBoundingClientRect().top;
// Add pointer-specific event listeners
document.addEventListener("pointermove", this.pointerMoveHandler as (e: PointerEvent) => void);
document.addEventListener("pointerup", this.pointerUpHandler);
// Capture the pointer to ensure we get events even when outside the target
target.setPointerCapture(pointerEvent.pointerId);
}
}
private handlePointerMove(e: PointerEvent | TouchEvent): void {
if (!this.dragging) return;
const { modalEl } = this;
// Prevent default behavior
e.preventDefault();
if (e.type === "touchmove") e.stopPropagation();
let clientX, clientY;
if (e.type === "touchmove") {
const touch = (e as TouchEvent).touches[0];
clientX = touch.clientX;
clientY = touch.clientY;
} else {
const pointerEvent = e as PointerEvent;
clientX = pointerEvent.clientX;
clientY = pointerEvent.clientY;
}
const x = clientX - this.offsetX;
const y = clientY - this.offsetY;
// Position the modal element
modalEl.style.left = `${x}px`;
modalEl.style.top = `${y}px`;
modalEl.style.transform = "none"; // Remove centering transform
}
private handlePointerUp(): void {
this.dragging = false;
// Remove all event listeners
document.removeEventListener("pointermove", this.pointerMoveHandler as (e: PointerEvent) => void);
document.removeEventListener("pointerup", this.pointerUpHandler);
document.removeEventListener("touchmove", this.pointerMoveHandler as (e: TouchEvent) => void);
document.removeEventListener("touchend", this.pointerUpHandler);
document.removeEventListener("touchcancel", this.pointerUpHandler);
}
private handleEscKey(e: KeyboardEvent) {
if (e.key === "Escape") {
// Optionally stop propagation if you do not want other handlers firing
e.stopPropagation();
this.close();
}
}
open(): void {
super.open();
// NEW: capture previously focused element & release Obsidian modal key trapping
if (this.disableKeyCapture) {
this.previousActive = document.activeElement as HTMLElement | null;
try {
// @ts-ignore pop modal's key scope so keys are not intercepted
this.app.keymap.popScope(this.scope);
} catch {}
try {
// @ts-ignore prevent automatic selection / focus restoration
this.shouldRestoreSelection = false;
} catch {}
}
setTimeout(() => {
//@ts-ignore
const { containerEl, modalEl, bgEl, headerEl } = this;
containerEl.style.pointerEvents = "none";
if (bgEl) bgEl.style.display = "none";
if (headerEl) headerEl.style.pointerEvents = "none";
// Set initial position and make modal draggable
if (modalEl) {
modalEl.style.pointerEvents = "auto";
// Position absolute is needed for custom positioning
modalEl.style.position = "absolute";
// Center the modal initially
const rect = modalEl.getBoundingClientRect();
const centerX = window.innerWidth / 2 - rect.width / 2;
const centerY = window.innerHeight / 2 - rect.height / 2;
modalEl.style.left = `${centerX}px`;
modalEl.style.top = `${centerY}px`;
modalEl.style.transform = "none";
const modalStyle = window.getComputedStyle(modalEl);
modalEl.style.borderBottomLeftRadius = modalStyle.borderTopLeftRadius;
modalEl.style.borderBottomRightRadius = modalStyle.borderTopRightRadius;
// 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,
});
if (this.disableKeyCapture) {
// Prevent the modal from stealing focus
modalEl.setAttr("tabindex", "-1");
// Refocus previous element (if still in DOM)
if (this.previousActive?.isConnected) {
this.previousActive.focus({ preventScroll: true });
}
// Stop key events originating inside the modal from bubbling back
modalEl.addEventListener("keydown", this.modalKeydownStopHandler, { capture: true });
}
// Add ESC listener (capture to run before underlying workspace)
document.addEventListener("keydown", this.escListener, { capture: true });
}
});
}
close(): void {
// Optional: restore previous focus if body ended up focused
if (this.disableKeyCapture && this.previousActive?.isConnected && document.activeElement === document.body) {
try { this.previousActive.focus({ preventScroll: true }); } catch {}
}
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);
// Remove the capturing keydown stopper if it was added
modalEl.removeEventListener("keydown", this.modalKeydownStopHandler, { capture: true });
}
// Remove any remaining document event listeners
this.handlePointerUp();
document.removeEventListener("keydown", this.escListener, { capture: true });
super.close();
}
// (Optional helper if you want to toggle later)
enableKeyCapture() { this.disableKeyCapture = false; }
disableKeyCaptureFn() { this.disableKeyCapture = true; }
}
+13 -13
View File
@@ -1,22 +1,25 @@
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { t } from "src/lang/helpers";
import { CaptureUpdateAction } from "src/constants/constants";
import { FloatingModal } from "./FloatingModal";
import ExcalidrawView from "src/view/ExcalidrawView";
import { Setting } from "obsidian";
export const showFrameSettings = (ea: ExcalidrawAutomate) => {
const {enabled, clip, name, outline} = ea.getExcalidrawAPI().getAppState().frameRendering;
export const showFrameSettings = (view: ExcalidrawView) => {
const {enabled, clip, name, outline, markerName, markerEnabled} = view.excalidrawAPI.getAppState().frameRendering;
// Create modal dialog
const frameSettingsModal = new ea.obsidian.Modal(ea.plugin.app);
const frameSettingsModal = new FloatingModal(view.app);
frameSettingsModal.onOpen = () => {
const {contentEl} = frameSettingsModal;
contentEl.createEl("h1", {text: t("FRAME_SETTINGS_TITLE")});
const settings = { enabled, clip, name, outline };
const settings = { enabled, clip, name, outline, markerName, markerEnabled };
// Add toggles
const enableFramesSetting = new ea.obsidian.Setting(contentEl)
new Setting(contentEl)
.setName(t("FRAME_SETTINGS_ENABLE"))
.addToggle(toggle => toggle
.setValue(settings.enabled)
@@ -28,21 +31,21 @@ export const showFrameSettings = (ea: ExcalidrawAutomate) => {
})
);
const displayFrameNameSetting = new ea.obsidian.Setting(contentEl)
const displayFrameNameSetting = new Setting(contentEl)
.setName(t("FRAME_SETTIGNS_NAME"))
.addToggle(toggle => toggle
.setValue(settings.name)
.onChange(value => settings.name = value)
);
const displayFrameOutlineSetting = new ea.obsidian.Setting(contentEl)
const displayFrameOutlineSetting = new Setting(contentEl)
.setName(t("FRAME_SETTINGS_OUTLINE"))
.addToggle(toggle => toggle
.setValue(settings.outline)
.onChange(value => settings.outline = value)
);
const enableFrameClippingSetting = new ea.obsidian.Setting(contentEl)
const enableFrameClippingSetting = new Setting(contentEl)
.setName(t("FRAME_SETTINGS_CLIP"))
.addToggle(toggle => toggle
.setValue(settings.clip)
@@ -55,12 +58,12 @@ export const showFrameSettings = (ea: ExcalidrawAutomate) => {
hideComponent(enableFrameClippingSetting, !settings.enabled);
// Add OK button
new ea.obsidian.Setting(contentEl)
new Setting(contentEl)
.addButton(button => button
.setButtonText("OK")
.onClick(() => {
// Update appState with new settings
ea.viewUpdateScene({
view.updateScene({
// @ts-ignore
appState: {
frameRendering: settings
@@ -72,9 +75,6 @@ export const showFrameSettings = (ea: ExcalidrawAutomate) => {
);
};
frameSettingsModal.onClose = () => {
ea.destroy();
}
frameSettingsModal.open();
};
@@ -1,5 +1,4 @@
import { App, FuzzySuggestModal, TFile } from "obsidian";
import { REG_LINKINDEX_INVALIDCHARS } from "../../constants/constants";
import { t } from "../../lang/helpers";
export class InsertCommandDialog extends FuzzySuggestModal<TFile> {
+2 -2
View File
@@ -70,7 +70,7 @@ export class InsertPDFModal extends Modal {
this.setImageSizeMessage = null;
}
private async getPageDimensions (pdfDoc: any) {
private async getPDFPageDimensions (pdfDoc: any) {
try {
const scale = this.plugin.settings.pdfScale;
const canvas = createEl("canvas");
@@ -197,7 +197,7 @@ export class InsertPDFModal extends Modal {
rangeOnChange(`1-${numPages}`);
importButtonMessages();
numPagesMessages();
this.getPageDimensions(this.pdfDoc);
this.getPDFPageDimensions(this.pdfDoc);
} else {
importButton.setDisabled(true);
}
+306 -158
View File
@@ -11,12 +11,315 @@ Thank you & Enjoy!
`;
export const RELEASE_NOTES: { [k: string]: string } = {
Intro: `After each update you'll be prompted with the release notes. You can disable this in plugin settings.
Intro: `After each update, you’ll see these release notes (you can turn this off in the plugin settings).
I develop this plugin as a hobby, spending my free time doing this. If you find it valuable, then please say THANK YOU or...
I build this plugin in my free time, as a labor of love. Curious about the philosophy behind it? Check out [📕 Sketch Your Mind](https://sketch-your-mind.com). If you find it valuable, say THANK YOU or…
<div class="ex-coffee-div"><a href="https://ko-fi.com/zsolt"><img src="https://storage.ko-fi.com/cdn/kofi6.png?v=6" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
`,
"2.15.3":`
## Fixed
- New back of the note cards are not visible until the drawing is saved. When adding a back-of-the-note card using the context menu, the card got placed at the absolute 0,0 position in the scene instead of the current pointer position. [#9949](https://github.com/excalidraw/excalidraw/issues/9949)
- Drawings created 4 years ago don't open [#2479](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2479)
- On Obsidian Mobile, when an element has multiple links, clicking the link icon, the link selector pops up and immediately closes
- Improved handling of importing external images and drag and drop of images from inside Obsidian. Features like (Convert SVG to Strokes) and (Flip the card) now work immediately, you don't need to force save, or wait for autosave to kick in.
## New
- Added startup check that detects when Obsidian's recorded plugin version differs from the installed Excalidraw code (e.g. after partial sync of large files) and offers to update or ignore, with a setting to disable the check.
- When Excalidraw is open in two or more tabs—either as Markdown or Excalidraw—auto-zoom is disabled. This allows you to work in multiple tabs on the same drawing at once: focusing on different areas of the same drawing, or editing the Markdown and Excalidraw views in parallel.
`,
"2.15.2":`
## Fixed:
- Pressing enter on a text element erroneously activated all markdown embeddables in the scene. [discord](https://discord.com/channels/1026825302900494357/1412683408424833045)
- After updating to PDF++ 0.40.31, touch scrolling of embedded PDF documents stopped working on mobile devices, and the PDF document appeared with the wrong themes in some cases.
- Issue with the Kanban board as an active embeddable on mobile phones is fixed.
## Fixed in ExcalidrawAutomate
- \`getActiveEmbeddableViewOrEditor (view?:ExcalidrawView): {view:any}|{file:TFile, editor:Editor}|{node: ObsidianCanvasNode}|null;\` no returns the node, instead of the empty view from the leaf.
`,
"2.15.1":`
## Fixed
- PDF improvements
- It was not possible to scroll the embedded PDF. [#9891](https://github.com/excalidraw/excalidraw/pull/9891)
- Embedded PDF pages were blurred (pixelated).
- Embedded PDF now accurately follows \`excalidraw-embeddable-theme\` document property.
- auto: follows Excalidraw theme (regardless of Obsidian theme)
- default: follows Obsidian theme (regardless of Excalidraw theme)
- dark: always displays the PDF in dark mode (regardless of Excalidraw and Obsidian themes)
- light: always displays the PDF in light mode (regardless of Excalidraw and Obsidian themes)
- New embeddable-menu buttons:
- Snapshot: inserts an image of the current active page to the scene
- Bookmark: updates the embed link to the current page
- Pasting an oversized image triggered an error and caused Excalidraw to discard the scene. [#2453](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2453), [#9878](https://github.com/excalidraw/excalidraw/issues/9878)
- Video with local URI will no longer autoplay when the scene loads
- Error creating link to element when element is a sticky note
- Area link embeds hide the content of the objects within the area [#2461](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2461)
- On Obsidian Mobile 1.9.10, embeddables could cause a black/white screen (no active view) until reselecting the Excalidraw page; [#2460](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2460)
- Scrolling of embedded web pages on mobile devices is working again.
## New
- Insert Any File now supports adding Audio files.
- New option in settings under "Zoom and Pan". Pan with right mouse button (Miro-style): right-click and drag to pan the canvas. Press 'm' for the context menu (disabled while editing text). 🙏 [@mfuria](https://github.com/mfuria) for making this happen! [#2450](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2450), [#329](https://github.com/zsviczian/excalidraw/pull/329)
- Insert image in the main toolbar now opens a dropdown menu of options: Insert from system, insert from Vault, insert Card, and insert LaTeX. [#2448](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2448)
## Deprecated
- Removed "Toggle RAW mode" from the Command Palette and the Obsidian Tools menu due to low usage. RAW mode remains available by adding \`excalidraw-plugin: raw\` to the note's YAML frontmatter/document properties.
## New in ExcalidrawAutomate
\`\`\`ts
/**
* Returns the center position of the current view in Excalidraw coordinates.
* @returns {{x:number, y:number}} The center position of the view.
*/
public getViewCenterPosition(): {x:number, y:number};
\`\`\`
`,
"2.15.0":`
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/DqDnzCOoYMc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
## New
- Introducing **Marker Frames**. These are special frames that can be used to mark slides, pages areas for PDF printouts, image references, etc.
To create a marker frame, create a frame and toggle the marker frame in the elements properties panel.
- Markers are not included in exports such as images or PDFs.
- Markers do not contain elements
- Markers can be hidden/shown from the canvas context menu
- Updated the "Printable Layout Wizard" script
- Now works with marker frames
- Supports different page sizes and orientations within a single PDF document
- The printout may include non-marker frames (e.g., PDF image embeds in frames)
- Pro-tip: You can also use marker frames...
- with the Slideshow plugin
- to create image-area references such that the frames do not get rendered in exported images, and you can reference areas by frame name
- Performance improvement of Image-area references
# New in ExcalidrawAutomate
- \`createPDF()\` now supports \`SVG[]\` array of SVGs with different sizes.
- New function:
\`\`\`ts
/**
* Gets the elements within a specific area.
* @param elements - The elements to check.
* @param param1 - The area to check against.
* @returns The elements within the area.
*/
elementsInArea(
elements: NonDeletedExcalidrawElement[],
{x, y, width, height}:{
x:number; y:number; width:number; height:number;
}
):ExcalidrawElement[]
\`\`\`
`,
"2.14.3":`
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/29EWeglRm7s" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
Updated the Printable Layout Wizard script with the option to exclude empty pages.
## Fixed
- If a frame is locked, elements created over the frame or dragged over the frame should not be auto-added to the frame. [#9850](https://github.com/excalidraw/excalidraw/issues/9850)
## Fixed in ExcalidrawAutomate
- Not all AppState properties were being correctly copied to the template when creating a new drawing with ea.create() [#2440](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2440)
`,
"2.14.2":`
## Fixed
- Converting Markdown to Excalidraw ("Back of note"/"Convert markdown to ExcaliDrawing") no longer appends T00:00:00.000Z to an existing date frontmatter field and handles merging of lists such as tags intelligently [#2414](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2414)
- Multi‑point line creation on touchscreens (tap–tap–tap) produced a horizontal line after using a pen. Fixed. [#9840](https://github.com/excalidraw/excalidraw/pull/9840#issuecomment-3165319266)
## New
- Zoom settings (Settings → Excalidraw → Appearance and Behavior → Zoom) [#2434](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2434):
- Zoom increment (default 5%) to fine‑tune mouse wheel / gesture precision.
- Minimum zoom (default 10%) controls how far you can zoom out (below 10% may be unstable—use with caution).
- Maximum zoom (default 3000%) defines the upper zoom limit.
- Palm Guard script (in script store): Mobile-friendly drawing mode for stylus users. Enters fullscreen, hides UI, shows a draggable minimal toolbar (toggle + exit) to prevent accidental palm taps; single tap to exit. Inspired by [#2409](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2409)
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/A_udjVjgWN0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
## ExcalidrawAutomate
- Improved \`FloatingModal\` behavior. Floating Modal now does not trap keyboard events, the header element does not block "X" button in the top right corner, all four corners are rounded on Mobile Devices.
`,
"2.14.1":`
## Fixed
- Excalidraw broke Obsidian's UI in Arabic, Persian, and Hebrew due to LTR, RTL conflict. [#2423](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2423)
- Styling issues impacting native Obsidian search/replace dialogs. [#2420](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2420)
- Now using native Obsidian attachment location function. 🙏 [mnaoumov](https://github.com/mnaoumov) [#2421](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2421), potentially fixes [#179](https://github.com/RainCat1998/obsidian-custom-attachment-location/issues/179) of the Obsidian Custom Attachment Location plugin issue.
## New
- New frontmatter option \`excalidraw-embed-md\`. When set to \`true\`, embedding the drawing into a markdown note will render the "back of the note" (its markdown content) instead of rendering it as an image.
- If you want to always display the drawing as an image, even when \`excalidraw-embed-md\` is enabled, use the special embed syntax: \`![[drawing#^as-image]]\`. Here, \`as-image\` is a phantom block reference that forces image rendering.
- Added Spanish translation by [@Joakim31](https://github.com/Joakim31) [#2425](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2425)
- Incremental minor updates from the main [Excalidraw project](https://github.com/excalidraw/excalidraw).
`,
"2.14.0":`
## A Big "Small" Update
- Added search to Excalidraw Settings, plus added a link to access the public NotebookLM workbook pre-loaded with everything about the plugin
- New Taiwan-idiomatic Traditional Chinese translation by [@rlan](https://github.com/rlan) [#2413](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2413)
`,
"2.13.2":`
## New
- Excalidraw now properly supports drag and drop of obsidian links from Bases.
- ExcalidrawAutomate exposes a new class: \`FloatingModal\`. This is a modified version of the Obsidian.Modal class that allows the modal to be dragged around the screen and that does not dim the background. You can use it to create custom dialogs that behave like Obsidian modals but with more flexibility.
`,
"2.13.1":`
## New
- Support for Obsidian bases as embeddables in Excalidraw.
- **Note:** The feature is only available to Insiders who have Obsidian 1.9.4 or later installed.
- If your base includes multiple views you can pin the desired view similar to filtering to a section (click top left # button; \`[[my.base|my view]]\`).
## Fixed
- Cannot type in embedded web forms. In certain cases, typing within these embeds would trigger Excalidraw hotkeys instead of interacting with the embedded content. [#2403](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2403)
`,
"2.13.0":`
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/QzhyQb4JF3Q" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
## New
- **Flexible Auto-Export Location:** Take control of where your auto-exported .png, .svg, and .excalidraw files are saved. Addressing a long-standing request, you can now define custom output paths using the new **Excalidraw Hooks**.
- Implement the \`onImageExportPathHook\` callback in your ExcalidrawAutomate startup script to control the *destination path*.
- Get the skeleton script via plugin settings or download it [here](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/refs/heads/master/src/constants/assets/startupScript.md).
- **Control Auto-Export Trigger:** Use the \`onTriggerAutoexportHook\` in your startup script to decide *if* and *how* auto-export runs for a file, based on its properties or frontmatter, *before* the export path is determined.
- **Improved "Open Excalidraw drawing":** The Command Palette command now searches the *entire Vault* for the matching Excalidraw file when used on an embedded .svg or .png, useful when exports are in different folders.
- **Placeholder Files for New Embeds:** When embedding a new drawing as PNG/SVG via the Command Palette, empty placeholder files are now created immediately based on your auto-export setting. This ensures Obsidian correctly updates links if you rename the file soon after creation (when "Keep filenames in sync" is on).
- **Paste Obsidian URLs into Excalidraw:** Pasting an Obsidian URL for an image or file into Excalidraw now inserts the associated image directly into the drawing.
- **\`onImageFilePathHook\` Drag & Drop Support:** The \`onImageFilePathHook\` (for controlling location/filename of *embedded* files) is now triggered when dragging and dropping files into Excalidraw from outside Obsidian, matching the existing behavior for pasting.
## New in ExcalidrawAutomate
\`\`\`ts
splitFolderAndFilename(filepath: string) : {
folderpath: string;
filename: string;
basename: string;
extension: string;
}
\`\`\`
`,
"2.12.4":`
## Fixed
- ExaliBrain did not render after the 2.12.3 update. [#2384](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2384)
`,
"2.12.3":`
## Minor fixes
- Includes all recent updates and fixes from excalidraw.com
- Fixed issue with line editor snapping out of edit mode
- Fixed long-standing issue with wireframe to code calling a deprecated OpenAI endpoint
- "Load Excalidraw Properties into Obsidian Suggester" setting now defaults to false for new installations. [#2380](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2380)
- Taskbone OCR result does not get saved to frontmatter in some cases [#1123](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1123)
## New
- If the cropped file or annotated file prefix is set to empty, there will now be no prefix added to the file name. Additionally, now you can also set a suffix to the file name. [#2370](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2370)
`,
"2.12.2": `
## Fixed
- BUG: Excalidraw theme changes to Light from Dark when clicking line element node [#2360](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2360)
`,
"2.12.1": `
## New
- "Text to Path" text input window is now draggable.
## Fixed
- Minor fixes to the Polygon line feature introduced in 2.12.0. [#9580](https://github.com/excalidraw/excalidraw/pull/9580)
- Fix new Improved Unlock UI, where if a lock element was over an unlocked element, the unlocked element was not selectable. [#9582](https://github.com/excalidraw/excalidraw/pull/9582)
- Fixed ghost point issue when moving a shape after dragging a point in the line editor [#9530](https://github.com/excalidraw/excalidraw/pull/9530)
## New in ExcalidrawAutomate
${String.fromCharCode(96,96,96)}js
untils.inputPrompt({
header: string,
placeholder?: string,
value?: string,
buttons?: { caption: string; tooltip?:string; action: Function }[],
lines?: number,
displayEditorButtons?: boolean,
customComponents?: (container: HTMLElement) => void,
blockPointerInputOutsideModal?: boolean,
controlsOnTop?: boolean,
draggable?: boolean,
});
${String.fromCharCode(96,96,96)}
`,
"2.12.0": `
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/-fldh3cE2gs" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
## Fixed
- Dynamic styling was not working when frames were present in the scene.
- Minor fix to the screenshot feature. This also resolves the long-standing issue where window control buttons (close, minimize, maximize) appeared in full-screen mode.
- Fixed an issue where ALT/OPT + dragging an embeddable object sometimes failed, resulting in an empty object instead of dragging the element.
## New
- **Line Polygons**: Draw a closed line shape, and it will automatically snap into a polygon. [#9477](https://github.com/excalidraw/excalidraw/pull/9477)
- Updated the Split Ellipse and Boolean Operations scripts to support this feature.
- When entering line editor mode (CTRL/CMD + click), the lock point is now marked for easier editing. You can break the polygon using the polygon action in the elements panel.
- **Popout Override**: The "Open the back-of-the-note for the selected image in a popout window" action now overrides the "Focus on Existing Tab" setting and always opens a new popout.
- **Text Arch Enhancements**: The Text Arch script now supports fitting text to a wider range of paths and shapes. Text can also be edited and refitted to different paths.
- **Improved Unlock UI**: Single-clicking a locked element now shows an unlock button. [#9546](https://github.com/excalidraw/excalidraw/pull/9546)
- **Script Update Alerts**: On startup, Excalidraw will notify you if any installed scripts have available updates.
`,
"2.11.1": `
## Fixed:
- The new "Screenshot" option in the Export Image dialog was not working properly. [#2339](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2339)
## New from Excalidraw.com
- Quarter snap points for diamonds [#9387](https://github.com/excalidraw/excalidraw/pull/9387)
- Precise highlights for bindings [#9472](https://github.com/excalidraw/excalidraw/pull/9472)
`,
"2.11.0": `
## New
- New "Screenshot" option in the Export Image dialog. This allows you to take a screenshot of the current view, including embedded web pages, youtube videos, and markdown documents. Screenshot is only possible in PNG.
- Expose parameter in plugin settings to disable AI functionality [#2325](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2325)
- Enable (disable) double-click text editing option in Excalidraw appearance and behavior (based on request on Discord)
- Added two new PDF export sizes: "Match image", "HD Screen".
- Switch between basic shapes. Quickly change the shape of the selected element by pressing TAB [#9270](https://github.com/excalidraw/excalidraw/pull/9270)
- Updated the Scribble Helper Script. Now controls are at the top so your palm does accidently trigger them. I added a new button to insert special characters. Scribble helper now makes use of the new text element wrapping in Excalidraw.
## Fixed in the plugin
- Scaling multiple embeddables at once did not work. [#2276](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2276)
- When creating multiple back-of-the-note the second card is not created correctly if autosave has not yet happened.
- Drawing reloads while editing the back-of-the-note card in certain cases causes editing to be interrupted.
- Moved Excalidraw filetype indicator ✏️ to after filename where other filetype tags are displayed. You can turn the filetype indicator on/off in plugin settings under Miscellaneous.
## Fixed by Excalidraw.com
- Alt-duplicate now preserves the original element. Previously, using Alt to duplicate would swap the original with the new element, leading to unexpected behavior and several downstream issues. [#9403](https://github.com/excalidraw/excalidraw/pull/9403)
- When dragging the arrow endpoint, update the binding only on the dragged side [#9367](https://github.com/excalidraw/excalidraw/pull/9367)
- Laser pointer trail disappearing on pointerup [#9413](https://github.com/excalidraw/excalidraw/pull/9413) [#9427](https://github.com/excalidraw/excalidraw/pull/9427)
`,
"2.10.1": `
## Fixed by Excalidraw.com
- Eraser performance improvement regression. Erasing locked elements. [#9400](https://github.com/excalidraw/excalidraw/pull/9400)
## New
- Grid Customization Options in plugin settings (appearance and behavior/grid): You can now selectively show or hide vertical and horizontal grid lines independently. This allows you to create alternative grid styles, such as horizontal-only lined grids instead of the traditional checkered pattern.
## Fixed in ExcalidrawAutomate
- ${String.fromCharCode(96)}ea.createSVG${String.fromCharCode(96)} throws error [#2321](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2321)
---
## ❤️ Enjoying the plugin?
Support my work by checking out my new book, now available for pre-order:
[Sketch Your Mind: Nurture a Playful and Creative Brain](https://sketch-your-mind.com) is about visual Personal Knowledge Management. It explores the thinking behind Excalidraw and how it helps you structure and evolve ideas visually. It’s the book I wish I had when I began my own PKM journey.
<div class="ex-coffee-div"><a href="https://sketch-your-mind.com"><img src="https://raw.githubusercontent.com/zsviczian/sketch-your-mind/refs/heads/main/images/cover-mini.jpg" border="0" alt="Pre-order Sketch Your Mind" height="100%"></a></div>
`,
"2.10.0": `
## New from Excalidraw.com
- Lasso select [#9169](https://github.com/excalidraw/excalidraw/pull/9169)
@@ -28,7 +331,7 @@ I develop this plugin as a hobby, spending my free time doing this. If you find
- Keep arrow label horizontal [#9364](https://github.com/excalidraw/excalidraw/pull/9364)
## Fixed in ExcalidrawAutomate
- ea.addText did not honor the width parameter.
- ${String.fromCharCode(96)}ea.addText${String.fromCharCode(96)} did not honor the width parameter.
`,
"2.9.2":`
- More minor fix. Toolbars are not responsive when dynamic styling is turned off. [#2287](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2287)
@@ -157,160 +460,5 @@ function onImageFilePathHook: (data: {
drawingFilePath: string;
}) => string = null;
${String.fromCharCode(96,96,96)}
`,
"2.7.5":`
## Fixed
- PDF export scenario described in [#2184](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2184)
- Elbow arrows do not work within frames [#2187](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2187)
- Embedding images into Excalidraw with areaRef links did not work as expected due to conflicting SVG viewbox and width and height values
- Can't exit full-screen mode in popout windows using the Command Palette toggle action [#2188](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2188)
- If the image mask extended beyond the image in "Mask and Crop" image mode, the mask got misaligned from the image.
- PDF image embedding fixes that impacted some PDF files (not all):
- When cropping the PDF page in the scene (by double-clicking the image to crop), the size and position of the PDF cutout drifted.
- Using PDF++ there was a small offset in the position of the cutout in PDF++ and the image in Excalidraw.
- Updated a number of scripts including Split Ellipse, Select Similar Elements, and Concatenate Lines
## New in ExcalidrawAutomate
${String.fromCharCode(96,96,96)}
/**
* Add, modify, or delete keys in element.customData and preserve existing keys.
* Creates customData={} if it does not exist.
* Takes the element id for an element in ea.elementsDict and the newData to add or modify.
* To delete keys set key value in newData to undefined. So {keyToBeDeleted:undefined} will be deleted.
* @param id
* @param newData
* @returns undefined if element does not exist in elementsDict, returns the modified element otherwise.
*/
public addAppendUpdateCustomData(id:string, newData: Partial<Record<string, unknown>>);
${String.fromCharCode(96,96,96)}
`,
"2.7.4":`
## Fixed
- Regression from 2.7.3 where image fileId got overwritten in some cases
- White flash when opening a dark drawing [#2178](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2178)
`,
"2.7.3":`
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/ISuORbVKyhQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
## Fixed
- Toggling image size anchoring on and off by modifying the image link did not update the image in the view until the user forced saved it or closed and opened the drawing again. This was a side-effect of the less frequent view save introduced in 2.7.1
## New
- **Shade Master Script**: A new script that allows you to modify the color lightness, hue, saturation, and transparency of selected Excalidraw elements, SVG images, and nested Excalidraw drawings. When a single image is selected, you can map colors individually. The original image remains unchanged, and a mapping table is added under ${String.fromCharCode(96)}## Embedded Files${String.fromCharCode(96)} for SVG and nested drawings. This helps maintain links between drawings while allowing different color themes.
- New Command Palette Command: "Duplicate selected image with a different image ID". Creates a copy of the selected image with a new image ID. This allows you to add multiple color mappings to the same image. In the scene, the image will be treated as if a different image, but loaded from the same file in the Vault.
## QoL Improvements
- New setting under ${String.fromCharCode(96)}Embedding Excalidraw into your notes and Exporting${String.fromCharCode(96)} > ${String.fromCharCode(96)}Image Caching and rendering optimization${String.fromCharCode(96)}. You can now set the number of concurrent workers that render your embedded images. Increasing the number will increase the speed but temporarily reduce the responsiveness of your system in case of large drawings.
- Moved pen-related settings under ${String.fromCharCode(96)}Excalidraw appearance and behavior${String.fromCharCode(96)} to their sub-heading called ${String.fromCharCode(96)}Pen${String.fromCharCode(96)}.
- Minor error fixing and performance optimizations when loading and updating embedded images.
- Color maps in ${String.fromCharCode(96)}## Embedded Files${String.fromCharCode(96)} may now include color keys "stroke" and "fill". If set, these will change the fill and stroke attributes of the SVG root element of the relevant file.
## New in ExcalidrawAutomate
${String.fromCharCode(96,96,96)}ts
// Updates the color map of an SVG image element in the view. If a ColorMap is provided, it will be used directly.
// If an SVGColorInfo is provided, it will be converted to a ColorMap.
// The view will be marked as dirty and the image will be reset using the color map.
updateViewSVGImageColorMap(
elements: ExcalidrawImageElement | ExcalidrawImageElement[],
colors: ColorMap | SVGColorInfo | ColorMap[] | SVGColorInfo[]
): Promise<void>;
// Retrieves the color map for an image element.
// The color map contains information about the mapping of colors used in the image.
// If the element already has a color map, it will be returned.
getColorMapForImageElement(el: ExcalidrawElement): ColorMap;
// Retrieves the color map for an SVG image element.
// The color map contains information about the fill and stroke colors used in the SVG.
// If the element already has a color map, it will be merged with the colors extracted from the SVG.
getColorMapForImgElement(el: ExcalidrawElement): Promise<SVGColorInfo>;
// Extracts the fill (background) and stroke colors from an Excalidraw file and returns them as an SVGColorInfo.
getColosFromExcalidrawFile(file:TFile, img: ExcalidrawImageElement): Promise<SVGColorInfo>;
// Extracts the fill and stroke colors from an SVG string and returns them as an SVGColorInfo.
getColorsFromSVGString(svgString: string): SVGColorInfo;
// upgraded the addImage function.
// 1. It now accepts an object as the input parameter, making your scripts more readable
// 2. AddImageOptions now includes colorMap as an optional parameter, this will only have an effect in case of SVGs and nested Excalidraws
// 3. The API function is backwards compatible, but I recommend new implementations to use the object based input
addImage(opts: AddImageOptions}): Promise<string>;
interface AddImageOptions {
topX: number;
topY: number;
imageFile: TFile | string;
scale?: boolean;
anchor?: boolean;
colorMap?: ColorMap;
}
type SVGColorInfo = Map<string, {
mappedTo: string;
fill: boolean;
stroke: boolean;
}>;
interface ColorMap {
[color: string]: string;
};
${String.fromCharCode(96,96,96)}
`,
"2.7.2":`
## Fixed
- The plugin did not load on **iOS 16 and older**. [#2170](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2170)
- Added empty line between ${String.fromCharCode(96)}# Excalidraw Data${String.fromCharCode(96)} and ${String.fromCharCode(96)}## Text Elements${String.fromCharCode(96)}. This will now follow **correct markdown linting**. [#2168](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2168)
- Adding an **embeddable** to view did not **honor the element background and element stroke colors**, even if it was configured in plugin settings. [#2172](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2172)
- **Deconstruct selected elements script** did not copy URLs and URIs for images embedded from outside Obsidian. Please update your script from the script library.
- When **rearranging tabs in Obsidian**, e.g. having two tabs side by side, and moving one of them to another location, if the tab was an Excalidraw tab, it appeared as non-responsive after the move, until the tab was resized.
## Source Code Refactoring
- Updated filenames, file locations, and file name letter-casing across the project
- Extracted onDrop, onDragover, etc. handlers to DropManger in ExcalidrawView
`,
"2.7.1":`
## Fixed
- Deleting excalidraw file from file system while it is open in fullscreen mode in Obsidian causes Obsidian to be stuck in full-screen view [#2161](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2161)
- Chinese fonts are not rendered in LaTeX statements [#2162](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2162)
- Since Electron 32 (newer Obsidian Desktop installers) drag and drop links from Finder or OS File Explorer did not work. [Electron breaking change](https://www.electronjs.org/docs/latest/breaking-changes#removed-filepath). This is now fixed
- Addressed unnecessary image reloads when changing windows in Obsidian
`,
"2.7.0":`
## Fixed
- Various Markdown embeddable "fuzziness":
- Fixed issues with appearance settings and edit mode toggling when single-click editing is enabled.
- Ensured embeddable file editing no longer gets interrupted unexpectedly.
- **Hover Preview**: Disabled hover preview for back-of-the-note cards to reduce distractions.
- **Settings Save**: Fixed an issue where plugin settings unnecessarily saved on every startup.
## New Features
- **Image Cropping Snaps to Objects**: When snapping is enabled in the scene, image cropping now aligns to nearby objects.
- **Session Persistence for Pen Mode**: Excalidraw remembers the last pen mode when switching between drawings within the same session.
## Refactoring
- **Mermaid Diagrams**: Excalidraw now uses its own Mermaid package, breaking future dependencies on Obsidian's Mermaid updates. This ensures stability and includes all fixes and improvements made to Excalidraw Mermaid since February 2024. The plugin file size has increased slightly, but this change significantly improves maintainability while remaining invisible to users.
- **MathJax Optimization**: MathJax (LaTeX equation SVG image generation) now loads only on demand, with the package compressed to minimize the startup and file size impact caused by the inclusion of Mermaid.
- **On-Demand Language Loading**: Non-English language files are now compressed and load only when needed, counterbalancing the increase in file size due to Mermaid and improving load speeds.
- **Codebase Restructuring**: Improved type safety by removing many ${String.fromCharCode(96)}//@ts-ignore${String.fromCharCode(96)} commands and enhancing modularity. Introduced new management classes: **CommandManager**, **EventManager**, **PluginFileManager**, **ObserverManager**, and **PackageManager**. Further restructuring is planned for upcoming releases to improve maintainability and stability.
`,
"2.6.8":`
## New
- **QoL improvements**:
- Obsidian-link search button in Element Link Editor.
- Add Any File now searches file aliases as well.
- Cosmetic changes to file search modals (display path, show file type icon).
- Text Element cursor-color matches the text color.
- New script in script store: [Image Occlusion](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Image%20Occlusion.md) by [@TrillStones](https://github.com/TrillStones) 🙏
## Fixed
- Excalidraw icon on the **ribbon menu kept reappearing** every time you reopen Obsidian [#2115](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2115)
- In pen mode, when **single-finger panning** is enabled, Excalidraw should still **allow actions with the mouse**.
- When **editing a drawing in split mode** (drawing is on one side, markdown view is on the other), editing the markdown note sometimes causes the drawing to re-zoom and jump away from the selected area.
- Hover-Editor compatibility resolved [2041](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2041)
- ${String.fromCharCode(96)}ExcalidrawAutomate.create() ${String.fromCharCode(96)} will now correctly include the markdown text in templates above Excalidraw Data and below YAML front matter. This also fixes the same issue with the **Deconstruct Selected Element script**.
`,
};
@@ -21,6 +21,10 @@ export class PDFExportSettingsComponent {
if (!update) this.update = () => {};
}
isOrientationAndTilingVisible() {
return !(this.settings.pageSize === "HD Screen" || this.settings.pageSize === "MATCH IMAGE");
}
render() {
const pageSizeOptions: Record<string, string> = Object.keys(STANDARD_PAGE_SIZES)
.reduce((acc, key) => ({
@@ -28,6 +32,8 @@ export class PDFExportSettingsComponent {
[key]: key
}), {});
let div: HTMLDivElement;
new Setting(this.contentEl)
.setName(t("EXPORTDIALOG_PAGE_SIZE"))
.addDropdown(dropdown =>
@@ -36,11 +42,15 @@ export class PDFExportSettingsComponent {
.setValue(this.settings.pageSize)
.onChange(value => {
this.settings.pageSize = value as PageSize;
div.style.display = this.isOrientationAndTilingVisible() ? "block" : "none";
this.update();
})
);
new Setting(this.contentEl)
div = this.contentEl.createDiv();
div.style.display = this.isOrientationAndTilingVisible() ? "block" : "none";
new Setting(div)
.setName(t("EXPORTDIALOG_PAGE_ORIENTATION"))
.addDropdown(dropdown =>
dropdown
@@ -55,7 +65,7 @@ export class PDFExportSettingsComponent {
})
);
new Setting(this.contentEl)
new Setting(div)
.setName(t("EXPORTDIALOG_PDF_FIT_TO_PAGE"))
.addDropdown(dropdown =>
dropdown
+280 -46
View File
@@ -13,7 +13,7 @@ import ExcalidrawView from "../../view/ExcalidrawView";
import ExcalidrawPlugin from "../../core/main";
import { escapeRegExp, getLinkParts, sleep } from "../../utils/utils";
import { getLeaf, openLeaf } from "../../utils/obsidianUtils";
import { checkAndCreateFolder, splitFolderAndFilename } from "src/utils/fileUtils";
import { createOrOverwriteFile } from "src/utils/fileUtils";
import { KeyEvent, isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
import { t } from "src/lang/helpers";
import { ExcalidrawElement, getEA } from "src/core";
@@ -22,8 +22,7 @@ import { MAX_IMAGE_SIZE, REG_LINKINDEX_INVALIDCHARS } from "src/constants/consta
import { REGEX_LINK, REGEX_TAGS } from "../ExcalidrawData";
import { ScriptEngine } from "../Scripts";
import { openExternalLink, openTagSearch, parseObsidianLink } from "src/utils/excalidrawViewUtils";
export type ButtonDefinition = { caption: string; tooltip?:string; action: Function };
import { ButtonDefinition } from "src/types/promptTypes";
export class Prompt extends Modal {
private promptEl: HTMLInputElement;
@@ -98,6 +97,9 @@ export class GenericInputPrompt extends Modal {
private selectionUpdateTimer: number = 0;
private customComponents: (container: HTMLElement) => void;
private blockPointerInputOutsideModal: boolean = false;
private controlsOnTop: boolean = false;
private draggable: boolean = false;
private cleanupDragListeners: (() => void) | null = null;
public static Prompt(
view: ExcalidrawView,
@@ -111,6 +113,8 @@ export class GenericInputPrompt extends Modal {
displayEditorButtons?: boolean,
customComponents?: (container: HTMLElement) => void,
blockPointerInputOutsideModal?: boolean,
controlsOnTop?: boolean,
draggable?: boolean,
): Promise<string> {
const newPromptModal = new GenericInputPrompt(
view,
@@ -124,6 +128,8 @@ export class GenericInputPrompt extends Modal {
displayEditorButtons,
customComponents,
blockPointerInputOutsideModal,
controlsOnTop,
draggable,
);
return newPromptModal.waitForClose;
}
@@ -140,6 +146,8 @@ export class GenericInputPrompt extends Modal {
displayEditorButtons?: boolean,
customComponents?: (container: HTMLElement) => void,
blockPointerInputOutsideModal?: boolean,
controlsOnTop?: boolean,
draggable?: boolean,
) {
super(app);
this.view = view;
@@ -151,6 +159,8 @@ export class GenericInputPrompt extends Modal {
this.displayEditorButtons = this.lines > 1 ? (displayEditorButtons ?? false) : false;
this.customComponents = customComponents;
this.blockPointerInputOutsideModal = blockPointerInputOutsideModal ?? false;
this.controlsOnTop = controlsOnTop ?? false;
this.draggable = draggable ?? false;
this.waitForClose = new Promise<string>((resolve, reject) => {
this.resolvePromise = resolve;
@@ -173,13 +183,29 @@ export class GenericInputPrompt extends Modal {
this.titleEl.textContent = this.header;
const mainContentContainer: HTMLDivElement = this.contentEl.createDiv();
this.inputComponent = this.createInputField(
mainContentContainer,
this.placeholder,
this.input
);
this.customComponents?.(mainContentContainer);
this.createButtonBar(mainContentContainer);
// Conditionally order elements based on controlsOnTop flag
if (this.controlsOnTop) {
// Create button bar first
this.customComponents?.(mainContentContainer);
this.createButtonBar(mainContentContainer);
// Then add input field and custom components
this.inputComponent = this.createInputField(
mainContentContainer,
this.placeholder,
this.input
);
} else {
// Original order: input field, custom components, then buttons
this.inputComponent = this.createInputField(
mainContentContainer,
this.placeholder,
this.input
);
this.customComponents?.(mainContentContainer);
this.createButtonBar(mainContentContainer);
}
}
protected createInputField(
@@ -240,12 +266,8 @@ export class GenericInputPrompt extends Modal {
private createButtonBar(mainContentContainer: HTMLDivElement) {
const buttonBarContainer: HTMLDivElement = mainContentContainer.createDiv();
buttonBarContainer.style.display = "flex";
buttonBarContainer.style.justifyContent = "space-between";
buttonBarContainer.style.marginTop = "1rem";
buttonBarContainer.addClass(`excalidraw-prompt-buttonbar-${this.controlsOnTop ? "top" : "bottom"}`);
const editorButtonContainer: HTMLDivElement = buttonBarContainer.createDiv();
const actionButtonContainer: HTMLDivElement = buttonBarContainer.createDiv();
if (this.buttons && this.buttons.length > 0) {
@@ -279,6 +301,7 @@ export class GenericInputPrompt extends Modal {
this.createButton(editorButtonContainer, "⏎", ()=>this.insertStringBtnClickCallback("\n"), t("PROMPT_BUTTON_INSERT_LINE"), "0");
this.createButton(editorButtonContainer, "⌫", this.delBtnClickCallback.bind(this), "Delete");
this.createButton(editorButtonContainer, "⎵", ()=>this.insertStringBtnClickCallback(" "), t("PROMPT_BUTTON_INSERT_SPACE"));
this.createButton(editorButtonContainer, "§", this.specialCharsBtnClickCallback.bind(this), t("PROMPT_BUTTON_SPECIAL_CHARS"));
if(this.view) {
this.createButton(editorButtonContainer, "🔗", this.linkBtnClickCallback.bind(this), t("PROMPT_BUTTON_INSERT_LINK"));
}
@@ -384,16 +407,209 @@ export class GenericInputPrompt extends Modal {
);
}
private specialCharsBtnClickCallback = (evt: MouseEvent) => {
this.view.ownerWindow.clearTimeout(this.selectionUpdateTimer);
// Remove any existing popup
const existingPopup = document.querySelector('.excalidraw-special-chars-popup');
if (existingPopup) {
existingPopup.remove();
return;
}
// 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';
// Position near the button
const rect = (evt.target as HTMLElement).getBoundingClientRect();
popup.style.top = `${rect.bottom + 5}px`;
popup.style.left = `${rect.left}px`;
// Special characters to include
const specialChars = [',', '.', ':', ';', '!', '?', '"', '{', '}', '[', ']', '(', ')'];
// Add character buttons
specialChars.forEach(char => {
const charButton = document.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.addEventListener('click', () => {
this.insertStringBtnClickCallback(char);
popup.remove();
});
popup.appendChild(charButton);
});
// Add click outside listener to close popup
const closePopupListener = (e: MouseEvent) => {
if (!popup.contains(e.target as Node) &&
(evt.target as HTMLElement) !== e.target) {
popup.remove();
document.removeEventListener('click', closePopupListener);
}
};
// Add to document and set up listeners
document.body.appendChild(popup);
setTimeout(() => {
document.addEventListener('click', closePopupListener);
}, 10);
}
onOpen() {
super.onOpen();
this.inputComponent.inputEl.focus();
this.inputComponent.inputEl.select();
if (this.draggable) {
this.makeModalDraggable();
}
}
private makeModalDraggable() {
let isDragging = false;
let startX: number, startY: number, initialX: number, initialY: number;
let activeElement: HTMLElement | null = null;
let cursorPosition: { start: number; end: number } | null = null;
const modalEl = this.modalEl;
const header = modalEl.querySelector('.modal-titlebar') || modalEl.querySelector('.modal-title') || modalEl;
(header as HTMLElement).style.cursor = 'move';
// Track focus changes to store the last focused interactive element
const onFocusIn = (e: FocusEvent) => {
const target = e.target as HTMLElement;
if (target && (target.tagName === 'SELECT' || target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.tagName === 'BUTTON')) {
activeElement = target;
// Store cursor position for input/textarea elements (but not for number inputs)
if (target.tagName === 'TEXTAREA' ||
(target.tagName === 'INPUT' && (target as HTMLInputElement).type !== 'number')) {
const inputEl = target as HTMLInputElement | HTMLTextAreaElement;
cursorPosition = {
start: inputEl.selectionStart || 0,
end: inputEl.selectionEnd || 0
};
} else {
cursorPosition = null;
}
}
};
const onPointerDown = (e: PointerEvent) => {
const target = e.target as HTMLElement;
// Don't allow dragging if clicking on interactive controls
if (target.tagName === 'INPUT' ||
target.tagName === 'TEXTAREA' ||
target.tagName === 'BUTTON' ||
target.tagName === 'SELECT' ||
target.closest('button') ||
target.closest('input') ||
target.closest('textarea') ||
target.closest('select')) {
return;
}
// Allow dragging from header or modal content areas
if (!header.contains(target) && !modalEl.querySelector('.modal-content')?.contains(target)) {
return;
}
isDragging = true;
startX = e.clientX;
startY = e.clientY;
const rect = modalEl.getBoundingClientRect();
initialX = rect.left;
initialY = rect.top;
modalEl.style.position = 'absolute';
modalEl.style.margin = '0';
modalEl.style.left = `${initialX}px`;
modalEl.style.top = `${initialY}px`;
};
const onPointerMove = (e: PointerEvent) => {
if (!isDragging) return;
const dx = e.clientX - startX;
const dy = e.clientY - startY;
modalEl.style.left = `${initialX + dx}px`;
modalEl.style.top = `${initialY + dy}px`;
};
const onPointerUp = () => {
if (!isDragging) return;
isDragging = false;
// Restore focus and cursor position
if (activeElement && activeElement.isConnected) {
// Use setTimeout to ensure the pointer event is fully processed
setTimeout(() => {
activeElement.focus();
// Restore cursor position for input/textarea elements (but not for number inputs)
if (cursorPosition &&
(activeElement.tagName === 'TEXTAREA' ||
(activeElement.tagName === 'INPUT' && (activeElement as HTMLInputElement).type !== 'number'))) {
const inputEl = activeElement as HTMLInputElement | HTMLTextAreaElement;
inputEl.setSelectionRange(cursorPosition.start, cursorPosition.end);
}
}, 0);
}
};
// Initialize activeElement with the main input field
activeElement = this.inputComponent.inputEl;
cursorPosition = {
start: this.inputComponent.inputEl.selectionStart || 0,
end: this.inputComponent.inputEl.selectionEnd || 0
};
// Set up event listeners
modalEl.addEventListener('focusin', onFocusIn);
modalEl.addEventListener('pointerdown', onPointerDown);
document.addEventListener('pointermove', onPointerMove);
document.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);
};
}
onClose() {
super.onClose();
this.resolveInput();
this.removeInputListener();
// Clean up drag listeners to prevent memory leaks
if (this.cleanupDragListeners) {
this.cleanupDragListeners();
this.cleanupDragListeners = null;
}
}
}
@@ -576,10 +792,7 @@ export class NewFileActions extends Modal {
if (!this.path.match(/\.md$/)) {
this.path = `${this.path}.md`;
}
const folderpath = splitFolderAndFilename(this.path).folderpath;
checkAndCreateFolder(folderpath);
const f = await this.app.vault.create(this.path, data);
return f;
return await createOrOverwriteFile(this.app, this.path, data);
};
if(this.sourceElement) {
@@ -641,17 +854,30 @@ export class NewFileActions extends Modal {
}
}
export class ConfirmationPrompt extends Modal {
public waitForClose: Promise<boolean>;
private resolvePromise: (value: boolean) => void;
export class MultiOptionConfirmationPrompt extends Modal {
public waitForClose: Promise<any>;
private resolvePromise: (value: any) => void;
private rejectPromise: (reason?: any) => void;
private didConfirm: boolean = false;
private selectedValue: any = null;
private readonly message: string;
private readonly buttons: Map<string, any>;
private ctaButtonLabel: string = null;
constructor(private plugin: ExcalidrawPlugin, message: string) {
constructor(private plugin: ExcalidrawPlugin, message: string, buttons?: Map<string, any>, ctaButtonLabel?: string) {
super(plugin.app);
this.message = message;
this.waitForClose = new Promise<boolean>((resolve, reject) => {
if (!buttons || buttons.size === 0) {
buttons = new Map<string, any>([
[t("PROMPT_BUTTON_CANCEL"), null],
[t("PROMPT_BUTTON_OK"), true],
]);
if( !ctaButtonLabel) {
ctaButtonLabel = t("PROMPT_BUTTON_OK");
}
}
this.ctaButtonLabel = ctaButtonLabel;
this.buttons = buttons;
this.waitForClose = new Promise<any>((resolve, reject) => {
this.resolvePromise = resolve;
this.rejectPromise = reject;
});
@@ -671,14 +897,35 @@ export class ConfirmationPrompt extends Modal {
const buttonContainer = this.contentEl.createDiv();
buttonContainer.style.display = "flex";
buttonContainer.style.justifyContent = "flex-end";
buttonContainer.style.flexWrap = "wrap";
// Convert Map to Array for easier iteration
const buttonEntries = Array.from(this.buttons.entries());
const cancelButton = this.createButton(buttonContainer, t("PROMPT_BUTTON_CANCEL"), this.cancelClickCallback.bind(this));
cancelButton.buttonEl.style.marginRight = "0.5rem";
// Add buttons in reverse order (last button will be on the right)
let ctaButton: HTMLButtonElement = null;
buttonEntries.reverse().forEach(([buttonText, value], index) => {
const button = this.createButton(buttonContainer, buttonText, () => {
this.selectedValue = value;
this.close();
});
if (buttonText === this.ctaButtonLabel) {
ctaButton = button.buttonEl;
button.setCta();
}
if (index < buttonEntries.length - 1) {
button.buttonEl.style.marginRight = "0.5rem";
}
});
const confirmButton = this.createButton(buttonContainer, t("PROMPT_BUTTON_OK"), this.confirmClickCallback.bind(this));
confirmButton.buttonEl.style.marginRight = "0";
cancelButton.buttonEl.focus();
// Set focus on the first button (visually last)
if(this.ctaButtonLabel) {
if (ctaButton) {
ctaButton.focus();
}
}
}
private createButton(container: HTMLElement, text: string, callback: (evt: MouseEvent) => void) {
@@ -687,16 +934,6 @@ export class ConfirmationPrompt extends Modal {
return button;
}
private cancelClickCallback() {
this.didConfirm = false;
this.close();
};
private confirmClickCallback() {
this.didConfirm = true;
this.close();
};
onOpen() {
super.onOpen();
this.contentEl.querySelector("button")?.focus();
@@ -704,11 +941,7 @@ export class ConfirmationPrompt extends Modal {
onClose() {
super.onClose();
if (!this.didConfirm) {
this.resolvePromise(false);
} else {
this.resolvePromise(true);
}
this.resolvePromise(this.selectedValue);
}
}
@@ -778,6 +1011,7 @@ export async function linkPrompt(
...tagsArray,
];
await sleep(10); //obsidian modal link click immediately refocuses the editor, so we need to wait a bit
if (items.length>1) {
parts = await ScriptEngine.suggester(
app,
+13 -5
View File
@@ -2,6 +2,7 @@ import { App, MarkdownRenderer, Modal } from "obsidian";
import { isVersionNewerThanOther } from "src/utils/utils";
import ExcalidrawPlugin from "../../core/main";
import { FIRST_RUN, RELEASE_NOTES } from "./Messages";
import { t } from "src/lang/helpers";
declare const PLUGIN_VERSION:string;
@@ -16,17 +17,23 @@ export class ReleaseNotes extends Modal {
}
onOpen(): void {
//@ts-ignore
const { containerEl, contentEl, titleEl, headerEl } = this;
//this.contentEl.classList.add("excalidraw-release");
this.containerEl.classList.add("excalidraw-release");
this.titleEl.setText(`Welcome to Excalidraw ${this.version ?? ""}`);
containerEl.classList.add("excalidraw-release");
titleEl.setText(`${t("RN_WELCOME")} ${this.version ?? ""}`);
this.createForm();
if(headerEl) headerEl.style.pointerEvents = "none"; // Disable pointer events on header to allow clicks through
}
async onClose() {
this.contentEl.empty();
await this.plugin.loadSettings();
this.plugin.settings.previousRelease = PLUGIN_VERSION
await this.plugin.saveSettings();
if(this.plugin.settings.previousRelease !== PLUGIN_VERSION) {
this.plugin.settings.previousRelease = PLUGIN_VERSION;
await this.plugin.saveSettings();
}
}
async createForm() {
@@ -39,7 +46,8 @@ export class ReleaseNotes extends Modal {
.slice(0, 10)
.join("\n\n---\n")
: FIRST_RUN;
await MarkdownRenderer.renderMarkdown(
await MarkdownRenderer.render(
this.app,
message,
this.contentEl,
"",
+5 -151
View File
@@ -1,80 +1,27 @@
import { MarkdownRenderer, Modal, Notice, request } from "obsidian";
import ExcalidrawPlugin from "../../core/main";
import { errorlog, escapeRegExp } from "../../utils/utils";
import { errorlog } from "../../utils/utils";
import { log } from "src/utils/debugHelper";
import { ContentSearcher } from "../components/ContentSearcher";
const URL =
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/index-new.md";
export class ScriptInstallPrompt extends Modal {
private contentDiv: HTMLDivElement;
constructor(private plugin: ExcalidrawPlugin) {
super(plugin.app);
// this.titleEl.setText(t("INSTAL_MODAL_TITLE"));
}
async onOpen(): Promise<void> {
const searchBarWrapper = document.createElement("div");
searchBarWrapper.classList.add('search-bar-wrapper');
const searchBar = document.createElement("input");
searchBar.type = "text";
searchBar.id = "search-bar";
searchBar.placeholder = "Search...";
//searchBar.style.width = "calc(100% - 120px)"; // space for the buttons and hit count
const nextButton = document.createElement("button");
nextButton.textContent = "→";
nextButton.onclick = () => this.navigateSearchResults("next");
const prevButton = document.createElement("button");
prevButton.textContent = "←";
prevButton.onclick = () => this.navigateSearchResults("previous");
const hitCount = document.createElement("span");
hitCount.id = "hit-count";
hitCount.classList.add('hit-count');
searchBarWrapper.appendChild(prevButton);
searchBarWrapper.appendChild(nextButton);
searchBarWrapper.appendChild(searchBar);
searchBarWrapper.appendChild(hitCount);
this.contentEl.prepend(searchBarWrapper);
searchBar.addEventListener("input", (e) => {
this.clearHighlights();
const searchTerm = (e.target as HTMLInputElement).value;
if (searchTerm && searchTerm.length > 0) {
this.highlightSearchTerm(searchTerm);
const totalHits = this.contentDiv.querySelectorAll("mark.search-highlight").length;
hitCount.textContent = totalHits > 0 ? `1/${totalHits}` : "";
setTimeout(()=>this.navigateSearchResults("next"));
} else {
hitCount.textContent = "";
}
});
searchBar.addEventListener("keydown", (e) => {
// If Ctrl/Cmd + F is pressed, focus on search bar
if ((e.ctrlKey || e.metaKey) && e.key === "f") {
e.preventDefault();
searchBar.focus();
}
// If Enter is pressed, navigate to next result
else if (e.key === "Enter") {
e.preventDefault();
this.navigateSearchResults(e.shiftKey ? "previous" : "next");
}
});
this.contentEl.classList.add("excalidraw-scriptengine-install");
this.contentDiv = document.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 });
@@ -111,99 +58,6 @@ export class ScriptInstallPrompt extends Modal {
}
}
highlightSearchTerm(searchTerm: string): void {
// Create a walker to traverse text nodes
const walker = document.createTreeWalker(
this.contentDiv,
NodeFilter.SHOW_TEXT,
{
acceptNode: (node: Text) => {
return node.nodeValue!.toLowerCase().includes(searchTerm.toLowerCase()) ?
NodeFilter.FILTER_ACCEPT :
NodeFilter.FILTER_REJECT;
}
}
);
const nodesToReplace: Text[] = [];
while (walker.nextNode()) {
nodesToReplace.push(walker.currentNode as Text);
}
nodesToReplace.forEach(node => {
const nodeContent = node.nodeValue!;
const newNode = document.createDocumentFragment();
let lastIndex = 0;
let match;
const regex = new RegExp(escapeRegExp(searchTerm), 'gi');
// Iterate over all matches in the text node
while ((match = regex.exec(nodeContent)) !== null) {
const before = document.createTextNode(nodeContent.slice(lastIndex, match.index));
const highlighted = document.createElement('mark');
highlighted.className = 'search-highlight';
highlighted.textContent = match[0];
highlighted.classList.add('search-result');
newNode.appendChild(before);
newNode.appendChild(highlighted);
lastIndex = regex.lastIndex;
}
newNode.appendChild(document.createTextNode(nodeContent.slice(lastIndex)));
node.replaceWith(newNode);
});
}
clearHighlights(): void {
this.contentDiv.querySelectorAll("mark.search-highlight").forEach((el) => {
el.outerHTML = el.innerHTML;
});
}
navigateSearchResults(direction: "next" | "previous"): void {
const highlights: HTMLElement[] = Array.from(
this.contentDiv.querySelectorAll("mark.search-highlight")
);
if (highlights.length === 0) return;
const currentActiveIndex = highlights.findIndex((highlight) =>
highlight.classList.contains("active-highlight")
);
if (currentActiveIndex !== -1) {
highlights[currentActiveIndex].classList.remove("active-highlight");
highlights[currentActiveIndex].style.border = "none";
}
let nextActiveIndex = 0;
if (direction === "next") {
nextActiveIndex =
currentActiveIndex === highlights.length - 1
? 0
: currentActiveIndex + 1;
} else if (direction === "previous") {
nextActiveIndex =
currentActiveIndex === 0
? highlights.length - 1
: currentActiveIndex - 1;
}
const nextActiveHighlight = highlights[nextActiveIndex];
nextActiveHighlight.classList.add("active-highlight");
nextActiveHighlight.scrollIntoView({
behavior: "smooth",
block: "nearest",
});
// Update the hit count
const hitCount = document.getElementById("hit-count");
hitCount.textContent = `${nextActiveIndex + 1}/${highlights.length}`;
}
onClose(): void {
this.contentEl.empty();
}
+19 -5
View File
@@ -3,10 +3,13 @@ import { t } from "../../lang/helpers";
import ExcalidrawView from "src/view/ExcalidrawView";
import { getEA } from "src/core";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { MD_EX_SECTIONS } from "src/constants/constants";
import { CARD_HEIGHT, CARD_WIDTH, MD_EX_SECTIONS } from "src/constants/constants";
import { addBackOfTheNoteCard } from "src/utils/excalidrawViewUtils";
export class SelectCard extends FuzzySuggestModal<string> {
private center: boolean = false;
private x: number = 0;
private y: number = 0;
constructor(
public app: App,
@@ -31,7 +34,7 @@ export class SelectCard extends FuzzySuggestModal<string> {
this.close();
return;
}
addBackOfTheNoteCard(this.view, item);
addBackOfTheNoteCard(this.view, item, true, undefined, undefined, this.center, {x: this.x, y: this.y});
this.close();
}
}
@@ -48,18 +51,29 @@ export class SelectCard extends FuzzySuggestModal<string> {
onChooseItem(item: string): void {
const ea = getEA(this.view) as ExcalidrawAutomate;
if(this.center) {
const centerPos = ea.getViewCenterPosition();
if(centerPos) {
this.x = centerPos.x - (CARD_WIDTH / 2);
this.y = centerPos.y - (CARD_HEIGHT / 2);
}
}
const id = ea.addEmbeddable(
0,0,400,500,
this.x,this.y,CARD_WIDTH,CARD_HEIGHT,
`[[${this.view.file.path}#${item}]]`
);
(async () => {
await ea.addElementsToView(true, false, true);
await ea.addElementsToView(!this.center, false, true);
ea.selectElementsInView([id]);
ea.destroy();
})();
}
public start(): void {
public start(center: boolean = false): void {
this.x = this.view.currentPosition.x;
this.y = this.view.currentPosition.y;
this.center = !!center;
this.emptyStateText = t("EMPTY_SECTION_MESSAGE");
this.setPlaceholder(t("SELECT_SECTION_OR_TYPE_NEW"));
this.open();
+37 -26
View File
@@ -31,6 +31,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "The ExcalidrawPlugin object",
after: "",
},
{
field: "FloatingModal",
code: null,
desc: "A modified version of the Obsidian.Modal class that allows the modal to be dragged around the screen and that does not dim the background.",
after: "",
},
{
field: "elementsDict",
code: null,
@@ -575,27 +581,6 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "Adds elements from elementsDict to the current view\nrepositionToCursor: default is false\nsave: default is true\nnewElementsOnTop: default is false, i.e. the new elements get to the bottom of the stack\nnewElementsOnTop controls whether elements created with ExcalidrawAutomate are added at the bottom of the stack or the top of the stack of elements already in the view\nNote that elements copied to the view with copyViewElementsToEAforEditing retain their position in the stack of elements in the view even if modified using EA",
after: "",
},
{
field: "onDropHook",
code: 'onDropHook(data: {ea: ExcalidrawAutomate, event: React.DragEvent<HTMLDivElement>, draggable: any, type: "file" | "text" | "unknown", payload: {files: TFile[], text: string,}, excalidrawFile: TFile, view: ExcalidrawView, pointerPosition: { x: number, y: number},}): boolean;',
desc: "If set Excalidraw will call this function onDrop events.\nA return of true will stop the default onDrop processing in Excalidraw.\n\ndraggable is the Obsidian draggable object\nfiles is the array of dropped files\nexcalidrawFile is the file receiving the drop event\nview is the excalidraw view receiving the drop.\npointerPosition is the pointer position on canvas at the time of drop.",
after: "",
},
{
field: "onImageFilePathHook",
code: `onImageFilePathHook: (data: {currentImageName: string; drawingFilePath: string;}): string;`,
desc: "If set, this callback is triggered when an image is being saved in Excalidraw.\n"
+ "You can use this callback to customize the naming and path of pasted images to avoid\n"
+ 'default names like "Pasted image 123147170.png" being saved in the attachments folder,\n'
+ "and instead use more meaningful names based on the Excalidraw file or other criteria,\n"
+ "plus save the image in a different folder.\n\n"
+ "If the function returns null or undefined, the normal Excalidraw operation will continue\n"
+ "with the excalidraw generated name and default path.\n"
+ "If a filepath is returned, that will be used. Include the full Vault filepath and filename\n"
+ "with the file extension.\n"
+ "The currentImageName is the name of the image generated by excalidraw or provided during paste.",
after: "",
},
{
field: "mostRecentMarkdownSVG",
code: "mostRecentMarkdownSVG: SVGSVGElement;",
@@ -626,6 +611,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
"}",
after: "",
},
{
field: "getElementsInArea",
code: "getElementsInArea(elements: ExcalidrawElement[], area: {x: number, y: number, width: number, height: number}): ExcalidrawElement[];",
desc: "Filter the elements and returns only those within the specific area.",
after: "",
},
{
field: "getBoundingBox",
code: "getBoundingBox(elements: ExcalidrawElement[]): {topX: number, topY: number, width: number, height: number,};",
@@ -828,11 +819,11 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "getActiveEmbeddableViewOrEditor",
code: "getActiveEmbeddableViewOrEditor(view?: ExcalidrawView);",
code: "getActiveEmbeddableViewOrEditor (view?:ExcalidrawView): {view:any}|{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>" +
"If the embedded file is a markdown document the function will return<br>" +
"<code>{file:TFile, editor:Editor}</code> otherwise it will return {view:any}. You can check view type with view.getViewType();",
"If the embedded file is an eligible Obsidian canvas node document the function will return<br>" +
"<code>{file:TFile, editor:Editor}</code> of {node: ObsidianCanvasNode}, otherwise it will return {view:any}. You can check view type with view.getViewType();",
after: "",
},
{
@@ -841,6 +832,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "@returns the last recorded pointer position on the Excalidraw canvas",
after: "",
},
{
field: "getViewCenterPosition",
code: "getViewCenterPosition(): {x: number, y: number};",
desc: "@returns the center position of the current view in Excalidraw coordinates",
after: "",
},
{
field: "getleaf",
code: "getLeaf(origo: WorkspaceLeaf, targetPane?: PaneTarget): WorkspaceLeaf;",
@@ -917,6 +914,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "Sets Excalidraw in the targetView to view-mode",
after: "",
},
{
field: "splitFolderAndFilename",
code: "splitFolderAndFilename(filepath: string): { folderpath: string; filename: string; basename: string; extension: string; }",
desc: "Splits a file path into its components.",
after: "",
},
{
field: "viewUpdateScene",
code: "viewUpdateScene(scene:{elements?:ExcalidrawElement[],appState?: AppState,files?: BinaryFileData,captureUpdate?: 'IMMEDIATELY' | 'NEVER' | 'EVENTUALLY'},restore:boolean=false):void",
@@ -947,15 +950,16 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
export const EXCALIDRAW_SCRIPTENGINE_INFO: SuggesterInfo[] = [
{
field: "inputPrompt",
code: "inputPrompt: (header: string, placeholder?: string, value?: string, buttons?: {caption:string, tooltip?:string, action:Function}[], lines?: number, displayEditorButtons?: boolean, customComponents?: (container: HTMLElement) => void, blockPointerInputOutsideModal?: boolean);",
code: "inputPrompt: (opts: {header: string, placeholder?: string, value?: string, buttons?: {caption:string, tooltip?:string, action:Function}[], lines?: number, displayEditorButtons?: boolean, customComponents?: (container: HTMLElement) => void, blockPointerInputOutsideModal?: boolean, controlsOnTop?: boolean});",
desc:
"Opens a prompt that asks for an input.\nReturns a string with the input.\nYou need to await the result of inputPrompt.\n" +
"Editor buttons are text editing buttons like delete, enter, allcaps - these are only displayed if lines is greater than 1 \n" +
"Custom components are components that you can add to the prompt. These will be displayed between the text input area and the buttons.\n" +
"blockPointerInputOutsideModal will block pointer input outside the modal. This is useful if you want to prevent the user accidently closing the modal or interacting with the excalidraw canvas while the prompt is open.\n" +
"controlsOnTop when set to true will move all the buttons to the top of the modal, leaving the text area at the bottom. This feature was developed for Scribble Helper script to avoid your palm pressing buttons while scribbling.\n"+
"buttons.action(input: string) => string\nThe button action function will receive the actual input string. If action returns null, input will be unchanged. If action returns a string, input will receive that value when the promise is resolved. " +
"example:\n<code>let fileType = '';\nconst filename = await utils.inputPrompt (\n 'Filename',\n '',\n '',\n, [\n {\n caption: 'Markdown',\n action: ()=>{fileType='md';return;}\n },\n {\n caption: 'Excalidraw',\n action: ()=>{fileType='ex';return;}\n }\n ]\n);</code>",
after: "",
after: `({\n header: "",\n placeholder: undefined, //string\n value: undefined, //string\n buttons: [{ //optional, may leave undefined\n caption: "", //string\n tooltip: undefined, //string\n action: (input)=>{} //Function\n }],\n lines: undefined, //number\n displayEditorButtons: undefined, //boolean\n customComponents: undefined, //(container: HTMLElement) => void\n blockPointerInputOutsideModal: undefined, //boolean\n controlsOnTop: undefined, //boolean\n draggable: undefined, //boolean\n});`,
},
{
field: "suggester",
@@ -1075,6 +1079,13 @@ export const FRONTMATTER_KEYS_INFO: SuggesterInfo[] = [
desc: "If this key is present the file will be opened as a markdown file in the editor",
after: ": true",
},
{
field: "embed-md",
code: null,
desc: "If this key is present, when embedding the ![[image]] into a markdown document, it will be embedded as markdown, not as an image.\n" +
"If however you embed ![[image#^as-image]], i.e. you reference the 'as-image' block, then the image will be embedded as an image.",
after: ": true",
},
{
field: "autoexport",
code: null,
@@ -1,4 +1,4 @@
import { ButtonComponent, DropdownComponent, TFile, ToggleComponent } from "obsidian";
import { ButtonComponent, DropdownComponent, TFile } from "obsidian";
import ExcalidrawView from "../../view/ExcalidrawView";
import ExcalidrawPlugin from "../../core/main";
import { Modal, Setting, TextComponent } from "obsidian";
@@ -10,6 +10,7 @@ import { InsertPDFModal } from "./InsertPDFModal";
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { cleanSectionHeading } from "src/utils/obsidianUtils";
import { t } from "src/lang/helpers";
export class UniversalInsertFileModal extends Modal {
private center: { x: number, y: number } = { x: 0, y: 0 };
@@ -61,7 +62,7 @@ export class UniversalInsertFileModal extends Modal {
onOpen(): void {
this.containerEl.classList.add("excalidraw-release");
this.titleEl.setText(`Insert File From Vault`);
this.titleEl.setText(t("UIFM_TITLE"));
this.createForm();
}
@@ -155,15 +156,15 @@ export class UniversalInsertFileModal extends Modal {
});
sectionPickerSetting = new Setting(ce)
.setName("Select section heading")
.setName(t("UIFM_SECTION_HEAD"))
.addDropdown(dropdown => {
sectionPicker = dropdown;
sectionPicker.selectEl.style.width = "100%";
})
sizeToggleSetting = new Setting(ce)
.setName("Anchor to 100% of original size")
.setDesc("This is a pro feature, use it only if you understand how it works. If enabled even if you change the size of the imported image in Excalidraw, the next time you open the drawing this image will pop back to 100% size. This is useful when embedding an atomic Excalidraw idea into another note and preserving relative sizing of text and icons.")
.setName(t("UIFM_ANCHOR"))
.setDesc(t("UIFM_ANCHOR_DESC"))
.addToggle(toggle => {
toggle.setValue(anchorTo100)
.onChange((value) => {
@@ -174,7 +175,7 @@ export class UniversalInsertFileModal extends Modal {
new Setting(ce)
.addButton(button => {
button
.setButtonText("as Embeddable")
.setButtonText(t("UIFM_BTN_EMBEDDABLE"))
.onClick(async () => {
const path = this.app.metadataCache.fileToLinktext(
file,
@@ -198,7 +199,7 @@ export class UniversalInsertFileModal extends Modal {
})
.addButton(button => {
button
.setButtonText("as Pdf")
.setButtonText(t("UIFM_BTN_PDF"))
.onClick(() => {
const insertPDFModal = new InsertPDFModal(this.plugin, this.view);
insertPDFModal.open(file);
@@ -208,7 +209,7 @@ export class UniversalInsertFileModal extends Modal {
})
.addButton(button => {
button
.setButtonText("as Image")
.setButtonText(t("UIFM_BTN_IMAGE"))
.onClick(async () => {
const ea:ExcalidrawAutomate = getEA(this.view);
const isMarkdown = file && file.extension === "md" && !ea.isExcalidrawFile(file);
+102
View File
@@ -0,0 +1,102 @@
import { Modal, Setting } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
import { t } from "src/lang/helpers";
declare const PLUGIN_VERSION: string;
/**
* A modal dialog that informs the user about a version mismatch between the version recorded by Obsidian and the actual version of the plugin executable.
* Explain that this can be the result of a partial sync, such as an Obsidian Sync Standard plan, which does not syncronize files larger than 5MB, and the plugin executable is larger.
* Explain that changing the plugin version information in Obsidian can lead to unexpected behavior in plugins suchs as the Plugin Update Tracker plugin or the BRAT plugin.
* The user has a toggle button to disable this check in the future. There is additional information that this can be reenabled in plugin settings.
* The user can click update obsidian version info to match the plugin version, and open Obsidian settings to redownload the plugin.
* The user can click ignore to dismiss the dialog.
*/
export class VersionMismatchPrompt extends Modal {
private resolvePromise: (value: any) => void;
public promise: Promise<any>;
private resolved: boolean;
private isDirty: boolean = false;
public constructor(
private plugin: ExcalidrawPlugin,
) {
super(plugin.app);
}
async start(): Promise<any> {
this.promise = new Promise((resolve) => {
this.resolvePromise = resolve;
});
await this.plugin.loadSettings();
this.buildUI();
this.open();
return this.promise;
}
private buildUI() {
const { contentEl } = this;
contentEl.empty();
const recorded = this.plugin.manifest.version;
const actual = PLUGIN_VERSION;
contentEl.createEl("h2", { text: t("VERSION_MISMATCH_HEADING") });
const p1 = contentEl.createEl("p");
p1.innerHTML = t("VERSION_MISMATCH_NOTICE")
.replace("{VAL_RECORDED}", recorded)
.replace("{VAL_ACTUAL}", actual);
const p2 = contentEl.createEl("p");
p2.innerHTML = t("VERSION_MISMATCH_CAUSE");
const p3 = contentEl.createEl("p");
p3.innerHTML = t("VERSION_MISMATCH_OPTIONS");
const p4 = contentEl.createEl("p");
p4.innerHTML = t("VERSION_MISMATCH_NOTE");
new Setting(contentEl)
.setName(t("VERSION_MISMATCH_DISABLE_NAME"))
.setDesc(t("VERSION_MISMATCH_DISABLE_DESC"))
.addToggle(tg =>
tg.setValue(!this.plugin.settings.compareManifestToPluginVersion ? true : false)
.onChange(async (value) => {
this.plugin.settings.compareManifestToPluginVersion = !value; // invert because label is Disable ...
this.isDirty = true;
}),
);
// Buttons row
const buttonBar = contentEl.createDiv({ cls: "ex-version-mismatch-buttons" });
const redownloadBtn = buttonBar.createEl("button", { text: t("VERSION_MISMATCH_REDOWNLOAD") });
redownloadBtn.addEventListener("click", () => {
this.resolved = true; // triggers opening settings in caller
this.close();
});
const ignoreBtn = buttonBar.createEl("button", { text: t("VERSION_MISMATCH_IGNORE") });
ignoreBtn.addEventListener("click", () => {
this.resolved = false;
this.close();
});
buttonBar.style.display = "flex";
buttonBar.style.gap = "0.5rem";
buttonBar.style.marginTop = "1rem";
redownloadBtn.style.backgroundColor = "var(--interactive-accent)";
redownloadBtn.style.color = "var(--text-on-accent)";
}
async onClose() {
super.onClose();
if(this.isDirty) {
await this.plugin.saveSettings();
}
if (!this.resolved) {
this.resolvePromise && this.resolvePromise(false);
} else {
this.resolvePromise && this.resolvePromise(true);
}
}
}
+37 -10
View File
@@ -1,7 +1,7 @@
//https://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
//https://img.youtube.com/vi/uZz5MgzWXiM/maxresdefault.jpg
import { ExcalidrawElement, FileId } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { ExcalidrawElement, FileId } from "@zsviczian/excalidraw/types/element/src/types";
import { BinaryFileData, DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import { App, MarkdownRenderer, Notice, TFile } from "obsidian";
import {
@@ -201,6 +201,10 @@ export class EmbeddedFile {
}
}
get hasSeparateDarkAndLightVersion(): boolean {
return this.isSVGwithBitmap || (this.file && this.file.extension.toLowerCase() === "pdf");
}
public resetImage(hostPath: string, imgPath: string) {
this.imgInverted = this.img = "";
this.mtime = 0;
@@ -278,11 +282,12 @@ export class EmbeddedFile {
if (this.fileChanged()) {
this.imgInverted = this.img = "";
}
this.isSVGwithBitmap = isSVGwithBitmap;
this.mtime = this.isHyperLink || this.isLocalLink ? 0 : this.file.stat.mtime;
this.pdfPageViewProps = pdfPageViewProps;
this.size = size;
this.mimeType = mimeType;
switch (isDark && isSVGwithBitmap) {
switch (isDark && this.hasSeparateDarkAndLightVersion) {
case true:
this.imgInverted = imgBase64;
break;
@@ -290,7 +295,6 @@ export class EmbeddedFile {
this.img = imgBase64;
break; //bitmaps and SVGs without an embedded bitmap do not need a negative image
}
this.isSVGwithBitmap = isSVGwithBitmap;
}
public isLoaded(isDark: boolean): boolean {
@@ -309,7 +313,7 @@ export class EmbeddedFile {
return false;
}
}
if (this.isSVGwithBitmap && isDark) {
if (this.hasSeparateDarkAndLightVersion && isDark) {
return this.imgInverted !== "";
}
return this.img !== "";
@@ -319,7 +323,7 @@ export class EmbeddedFile {
if (!this.file && !this.isHyperLink && !this.isLocalLink) {
return "";
}
if (isDark && this.isSVGwithBitmap) {
if (this.hasSeparateDarkAndLightVersion && isDark) {
return this.imgInverted;
}
return this.img; //images that are not SVGwithBitmap, only the light string is stored, since inverted and non-inverted are ===
@@ -608,7 +612,7 @@ export class EmbeddedFilesLoader {
return {
mimeType,
fileId: await generateIdFromFile(
isHyperLink || isPDF || isExcalidrawFile ? (new TextEncoder()).encode(dataURL as string) : ab,
isHyperLink || isPDF || isExcalidrawFile ? (new TextEncoder()).encode(dataURL as string).buffer : ab,
inFile instanceof EmbeddedFile ? inFile.filenameparts?.linkpartReference : undefined
),
dataURL,
@@ -675,7 +679,7 @@ export class EmbeddedFilesLoader {
};
files[batch].push(fileData);
}
} else if (embeddedFile.isSVGwithBitmap && (depth !== 0 || isThemeChange)) {
} else if (embeddedFile.hasSeparateDarkAndLightVersion && (depth !== 0 || isThemeChange)) {
//this will reload the image in light/dark mode when switching themes
const fileData: FileData = {
mimeType: embeddedFile.mimeType,
@@ -927,6 +931,26 @@ export class EmbeddedFilesLoader {
const canvas = await renderPage(pageNum);
if(canvas) {
// NEW: invert colors for dark theme (keep alpha unchanged)
if (this.isDark) {
const ctx = canvas.getContext('2d');
if (ctx) {
try {
const img = ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = img.data;
for (let i = 0; i < data.length; i += 4) {
data[i] = 255 - data[i]; // R
data[i + 1] = 255 - data[i+1]; // G
data[i + 2] = 255 - data[i+2]; // B
// alpha channel (data[i+3]) remains unchanged
}
ctx.putImageData(img, 0, 0);
} catch (e) {
// If reading pixel data fails, silently fallback to non-inverted
}
}
}
const result: [DataURL,Size, PDFPageViewProps] = [`data:image/png;base64,${await new Promise((resolve, reject) => {
canvas.toBlob(async (blob) => {
const dataURL = await blobToBase64(blob);
@@ -1215,11 +1239,14 @@ export const generateIdFromFile = async (file: ArrayBuffer, key?: string): Promi
}
// Hash the combined data (file and key, if provided)
const hashBuffer = await window.crypto.subtle.digest("SHA-1", dataToHash);
// 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 hashBuffer = await window.crypto.subtle.digest("SHA-1", buffer);
id =
// Convert buffer to byte array
Array.from(new Uint8Array(hashBuffer))
// Convert to hex string
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("") as FileId;
} catch (error) {
+215 -43
View File
@@ -12,7 +12,7 @@ import {
RoundnessType,
ExcalidrawFrameElement,
ExcalidrawTextContainer,
} from "@zsviczian/excalidraw/types/excalidraw/element/types";
} from "@zsviczian/excalidraw/types/element/src/types";
import { ColorMap, MimeType } from "./EmbeddedFileLoader";
import { Editor, Notice, OpenViewState, RequestUrlResponse, TFile, TFolder, WorkspaceLeaf } from "obsidian";
import * as obsidian_module from "obsidian";
@@ -34,7 +34,7 @@ import {
mermaidToExcalidraw,
refreshTextDimensions,
} from "src/constants/constants";
import { blobToBase64, checkAndCreateFolder, getDrawingFilename, getExcalidrawEmbeddedFilesFiletree, getListOfTemplateFiles, getNewUniqueFilepath } from "src/utils/fileUtils";
import { blobToBase64, checkAndCreateFolder, getDrawingFilename, getExcalidrawEmbeddedFilesFiletree, getListOfTemplateFiles, getNewUniqueFilepath, splitFolderAndFilename } from "src/utils/fileUtils";
import {
//debug,
getImageSize,
@@ -43,7 +43,6 @@ import {
arrayToMap,
addAppendUpdateCustomData,
getSVG,
getWithBackground,
} from "src/utils/utils";
import { getAttachmentsFolderAndFilePath, getExcalidrawViews, getLeaf, getNewOrAdjacentLeaf, isObsidianThemeDark, mergeMarkdownFiles, openLeaf } from "src/utils/obsidianUtils";
import { AppState, BinaryFileData, DataURL, ExcalidrawImperativeAPI, SceneData } from "@zsviczian/excalidraw/types/excalidraw/types";
@@ -70,7 +69,7 @@ import {ConversionResult, svgToExcalidraw} from "src/shared/svgToExcalidraw/pars
import { ROUNDNESS } from "src/constants/constants";
import { ClipboardData } from "@zsviczian/excalidraw/types/excalidraw/clipboard";
import { emulateKeysForLinkClick, PaneTarget } from "src/utils/modifierkeyHelper";
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import PolyBool from "polybooljs";
import { EmbeddableMDCustomProps } from "./Dialogs/EmbeddableSettings";
import {
@@ -82,12 +81,16 @@ import { EXCALIDRAW_AUTOMATE_INFO, EXCALIDRAW_SCRIPTENGINE_INFO } from "./Dialog
import { addBackOfTheNoteCard } from "../utils/excalidrawViewUtils";
import { log } from "../utils/debugHelper";
import { ExcalidrawLib } from "../types/excalidrawLib";
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/types";
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/src/types";
import { AddImageOptions, ImageInfo, SVGColorInfo } from "src/types/excalidrawAutomateTypes";
import { _measureText, cloneElement, createPNG, createSVG, errorMessage, filterColorMap, getEmbeddedFileForImageElment, getFontFamily, getLineBox, getTemplate, isColorStringTransparent, isSVGColorInfo, mergeColorMapIntoSVGColorInfo, normalizeLinePoints, repositionElementsToCursor, svgColorInfoToColorMap, updateOrAddSVGColorInfo, verifyMinimumPluginVersion } from "src/utils/excalidrawAutomateUtils";
import { exportToPDF, getMarginValue, getPageDimensions, PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFPageProperties } from "src/utils/exportUtils";
import { FrameRenderingOptions } from "src/types/utilTypes";
import { CaptureUpdateAction } from "src/constants/constants";
import { AutoexportConfig } from "src/types/excalidrawViewTypes";
import { FloatingModal } from "./Dialogs/FloatingModal";
import { patchMobileView } from "src/utils/customEmbeddableUtils";
import { ObsidianCanvasNode } from "src/view/managers/CanvasNodeFactory";
extendPlugins([
HarmonyPlugin,
@@ -170,6 +173,15 @@ export class ExcalidrawAutomate {
return obsidian_module;
};
/**
* This is a modified version of the Obsidian.Modal class
* that allows the modal to be dragged around the screen
* and that does not dim the background.
*/
get FloatingModal() {
return FloatingModal;
}
/**
* Retrieves the laser pointer settings from the plugin.
* @returns {Object} The laser pointer settings.
@@ -318,6 +330,19 @@ export class ExcalidrawAutomate {
return await checkAndCreateFolder(folderpath);
}
/**
* @param filepath - The file path to split into folder and filename.
* @returns object containing folderpath, filename, basename, and extension.
*/
public splitFolderAndFilename(filepath: string) : {
folderpath: string;
filename: string;
basename: string;
extension: string;
} {
return splitFolderAndFilename(filepath);
}
/**
* Generates a unique filepath by appending a number if file already exists.
* @param {string} filename - Base filename.
@@ -452,7 +477,7 @@ export class ExcalidrawAutomate {
* @param {ExcalidrawView} [view] - The view to check.
* @returns {{view:any}|{file:TFile, editor:Editor}|null} The active embeddable view or editor.
*/
public getActiveEmbeddableViewOrEditor (view?:ExcalidrawView): {view:any}|{file:TFile, editor:Editor}|null {
public getActiveEmbeddableViewOrEditor (view?:ExcalidrawView): {view:any}|{file:TFile, editor:Editor}|{node: ObsidianCanvasNode}|null {
if (!this.targetView && !view) {
return null;
}
@@ -462,6 +487,9 @@ export class ExcalidrawAutomate {
if(leafOrNode.node && leafOrNode.node.isEditing) {
return {file: leafOrNode.node.file, editor: leafOrNode.node.child.editor};
}
if(leafOrNode.node) {
return {node: leafOrNode.node};
}
if(leafOrNode.leaf && leafOrNode.leaf.view) {
return {view: leafOrNode.leaf.view};
}
@@ -532,6 +560,25 @@ export class ExcalidrawAutomate {
return this.targetView.currentPosition;
}
/**
* Returns the center position of the current view in Excalidraw coordinates.
* @returns {{x:number, y:number}} The center position of the view.
*/
public getViewCenterPosition(): {x:number, y:number} {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "getExcalidrawAPI()");
return null;
}
const st = (this.getExcalidrawAPI() as ExcalidrawImperativeAPI).getAppState();
if (!st) return null;
const zoom = st.zoom?.value ?? 1;
const x = -st.scrollX + (st.width / 2) / zoom;
const y = -st.scrollY + (st.height / 2) / zoom;
return { x, y };
}
/**
* Returns the Excalidraw API for the current view or the view provided.
* @param {ExcalidrawView} [view] - The view to get the API for.
@@ -809,59 +856,60 @@ 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 scene = {
type: "excalidraw",
version: 2,
source: GITHUB_RELEASES+PLUGIN_VERSION,
elements,
appState: {
theme: template?.appState?.theme ?? this.canvas.theme,
...templateAppstate,
theme: templateAppstate.theme ?? this.canvas.theme,
viewBackgroundColor:
template?.appState?.viewBackgroundColor ??
templateAppstate.viewBackgroundColor ??
this.canvas.viewBackgroundColor,
currentItemStrokeColor:
template?.appState?.currentItemStrokeColor ??
templateAppstate.currentItemStrokeColor ??
this.style.strokeColor,
currentItemBackgroundColor:
template?.appState?.currentItemBackgroundColor ??
templateAppstate.currentItemBackgroundColor ??
this.style.backgroundColor,
currentItemFillStyle:
template?.appState?.currentItemFillStyle ?? this.style.fillStyle,
templateAppstate.currentItemFillStyle ?? this.style.fillStyle,
currentItemStrokeWidth:
template?.appState?.currentItemStrokeWidth ??
templateAppstate.currentItemStrokeWidth ??
this.style.strokeWidth,
currentItemStrokeStyle:
template?.appState?.currentItemStrokeStyle ??
templateAppstate.currentItemStrokeStyle ??
this.style.strokeStyle,
currentItemRoughness:
template?.appState?.currentItemRoughness ?? this.style.roughness,
templateAppstate.currentItemRoughness ?? this.style.roughness,
currentItemOpacity:
template?.appState?.currentItemOpacity ?? this.style.opacity,
templateAppstate.currentItemOpacity ?? this.style.opacity,
currentItemFontFamily:
template?.appState?.currentItemFontFamily ?? this.style.fontFamily,
templateAppstate.currentItemFontFamily ?? this.style.fontFamily,
currentItemFontSize:
template?.appState?.currentItemFontSize ?? this.style.fontSize,
templateAppstate.currentItemFontSize ?? this.style.fontSize,
currentItemTextAlign:
template?.appState?.currentItemTextAlign ?? this.style.textAlign,
templateAppstate.currentItemTextAlign ?? this.style.textAlign,
currentItemStartArrowhead:
template?.appState?.currentItemStartArrowhead ??
templateAppstate.currentItemStartArrowhead ??
this.style.startArrowHead,
currentItemEndArrowhead:
template?.appState?.currentItemEndArrowhead ??
templateAppstate.currentItemEndArrowhead ??
this.style.endArrowHead,
currentItemRoundness: //type StrokeRoundness = "round" | "sharp"
template?.appState?.currentItemLinearStrokeSharpness ?? //legacy compatibility
template?.appState?.currentItemStrokeSharpness ?? //legacy compatibility
template?.appState?.currentItemRoundness ??
currentItemRoundness:
templateAppstate.currentItemLinearStrokeSharpness ??
templateAppstate.currentItemStrokeSharpness ??
templateAppstate.currentItemRoundness ??
this.style.roundness ? "round":"sharp",
gridSize: template?.appState?.gridSize ?? this.canvas.gridSize,
colorPalette: template?.appState?.colorPalette ?? this.colorPalette,
...template?.appState?.frameRendering
? {frameRendering: template.appState.frameRendering}
: {},
...template?.appState?.objectsSnapModeEnabled
? {objectsSnapModeEnabled: template.appState.objectsSnapModeEnabled}
: {},
gridSize: templateAppstate.gridSize ?? this.canvas.gridSize,
colorPalette: templateAppstate.colorPalette ?? this.colorPalette,
},
files: template?.files ?? {},
};
@@ -1018,6 +1066,7 @@ export class ExcalidrawAutomate {
* @param {boolean} [options.selectedOnly=false] - Whether to include only the selected elements in the SVG.
* @param {boolean} [options.skipInliningFonts=false] - Whether to skip inlining fonts in the SVG.
* @param {boolean} [options.embedScene=false] - Whether to embed the scene in the SVG.
* @param {ExcalidrawElement[]} [options.elementsOverride] - Optional override for the elements to include in the SVG. Primary to support the Printable Layout Wizard script
* @returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.
*/
async createViewSVG({
@@ -1028,6 +1077,7 @@ export class ExcalidrawAutomate {
selectedOnly = false,
skipInliningFonts = false,
embedScene = false,
elementsOverride,
} : {
withBackground?: boolean,
theme?: "light" | "dark",
@@ -1036,6 +1086,7 @@ export class ExcalidrawAutomate {
selectedOnly?: boolean,
skipInliningFonts?: boolean,
embedScene?: boolean,
elementsOverride?: ExcalidrawElement[]
}): Promise<SVGSVGElement> {
if(!this.targetView || !this.targetView.file || !this.targetView._loaded) {
console.log("No view loaded");
@@ -1044,6 +1095,9 @@ export class ExcalidrawAutomate {
const view = this.targetView;
const scene = this.targetView.getScene(selectedOnly);
if(elementsOverride) {
scene.elements = elementsOverride;
}
const exportSettings: ExportSettings = {
withBackground: view.getViewExportWithBackground(withBackground),
withTheme: true,
@@ -1096,13 +1150,14 @@ export class ExcalidrawAutomate {
? "light"
: undefined;
}
if (theme && !exportSettings) {
if (!exportSettings) {
exportSettings = {
withBackground: this.plugin.settings.exportWithBackground,
withTheme: true,
isMask: false,
skipInliningFonts: !embedFont,
};
}
}
if (!loader) {
loader = new EmbeddedFilesLoader(
this.plugin,
@@ -1267,6 +1322,7 @@ export class ExcalidrawAutomate {
boundElements: [] as any,
link,
locked: false,
frameId: null as string,
...scale ? {scale} : {},
};
}
@@ -1654,7 +1710,9 @@ export class ExcalidrawAutomate {
arrayToMap(this.getElements()),
originalText,
);
if(dimensions) {
if(dimensions && !formatting?.width) {
textElement.width = dimensions.width;
textElement.height = dimensions.height;
textElement.x = dimensions.x;
@@ -1714,6 +1772,7 @@ export class ExcalidrawAutomate {
id = id ?? nanoid();
const startPoint = points[0] as GlobalPoint;
const endPoint = points[points.length - 1] as GlobalPoint;
const elementsMap = arrayToMap(this.getElements());
this.elementsDict[id] = {
points: normalizeLinePoints(points),
lastCommittedPoint: null,
@@ -1722,6 +1781,7 @@ export class ExcalidrawAutomate {
focus: formatting?.startObjectId
? determineFocusDistance(
this.getElement(formatting?.startObjectId) as ExcalidrawBindableElement,
elementsMap,
endPoint,
startPoint,
)
@@ -1733,6 +1793,7 @@ export class ExcalidrawAutomate {
focus: formatting?.endObjectId
? determineFocusDistance(
this.getElement(formatting?.endObjectId) as ExcalidrawBindableElement,
elementsMap,
startPoint,
endPoint,
)
@@ -1898,10 +1959,12 @@ export class ExcalidrawAutomate {
image.size.width,
image.size.height,
);
this.elementsDict[id].fileId = fileId;
this.elementsDict[id].scale = [1, 1];
const newEl = this.elementsDict[id] as Mutable<ExcalidrawImageElement>;
newEl.fileId = fileId;
newEl.scale = [1, 1];
newEl.crop = null;
if(!scale && anchor) {
this.elementsDict[id].customData = {isAnchored: true}
newEl.customData = {isAnchored: true}
};
return id;
};
@@ -2163,7 +2226,7 @@ export class ExcalidrawAutomate {
};
targetView: ExcalidrawView = null; //the view currently edited
/**
* Sets the target view for EA. All the view operations and the access to Excalidraw API will be performend on this view.
* Sets the target view for EA. All the view operations and the access to Excalidraw API will be performed on this view.
* If view is null or undefined, the function will first try setView("active"), then setView("first").
* @param {ExcalidrawView | "first" | "active"} [view] - The view to set as target.
* @returns {ExcalidrawView} The target view.
@@ -2605,7 +2668,7 @@ export class ExcalidrawAutomate {
viewUpdateScene (
scene: {
elements?: ExcalidrawElement[],
appState?: AppState,
appState?: AppState | {},
files?: BinaryFileData,
commitToHistory?: boolean,
storeAction?: "capture" | "none" | "update",
@@ -2698,8 +2761,11 @@ export class ExcalidrawAutomate {
errorMessage("targetView not set", "addElementsToView()");
return false;
}
const elements = this.getElements();
return await this.targetView.addElements({
const elements = this.getElements();
if(elements.some(el=>el.type === "embeddable")) {
patchMobileView(this.targetView);
}
const result = await this.targetView.addElements({
newElements: elements,
repositionToCursor,
save,
@@ -2707,6 +2773,7 @@ export class ExcalidrawAutomate {
newElementsOnTop,
shouldRestoreElements,
});
return result;
};
/**
@@ -2844,7 +2911,86 @@ export class ExcalidrawAutomate {
onImageFilePathHook: (data: {
currentImageName: string; // Excalidraw generated name of the image, or the name received from the file system.
drawingFilePath: string; // The full filepath of the Excalidraw file where the image is being used.
}) => string = null;
}) => string | null = null;
/**
* If set, this callback is triggered when the Excalidraw image is being exported to
* .svg, .png, or .excalidraw.
* You can use this callback to customize the naming and path of the images. This allows
* you to place images into an assets folder.
*
* If the function returns null or undefined, the normal Excalidraw operation will continue
* with the currentImageName and in the same folder as the Excalidraw file
* If a filepath is returned, that will be used. Include the full Vault filepath and filename
* with the file extension.
* If the new folder path does not exist, excalidraw will create it - you don't need to worry about that.
* ⚠️⚠️If an image already exists on the path, that will be overwritten. When returning
* your own image path, you must take care of unique filenames (if that is a requirement) ⚠️⚠️
* The current image name is the name generated by Excalidraw:
* - my-drawing.png
* - my-drawing.svg
* - my-drawing.excalidraw
* - my-drawing.dark.svg
* - my-drawing.light.svg
* - my-drawing.dark.png
* - my-drawing.light.png
*
* @param data - An object containing the following properties:
* @property {string} exportFilepath - Default export filepath for the image.
* @property {string} exportExtension - The file extension of the export (e.g., .dark.svg, .png, .excalidraw).
* @property {string} excalidrawFile - TFile: The Excalidraw file being exported.
* @property {string} oldExcalidrawPath - If action === "move" The old path of the Excalidraw file, else undefined
* @property {string} action - The action being performed: "export", "move", or "delete". move and delete reference the change to the Excalidraw file.
*
* @returns {string} - The new filepath for the image including full vault path and extension.
*
* Example usage:
* ```
* onImageFilePathHook: (data) => {
* const { currentImageName, drawingFilePath, frontmatter } = data;
* // Generate a new filepath based on the drawing file name and other criteria
* const ext = currentImageName.split('.').pop();
* if(frontmatter && frontmatter["my-custom-field"]) {
* }
* return `${drawingFileName} - ${currentImageName || 'image'}.${ext}`;
* }
* ```
*/
onImageExportPathHook: (data: {
exportFilepath: string; // Default export filepath for the image.
exportExtension: string; // The file extension of the export (e.g., .dark.svg, .png, .excalidraw).
excalidrawFile: TFile; // The Excalidraw file being exported.
oldExcalidrawPath? : string; // The old path of the Excalidraw file, if it was moved/renamed.
action: "export" | "move" | "delete";
}) => string | null = null;
/**
* Excalidraw supports auto-export of Excalidraw files to .png, .svg, and .excalidraw formats.
*
* Auto-export of Excalidraw files can be controlled at multiple levels.
* 1) In plugin settings where you can set up default auto-export applicable to all your Excalidraw files.
* 2) However, if you do not want to auto-export every file, you can also control auto-export
* at the file level using the 'excalidraw-autoexport' frontmatter property.
* 3) This hook gives you an additional layer of control over the auto-export process.
*
* This hook is triggered when an Excalidraw file is being saved.
*
* interface AutoexportConfig {
* png: boolean; // Whether to auto-export to PNG
* svg: boolean; // Whether to auto-export to SVG
* excalidraw: boolean; // Whether to auto-export to Excalidraw format
* theme: "light" | "dark" | "both"; // The theme to use for the export
* }
*
* @param {Object} data - The data for the hook.
* @param {AutoexportConfig} data.autoexportConfig - The current autoexport configuration.
* @param {TFile} data.excalidrawFile - The Excalidraw file being auto-exported.
* @returns {AutoexportConfig | null} - Return a modified AutoexportConfig to override the export behavior, or null to use the default.
*/
onTriggerAutoexportHook: (data: {
autoexportConfig: AutoexportConfig;
excalidrawFile: TFile; // The Excalidraw file being auto-exported
}) => AutoexportConfig | null = null;
/**
* if set, this callback is triggered, when an Excalidraw file is opened
@@ -2923,6 +3069,32 @@ export class ExcalidrawAutomate {
return { withBackground, withTheme, isMask };
};
/**
* Gets the elements within a specific area.
* @param elements - The elements to check.
* @param param1 - The area to check against.
* @returns The elements within the area.
*/
getElementsInArea(
elements: NonDeletedExcalidrawElement[],
element: NonDeletedExcalidrawElement,
):ExcalidrawElement[] {
const {x, y, width, height, id} = element;
return elements
.filter(el => {
if((el.type==="frame" && el.frameRole==="marker")) return false;
if(el.id === id) return true;
const {topX, topY, width:w, height:h} = this.getBoundingBox([el]);
const elLeft = topX;
const elTop = topY;
const elRight = topX + w;
const elBottom = topY + h;
// overlap exists if rectangles intersect
return !(elLeft >= x + width || elRight <= x || elTop >= y + height || elBottom <= y);
});
};
/**
* Gets the bounding box of the specified elements.
* The bounding box is the box encapsulating all of the elements completely.
+48 -55
View File
@@ -44,19 +44,18 @@ import {
ExcalidrawImageElement,
ExcalidrawTextElement,
FileId,
} from "@zsviczian/excalidraw/types/excalidraw/element/types";
} from "@zsviczian/excalidraw/types/element/src/types";
import { BinaryFiles, DataURL, SceneData } from "@zsviczian/excalidraw/types/excalidraw/types";
import { EmbeddedFile, MimeType } from "./EmbeddedFileLoader";
import { ConfirmationPrompt } from "./Dialogs/Prompt";
import { MultiOptionConfirmationPrompt } from "./Dialogs/Prompt";
import { getMermaidImageElements, getMermaidText, shouldRenderMermaid } from "../utils/mermaidUtils";
import { DEBUGGING, debug } from "../utils/debugHelper";
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { updateElementIdsInScene } from "../utils/excalidrawSceneUtils";
import { checkAndCreateFolder, getNewUniqueFilepath, splitFolderAndFilename } from "../utils/fileUtils";
import { importFileToVault } from "../utils/fileUtils";
import { t } from "../lang/helpers";
import { displayFontMessage } from "../utils/excalidrawViewUtils";
import { getPDFRect } from "../utils/PDFUtils";
import { create } from "domain";
type SceneDataWithFiles = SceneData & { files: BinaryFiles };
@@ -305,7 +304,11 @@ const RE_TEXTELEMENTS_FALLBACK_2 = /(.*)##? Text Elements(?:\n|$)/m;
const RE_DRAWING = /^(%%\n+)?##? Drawing\n/m;
export const getExcalidrawMarkdownHeaderSection = (data:string, keys?:[string,string][]):string => {
export function getExcalidrawMarkdownHeader (data: string): {
header: string,
shouldFixTrailingHashtag: boolean,
processingOk: boolean,
} {
//The base case scenario is at the top, continued with fallbacks in order of likelihood and file structure
//change history for sake of backward compatibility
@@ -440,10 +443,18 @@ export const getExcalidrawMarkdownHeaderSection = (data:string, keys?:[string,st
}
}
if (trimLocation === -1) {
return data.endsWith("\n") ? data : (data + "\n");
return {header:data.endsWith("\n") ? data : (data + "\n"), shouldFixTrailingHashtag, processingOk: false};
}
let header = updateFrontmatterInString(data.substring(0, trimLocation),keys);
return {header: data.substring(0, trimLocation), shouldFixTrailingHashtag, processingOk: true};
}
export const getExcalidrawMarkdownHeaderSection = (data:string, keys?:[string,string][]):string => {
const {header, shouldFixTrailingHashtag, processingOk} = getExcalidrawMarkdownHeader(data);
if(!processingOk) return header;
const updatedHeader = updateFrontmatterInString(header, keys);
//this should be removed at a later time. Left it here to remediate 1.4.9 mistake
/*const REG_IMG = /(^---[\w\W]*?---\n)(!\[\[.*?]]\n(%%\n)?)/m; //(%%\n)? because of 1.4.8-beta... to be backward compatible with anyone who installed that version
if (header.match(REG_IMG)) {
@@ -451,8 +462,8 @@ export const getExcalidrawMarkdownHeaderSection = (data:string, keys?:[string,st
}*/
//end of remove
return shouldFixTrailingHashtag
? header + "\n#\n"
: header.endsWith("\n") ? header : (header + "\n");
? updatedHeader + "\n#\n"
: updatedHeader.endsWith("\n") ? header : (header + "\n");
}
@@ -570,6 +581,10 @@ export class ExcalidrawData {
el.containerId = null;
}
if (el.type === "text" && !el.originalText) {
el.originalText = el.rawText ?? el.text ?? "";
}
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/494
if (el.x === null) {
el.x = 0;
@@ -749,6 +764,27 @@ export class ExcalidrawData {
this.deletedElements = this.scene.elements.filter((el:ExcalidrawElement)=>el.isDeleted);
this.scene.elements = this.scene.elements.filter((el:ExcalidrawElement)=>!el.isDeleted);
//once off migration of legacy scenes
if(this.scene?.elements?.some((el:any)=>el.type==="iframe" && !el.customData)) {
const prompt = new MultiOptionConfirmationPrompt(
this.plugin,
"This file contains embedded frames " +
"which will be migrated to a newer version for compatibility with " +
"<a href='https://excalidraw.com'>excalidraw.com</a>.<br>🔄 If you're using Obsidian on " +
"multiple devices, you may proceed now, but please, before opening this " +
"file on your other devices, update Excalidraw on those as well.<br>🔍 More info is available "+
"<a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.9.9'>here</a>.<br>🌐 " +
"<a href='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'>" +
"Translate</a>.",
);
prompt.contentEl.focus();
const confirmation = await prompt.waitForClose
if(!confirmation) {
throw new Error(ERROR_IFRAME_CONVERSION_CANCELED);
}
}
this.initializeNonInitializedFields();
const timer = window.setTimeout(()=>{
const notice = new Notice(t("FONT_LOAD_SLOW"),15000);
@@ -791,27 +827,6 @@ export class ExcalidrawData {
delete this.scene.appState.gridColor.MajorGridFrequency;
}
//once off migration of legacy scenes
if(this.scene?.elements?.some((el:any)=>el.type==="iframe" && !el.customData)) {
const prompt = new ConfirmationPrompt(
this.plugin,
"This file contains embedded frames " +
"which will be migrated to a newer version for compatibility with " +
"<a href='https://excalidraw.com'>excalidraw.com</a>.<br>🔄 If you're using Obsidian on " +
"multiple devices, you may proceed now, but please, before opening this " +
"file on your other devices, update Excalidraw on those as well.<br>🔍 More info is available "+
"<a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.9.9'>here</a>.<br>🌐 " +
"<a href='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'>" +
"Translate</a>.",
);
prompt.contentEl.focus();
const confirmation = await prompt.waitForClose
if(!confirmation) {
throw new Error(ERROR_IFRAME_CONVERSION_CANCELED);
}
}
this.initializeNonInitializedFields();
data = data.substring(0, sceneJSONandPOS.pos);
//The Markdown # Text Elements take priority over the JSON text elements. Assuming the scenario in which the
@@ -1547,37 +1562,15 @@ export class ExcalidrawData {
}
}
let hookFilepath:string;
const ea = this.view?.getHookServer();
if(ea?.onImageFilePathHook) {
hookFilepath = ea.onImageFilePathHook({
currentImageName: fname,
drawingFilePath: this.view?.file?.path,
})
}
let filepath:string;
if(hookFilepath) {
const {folderpath, filename} = splitFolderAndFilename(hookFilepath);
await checkAndCreateFolder(folderpath);
filepath = getNewUniqueFilepath(this.app.vault,filename,folderpath);
} else {
const x = await getAttachmentsFolderAndFilePath(this.app, this.file.path, fname);
filepath = getNewUniqueFilepath(this.app.vault,fname,x.folder);
}
const arrayBuffer = await getBinaryFileFromDataURL(dataURL);
if(!arrayBuffer) return null;
const file = await this.app.vault.createBinary(
filepath,
arrayBuffer,
);
const file = await importFileToVault(this.app, fname, arrayBuffer, this.file, this.view);
const embeddedFile = new EmbeddedFile(
this.plugin,
this.file.path,
filepath,
file.path,
);
embeddedFile.setImage({
+19
View File
@@ -382,6 +382,25 @@ class ImageCache {
store.put(data, filepath);
}
public async removeBAKFromCache(filepath: string): Promise<void> {
if (!this.isReady()) {
return; // Database not initialized yet
}
const transaction = this.db.transaction(this.backupStoreName, "readwrite");
const store = transaction.objectStore(this.backupStoreName);
return new Promise<void>((resolve, reject) => {
const request = store.delete(filepath);
request.onsuccess = () => {
resolve();
};
request.onerror = () => {
reject(new Error(`Failed to remove backup file with key: ${filepath}`));
};
});
}
public async clearImageCache(): Promise<void> {
if (!this.isReady()) {
return; // Database not initialized yet
+1 -1
View File
@@ -2,7 +2,7 @@
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import ExcalidrawView from "../view/ExcalidrawView";
import { FileData, MimeType } from "./EmbeddedFileLoader";
import { FileId } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
import ExcalidrawPlugin from "src/core/main";
declare const loadMathjaxToSVG: Function;
+2 -2
View File
@@ -3,7 +3,7 @@ import {Notice, requestUrl} from "obsidian"
import ExcalidrawPlugin from "../../core/main"
import ExcalidrawView, { ExportSettings } from "../../view/ExcalidrawView"
import FrontmatterEditor from "src/shared/Frontmatter";
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import { EmbeddedFilesLoader } from "../EmbeddedFileLoader";
import { blobToBase64 } from "src/utils/fileUtils";
import { getEA } from "src/core";
@@ -114,7 +114,7 @@ export default class Taskbone {
if(addToFrontmatter) {
fe.setKey("taskbone-ocr",text);
view.data = fe.data;
view.save(false);
view.save(false, true, true);
}
window.navigator.clipboard.writeText(text);
new Notice(`I placed the recognized text onto the system clipboard${addToFrontmatter?" and to document properties":""}.`);
+29 -6
View File
@@ -8,13 +8,14 @@ import {
import { PLUGIN_ID } from "../constants/constants";
import ExcalidrawView from "../view/ExcalidrawView";
import ExcalidrawPlugin from "../core/main";
import { ButtonDefinition, GenericInputPrompt, GenericSuggester } from "./Dialogs/Prompt";
import { GenericInputPrompt, GenericSuggester } from "./Dialogs/Prompt";
import { getIMGFilename } from "../utils/fileUtils";
import { splitFolderAndFilename } from "../utils/fileUtils";
import { getEA } from "src/core";
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
import { WeakArray } from "./WeakArray";
import { getExcalidrawViews } from "../utils/obsidianUtils";
import { ButtonDefinition, InputPromptOptions } from "src/types/promptTypes";
export type ScriptIconMap = {
[key: string]: { name: string; group: string; svgString: string };
@@ -190,7 +191,7 @@ export class ScriptEngine {
...this.scriptIconMap,
};
const splitname = splitFolderAndFilename(name)
this.scriptIconMap[scriptPath] = { name:splitname.filename, group: splitname.folderpath === "/" ? "" : splitname.folderpath, svgString };
this.scriptIconMap[scriptPath] = { name:splitname.filename, group: splitname.folderpath, svgString };
this.updateToolPannels();
}
@@ -271,7 +272,7 @@ export class ScriptEngine {
//try {
result = await new AsyncFunction("ea", "utils", script)(ea, {
inputPrompt: (
header: string,
header: string | InputPromptOptions,
placeholder?: string,
value?: string,
buttons?: ButtonDefinition[],
@@ -279,8 +280,23 @@ export class ScriptEngine {
displayEditorButtons?: boolean,
customComponents?: (container: HTMLElement) => void,
blockPointerInputOutsideModal?: boolean,
) =>
ScriptEngine.inputPrompt(
controlsOnTop?: boolean,
draggable?: boolean,
) => {
if (typeof header === "object") {
const options = header as InputPromptOptions;
header = options.header;
placeholder = options.placeholder;
value = options.value;
buttons = options.buttons;
lines = options.lines;
displayEditorButtons = options.displayEditorButtons;
customComponents = options.customComponents;
blockPointerInputOutsideModal = options.blockPointerInputOutsideModal;
controlsOnTop = options.controlsOnTop;
draggable = options.draggable;
}
return ScriptEngine.inputPrompt(
view,
this.plugin,
this.app,
@@ -292,7 +308,10 @@ export class ScriptEngine {
displayEditorButtons,
customComponents,
blockPointerInputOutsideModal,
),
controlsOnTop,
draggable
);
},
suggester: (
displayItems: string[],
items: any[],
@@ -336,6 +355,8 @@ export class ScriptEngine {
displayEditorButtons?: boolean,
customComponents?: (container: HTMLElement) => void,
blockPointerInputOutsideModal?: boolean,
controlsOnTop?: boolean,
draggable: boolean = false,
) {
try {
return await GenericInputPrompt.Prompt(
@@ -350,6 +371,8 @@ export class ScriptEngine {
displayEditorButtons,
customComponents,
blockPointerInputOutsideModal,
controlsOnTop,
draggable
);
} catch {
return undefined;
+306
View File
@@ -0,0 +1,306 @@
import { t } from "src/lang/helpers";
import { escapeRegExp } from "../../utils/utils";
// @ts-ignore
import { getIcon, htmlToMarkdown, Notice } from "obsidian";
export class ContentSearcher {
private contentDiv: HTMLElement;
private searchBar: HTMLInputElement;
private prevButton: HTMLButtonElement;
private nextButton: HTMLButtonElement;
private exportMarkdown: HTMLButtonElement;
private showHideButton: HTMLButtonElement;
private customElemenentContainer: HTMLDivElement;
private inputContainer: HTMLDivElement;
private customElement: HTMLElement;
private hitCount: HTMLSpanElement;
private searchBarWrapper: HTMLDivElement;
constructor(contentDiv: HTMLElement, customElement?: HTMLElement) {
this.contentDiv = contentDiv;
this.customElement = customElement;
this.createSearchElements();
this.setupEventListeners();
contentDiv.prepend(this.getSearchBarWrapper());
}
/**
* Creates search UI elements styled like Obsidian's native search
*/
private createSearchElements(): void {
this.searchBarWrapper = createDiv("excalidraw-search document-search-container");
const documentSearch = createDiv("document-search");
this.inputContainer = createDiv("search-input-container document-search-input");
this.searchBar = createEl("input",{type: "text", placeholder: "Find..."});
this.hitCount = createDiv("document-search-count");
this.inputContainer.appendChild(this.searchBar);
this.inputContainer.appendChild(this.hitCount);
const buttonContainer = createDiv("document-search-buttons");
this.prevButton = createEl("button", {
cls: ["clickable-icon", "document-search-button"],
attr: {
"aria-label": t("SEARCH_PREVIOUS"),
"data-tooltip-position": "top",
},
type: "button",
});
this.prevButton.innerHTML = getIcon("arrow-up").outerHTML;
this.nextButton = createEl("button", {
cls: ["clickable-icon", "document-search-button"],
attr: {
"aria-label": t("SEARCH_NEXT"),
"data-tooltip-position": "top",
},
type: "button",
});
this.nextButton.innerHTML = getIcon("arrow-down").outerHTML;
this.exportMarkdown = createEl("button", {
cls: ["clickable-icon", "document-search-button"],
attr: {
"aria-label": t("SEARCH_COPY_TO_CLIPBOARD_ARIA"),
"data-tooltip-position": "top",
},
type: "button",
});
this.exportMarkdown.innerHTML = getIcon("clipboard-copy").outerHTML;
this.showHideButton = createEl("button", {
cls: ["clickable-icon", "document-search-button", "search-visible"],
attr: {
"aria-label": t("SEARCH_SHOWHIDE_ARIA"),
"data-tooltip-position": "top",
},
type: "button",
});
this.showHideButton.innerHTML = getIcon("minimize-2").outerHTML;
buttonContainer.appendChild(this.prevButton);
buttonContainer.appendChild(this.nextButton);
buttonContainer.appendChild(this.exportMarkdown);
buttonContainer.appendChild(this.showHideButton);
documentSearch.appendChild(this.inputContainer);
documentSearch.appendChild(buttonContainer);
this.searchBarWrapper.appendChild(documentSearch);
this.customElemenentContainer = createDiv();
if(this.customElement) {
this.customElemenentContainer.appendChild(this.customElement);
this.searchBarWrapper.appendChild(this.customElemenentContainer)
}
}
/**
* Attach event listeners to search elements
*/
private setupEventListeners(): void {
this.nextButton.onclick = () => this.navigateSearchResults("next");
this.prevButton.onclick = () => this.navigateSearchResults("previous");
this.exportMarkdown.onclick = () => {
// Get the full HTML content first
const fullHtml = this.contentDiv.outerHTML;
// Find the index of the first <hr> element
const startIndex = fullHtml.indexOf('<hr');
// Extract HTML from the first <hr> element onwards
const html = startIndex > -1 ? fullHtml.substring(startIndex) : fullHtml;
function replaceHeading(html:string,level:number):string {
const re = new RegExp(`<summary class="excalidraw-setting-h${level}">([^<]+)<\/summary>`,"g");
return html.replaceAll(re,`<summary class="excalidraw-setting-h${level}"><h${level}>$1</h${level}></summary>`);
}
let x = replaceHeading(html,1);
x = replaceHeading(x,2);
x = replaceHeading(x,3);
x = replaceHeading(x,4);
x = x.replaceAll(/<div class="setting-item-name">([^<]+)<\/div>/g,"<h5>$1</h5>");
const md = htmlToMarkdown(x);
window.navigator.clipboard.writeText(md);
new Notice(t("SEARCH_COPIED_TO_CLIPBOARD"));
};
this.showHideButton.onclick = () => {
const setOpacity = (value:string|null) => {
this.inputContainer.style.opacity = value;
this.prevButton.style.opacity = value;
this.nextButton.style.opacity = value;
this.exportMarkdown.style.opacity = value;
this.customElemenentContainer.style.opacity = value;
}
if(this.showHideButton.hasClass("search-visible")) {
this.showHideButton.removeClass("search-visible");
this.showHideButton.addClass("search-hidden");
this.searchBarWrapper.style.backgroundColor = "transparent";
setOpacity("0");
this.showHideButton.innerHTML = getIcon("maximize-2").outerHTML;
} else {
this.showHideButton.removeClass("search-hidden");
this.showHideButton.addClass("search-visible");
this.searchBarWrapper.style.backgroundColor = null;
setOpacity(null);
this.showHideButton.innerHTML = getIcon("minimize-2").outerHTML;
}
}
this.searchBar.addEventListener("input", (e) => {
this.clearHighlights();
const searchTerm = (e.target as HTMLInputElement).value;
if (searchTerm && searchTerm.length > 0) {
this.highlightSearchTerm(searchTerm);
const totalHits = this.contentDiv.querySelectorAll("mark.search-highlight").length;
this.hitCount.textContent = totalHits > 0 ? `1 / ${totalHits}` : "";
setTimeout(() => this.navigateSearchResults("next"));
} else {
this.hitCount.textContent = "";
}
});
this.searchBar.addEventListener("keydown", (e) => {
// If Ctrl/Cmd + F is pressed, focus on search bar
if ((e.ctrlKey || e.metaKey) && e.key === "f") {
e.preventDefault();
this.searchBar.focus();
}
// If Enter is pressed, navigate to next result
else if (e.key === "Enter") {
e.preventDefault();
this.navigateSearchResults(e.shiftKey ? "previous" : "next");
}
});
}
/**
* Get the search bar wrapper element to add to the DOM
*/
public getSearchBarWrapper(): HTMLElement {
return this.searchBarWrapper;
}
/**
* Highlight all instances of the search term in the content
*/
public highlightSearchTerm(searchTerm: string): void {
// Create a walker to traverse text nodes
const walker = document.createTreeWalker(
this.contentDiv,
NodeFilter.SHOW_TEXT,
{
acceptNode: (node: Text) => {
return node.nodeValue!.toLowerCase().includes(searchTerm.toLowerCase()) ?
NodeFilter.FILTER_ACCEPT :
NodeFilter.FILTER_REJECT;
}
}
);
const nodesToReplace: Text[] = [];
while (walker.nextNode()) {
nodesToReplace.push(walker.currentNode as Text);
}
nodesToReplace.forEach(node => {
const nodeContent = node.nodeValue!;
const newNode = document.createDocumentFragment();
let lastIndex = 0;
let match;
const regex = new RegExp(escapeRegExp(searchTerm), 'gi');
// Iterate over all matches in the text node
while ((match = regex.exec(nodeContent)) !== null) {
const before = document.createTextNode(nodeContent.slice(lastIndex, match.index));
const highlighted = document.createElement('mark');
highlighted.className = 'search-highlight';
highlighted.textContent = match[0];
highlighted.classList.add('search-result');
newNode.appendChild(before);
newNode.appendChild(highlighted);
lastIndex = regex.lastIndex;
}
newNode.appendChild(document.createTextNode(nodeContent.slice(lastIndex)));
node.replaceWith(newNode);
});
}
/**
* Remove all search highlights
*/
public clearHighlights(): void {
this.contentDiv.querySelectorAll("mark.search-highlight").forEach((el) => {
el.outerHTML = el.innerHTML;
});
}
/**
* Navigate to next or previous search result
*/
public navigateSearchResults(direction: "next" | "previous"): void {
const highlights: HTMLElement[] = Array.from(
this.contentDiv.querySelectorAll("mark.search-highlight")
);
if (highlights.length === 0) return;
const currentActiveIndex = highlights.findIndex((highlight) =>
highlight.classList.contains("active-highlight")
);
if (currentActiveIndex !== -1) {
highlights[currentActiveIndex].classList.remove("active-highlight");
highlights[currentActiveIndex].style.border = "none";
}
let nextActiveIndex = 0;
if (direction === "next") {
nextActiveIndex =
currentActiveIndex === highlights.length - 1
? 0
: currentActiveIndex + 1;
} else if (direction === "previous") {
nextActiveIndex =
currentActiveIndex === 0
? highlights.length - 1
: currentActiveIndex - 1;
}
const nextActiveHighlight = highlights[nextActiveIndex];
nextActiveHighlight.classList.add("active-highlight");
// Expand all parent details elements
this.expandParentDetails(nextActiveHighlight);
// Use setTimeout to ensure DOM has time to update after expanding details
setTimeout(() => {
nextActiveHighlight.scrollIntoView({
behavior: "smooth",
block: "nearest",
});
}, 100);
// Update the hit count
this.hitCount.textContent = `${nextActiveIndex + 1} / ${highlights.length}`;
}
/**
* Expand all parent <details> elements to make the element visible
*/
private expandParentDetails(element: HTMLElement): void {
let parent = element.parentElement;
while (parent) {
if (parent.tagName === "DETAILS") {
parent.setAttribute("open", "");
}
parent = parent.parentElement;
}
}
}
@@ -1,6 +1,6 @@
import { randomId, randomInteger } from "../utils";
import { ExcalidrawLinearElement, FillStyle, GroupId, RoundnessType, StrokeStyle } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { ExcalidrawLinearElement, FillStyle, GroupId, RoundnessType, StrokeStyle } from "@zsviczian/excalidraw/types/element/src/types";
export type Point = [number, number];
+1 -1
View File
@@ -1,4 +1,4 @@
import { ExcalidrawElement, ExcalidrawLinearElement, ExcalidrawTextElement, FillStyle, GroupId, RoundnessType, StrokeStyle } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { ExcalidrawElement, ExcalidrawLinearElement, ExcalidrawTextElement, FillStyle, GroupId, RoundnessType, StrokeStyle } from "@zsviczian/excalidraw/types/element/src/types";
export type PathCommand = {
type: string;
+18 -6
View File
@@ -1,11 +1,11 @@
import { RestoredDataState } from "@zsviczian/excalidraw/types/excalidraw/data/restore";
import { ImportedDataState } from "@zsviczian/excalidraw/types/excalidraw/data/types";
import { BoundingBox } from "@zsviczian/excalidraw/types/excalidraw/element/bounds";
import { ElementsMap, ExcalidrawBindableElement, ExcalidrawElement, ExcalidrawFrameElement, ExcalidrawFrameLikeElement, ExcalidrawTextContainer, ExcalidrawTextElement, FontFamilyValues, FontString, NonDeleted, NonDeletedExcalidrawElement, Theme } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { FontMetadata } from "@zsviczian/excalidraw/types/excalidraw/fonts/FontMetadata";
import { BoundingBox } from "@zsviczian/excalidraw/types/element/src";
import { ElementsMap, ExcalidrawBindableElement, ExcalidrawElement, ExcalidrawFrameElement, ExcalidrawFrameLikeElement, ExcalidrawTextContainer, ExcalidrawTextElement, FontFamilyValues, FontString, NonDeleted, NonDeletedExcalidrawElement, OrderedExcalidrawElement, Theme } from "@zsviczian/excalidraw/types/element/src/types";
import { FontMetadata } from "@zsviczian/excalidraw/types/common/src";
import { AppState, BinaryFiles, DataURL, GenerateDiagramToCode, Zoom } from "@zsviczian/excalidraw/types/excalidraw/types";
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/src/types";
interface MermaidConfig {
/**
@@ -52,7 +52,7 @@ type EmbeddedLink =
declare namespace ExcalidrawLib {
type ElementUpdate<TElement extends ExcalidrawElement> = Omit<
Partial<TElement>,
"id" | "version" | "versionNonce"
"id" | "updated"
>;
type ExportOpts = {
@@ -108,6 +108,7 @@ declare namespace ExcalidrawLib {
function determineFocusDistance(
element: ExcalidrawBindableElement,
elementsMap: ElementsMap,
a: GlobalPoint,
b: GlobalPoint,
): number;
@@ -146,6 +147,15 @@ declare namespace ExcalidrawLib {
elementsMap: ElementsMap,
): ExcalidrawElement[][];
function getFontMetrics(fontFamily: ExcalidrawTextElement["fontFamily"], fontSize?:number): {
unitsPerEm: number,
ascender: number,
descender: number,
lineHeight: number,
baseline: number,
fontString: string
}
function measureText(
text: string,
font: FontString,
@@ -221,5 +231,7 @@ declare namespace ExcalidrawLib {
function safelyParseJSON (json: string): Record<string, any> | null;
function loadSceneFonts(elements: NonDeletedExcalidrawElement[]): Promise<void>;
function loadMermaid(): Promise<any>;
function syncInvalidIndices(elements: readonly ExcalidrawElement[]): OrderedExcalidrawElement[];
function syncMovedIndices(elements: readonly ExcalidrawElement[], movedElements: ElementsMap): OrderedExcalidrawElement[];
}
+9 -1
View File
@@ -1,7 +1,7 @@
// src/types/ExcalidrawViewTypes.ts
import { WorkspaceLeaf } from "obsidian";
import { FileId } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
import { ObsidianCanvasNode } from "../view/managers/CanvasNodeFactory";
export type Position = { x: number; y: number };
@@ -22,11 +22,19 @@ export interface EmbeddableLeafRef {
editNode?: Function;
}
export interface AutoexportConfig {
png: boolean; // Whether to auto-export to PNG
svg: boolean; // Whether to auto-export to SVG
excalidraw: boolean; // Whether to auto-export to Excalidraw format
theme: "light" | "dark" | "both"; // The theme to use for the export
}
export interface ViewSemaphores {
warnAboutLinearElementLinkClick: boolean;
//flag to prevent overwriting the changes the user makes in an embeddable view editing the back side of the drawing
embeddableIsEditingSelf: boolean;
popoutUnload: boolean; //the unloaded Excalidraw view was the last leaf in the popout window
viewloaded: boolean; //onLayoutReady in view.onload has completed.
viewunload: boolean;
//first time initialization of the view
scriptsReady: boolean;
+14
View File
@@ -0,0 +1,14 @@
export type ButtonDefinition = { caption: string; tooltip?:string; action: Function };
export interface InputPromptOptions {
header: string,
placeholder?: string,
value?: string,
buttons?: ButtonDefinition[],
lines?: number,
displayEditorButtons?: boolean,
customComponents?: (container: HTMLElement) => void,
blockPointerInputOutsideModal?: boolean,
controlsOnTop?: boolean,
draggable?: boolean,
}
+2
View File
@@ -18,6 +18,7 @@ export type GridSettings = {
DYNAMIC_COLOR: boolean; // Whether the grid color is dynamic
COLOR: string; // The grid color (in hex format)
OPACITY: number; // The grid opacity (hex value between "00" and "FF")
GRID_DIRECTION: {horizontal: boolean, vertical: boolean}; // Whether the grid is horizontal or vertical
};
export type DeviceType = {
@@ -57,6 +58,7 @@ declare global {
declare module "obsidian" {
interface App {
internalPlugins: any;
setting: any;
isMobile(): boolean;
getObsidianUrl(file:TFile): string;
metadataTypeManager: {
+137
View File
@@ -0,0 +1,137 @@
import { Notice } from "obsidian";
import { debug, DEBUGGING } from "./debugHelper";
/**
* Centralized error handling for the Excalidraw plugin
*/
export class ErrorHandler {
private static instance: ErrorHandler;
private errorLog: Array<{error: Error, context: string, timestamp: number}> = [];
private errorNoticeTimeout: number = 10000; // 10 seconds
private maxLogEntries: number = 100;
private constructor() {}
/**
* Get singleton instance of ErrorHandler
*/
public static getInstance(): ErrorHandler {
if (!ErrorHandler.instance) {
ErrorHandler.instance = new ErrorHandler();
}
return ErrorHandler.instance;
}
/**
* Handles errors consistently across the plugin
* @param error The error object
* @param context Context information about where the error occurred
* @param showNotice Whether to show a user-facing notice
* @param timeout How long to show the notice (in ms)
*/
public handleError(
error: Error | string,
context: string,
showNotice = true,
timeout?: number
): void {
const errorObj = typeof error === 'string' ? new Error(error) : error;
// Log to console with better formatting
console.error(`[Excalidraw Error] in ${context}:`, errorObj);
// Add to error log with timestamp
this.errorLog.push({
error: errorObj,
context,
timestamp: Date.now()
});
// Trim log if it gets too large
if (this.errorLog.length > this.maxLogEntries) {
this.errorLog = this.errorLog.slice(this.errorLog.length - this.maxLogEntries);
}
// Show notice to user if required
if (showNotice) {
const formattedError = this.formatErrorForUser(errorObj, context);
new Notice(formattedError, timeout || this.errorNoticeTimeout);
}
// Debug output if debugging is enabled
if ((process.env.NODE_ENV === 'development') && DEBUGGING) {
debug(this.handleError, `ErrorHandler.handleError: ${context}`, errorObj);
}
}
/**
* Safely evaluates code with error handling
* @param code The code to evaluate
* @param context The context where evaluation is happening
* @param win The window object for evaluation context
* @param fallback Optional fallback value if evaluation fails
*/
public safeEval<T>(code: string, context: string, win: Window, fallback?: T): T {
try {
return win.eval.call(win, code) as T;
} catch (error) {
this.handleError(error, `SafeEval in ${context}`);
if (fallback !== undefined) {
return fallback;
}
throw error; // Re-throw if no fallback provided
}
}
/**
* Wraps a function with try/catch and error handling
* @param fn Function to wrap
* @param context Context for error reporting
* @param fallback Optional fallback value if function fails
*/
public wrapWithTryCatch<T>(fn: () => T, context: string, fallback?: T): T {
try {
return fn();
} catch (error) {
this.handleError(error, context);
if (fallback !== undefined) return fallback;
throw error; // Re-throw if no fallback provided
}
}
/**
* Format error message for user-facing notifications
*/
private formatErrorForUser(error: Error, context: string): string {
// Shorten and simplify the message for users
let message = error.message;
// Special handling for common error types
if (message.includes("Cannot read properties of undefined")) {
message = "A required object was not available. This might be due to a plugin loading issue.";
} else if (message.includes("is not a function")) {
message = "A required function was not available. This might be due to a plugin version mismatch.";
} else if (message.length > 100) {
// Truncate very long messages
message = message.substring(0, 100) + "...";
}
return `Excalidraw Error: ${message} (in ${context})`;
}
/**
* Get recent errors for debugging
*/
public getErrorLog(): Array<{error: Error, context: string, timestamp: number}> {
return [...this.errorLog];
}
/**
* Clear error log
*/
public clearErrorLog(): void {
this.errorLog = [];
}
}
export const errorHandler = ErrorHandler.getInstance();
+1 -1
View File
@@ -1,6 +1,6 @@
//for future use, not used currently
import { ImageCrop } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { ImageCrop } from "@zsviczian/excalidraw/types/element/src/types";
import { PDFPageViewProps } from "src/shared/EmbeddedFileLoader";
export function getPDFCropRect (props: {
+4 -4
View File
@@ -1,10 +1,10 @@
import { ExcalidrawEmbeddableElement, ExcalidrawFrameElement, ExcalidrawImageElement } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
import { ExcalidrawEmbeddableElement, ExcalidrawFrameElement, ExcalidrawImageElement } from "@zsviczian/excalidraw/types/element/src/types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { getEA } from "src/core";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { getCropFileNameAndFolder, getListOfTemplateFiles, splitFolderAndFilename } from "./fileUtils";
import { getCropFileNameAndFolder, getListOfTemplateFiles } from "./fileUtils";
import { Notice, TFile } from "obsidian";
import { Radians } from "@zsviczian/excalidraw/types/math";
import { Radians } from "@zsviczian/excalidraw/types/math/src/types";
export const CROPPED_PREFIX = "cropped_";
export const ANNOTATED_PREFIX = "annotated_";
+95 -12
View File
@@ -1,9 +1,25 @@
import { NonDeletedExcalidrawElement } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { DEVICE, REG_LINKINDEX_INVALIDCHARS } from "src/constants/constants";
import { getParentOfClass } from "./obsidianUtils";
import { App, Notice, TFile, WorkspaceLeaf } from "obsidian";
import { NonDeletedExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import { AUDIO_TYPES, DEVICE, REG_LINKINDEX_INVALIDCHARS, VIDEO_TYPES } from "src/constants/constants";
import { ConstructableWorkspaceSplit, getContainerForDocument, getParentOfClass } from "./obsidianUtils";
import { App, TFile, WorkspaceLeaf, WorkspaceSplit } from "obsidian";
import { getLinkParts } from "./utils";
import ExcalidrawView from "src/view/ExcalidrawView";
import { ObsidianCanvasNode } from "src/view/managers/CanvasNodeFactory";
export const createLeaf = (view: ExcalidrawView): {leaf: WorkspaceLeaf, rootSplit: WorkspaceSplit} => {
const doc = view.ownerDocument;
const rootSplit:WorkspaceSplit = new (WorkspaceSplit as ConstructableWorkspaceSplit)(view.app.workspace, "vertical");
rootSplit.getRoot = () => view.app.workspace[doc === document ? 'rootSplit' : 'floatingSplit'];
rootSplit.getContainer = () => getContainerForDocument(doc);
rootSplit.containerEl.style.width = '100%';
rootSplit.containerEl.style.height = '100%';
rootSplit.containerEl.style.borderRadius = "var(--embeddable-radius)";
view.plugin.setDebounceActiveLeafChangeHandler();
return {
leaf: view.app.workspace.createLeafInParent(rootSplit, 0),
rootSplit,
};
}
export const useDefaultExcalidrawFrame = (element: NonDeletedExcalidrawElement) => {
return !(element.link.startsWith("[") || element.link.startsWith("file:") || element.link.startsWith("data:")); // && !element.link.match(TWITTER_REG);
@@ -13,14 +29,39 @@ export const leafMap = new Map<string, WorkspaceLeaf>();
//This is definitely not the right solution, feels like sticking plaster
//patch disappearing content on mobile
export const patchMobileView = (view: ExcalidrawView) => {
if(DEVICE.isDesktop) return;
//based on obsidian app.js, obsidian is looking for activeEditor, but active editor is in a leaf that is disconnected from root
export const patchMobileView = (
view: ExcalidrawView,
opts?: { keepAlive?: boolean; isActive?: () => boolean }
): (() => void) | void => {
if (!DEVICE.isPhone) return;
console.log("patching mobile view");
const parent = getParentOfClass(view.containerEl,"mod-top");
if(parent) {
if(!parent.hasClass("mod-visible")) {
const parent = getParentOfClass(view.containerEl, "mod-top");
if (parent) {
if (!parent.hasClass("mod-visible")) {
parent.addClass("mod-visible");
}
// create observer here
const observer = new MutationObserver(() => {
if (opts?.keepAlive && opts?.isActive && !opts.isActive()) {
observer.disconnect();
return;
}
if (!parent.hasClass("mod-visible")) {
parent.addClass("mod-visible");
}
});
observer.observe(parent, { attributes: true, attributeFilter: ["class"] });
const cleanup = () => observer.disconnect();
if (opts?.keepAlive) {
// Keep the observer alive until caller cleans up (or callback signals inactive)
return cleanup;
}
// default behavior: disconnect after 500ms
window.setTimeout(cleanup, 500);
return cleanup;
}
}
@@ -58,16 +99,58 @@ export const generateEmbeddableLink = (src: string, theme: "light" | "dark"):str
}
export function setFileToLocalGraph(app: App, file: TFile) {
let lgv;
let lgv: any;
app.workspace.iterateAllLeaves((l) => {
if (l.view?.getViewType() === "localgraph") lgv = l.view;
});
if(!lgv) return;
try {
if (lgv) {
//@ts-ignore
if (lgv.loadFile && lgv.file !== file) {
lgv.loadFile(file);
}
} catch (e) {
console.error(e);
}
}
export function predictViewType(app: App, file: TFile): string {
const ext = file.extension?.toLowerCase?.() ?? "";
// 1) Try private registry APIs when available (covers .md files with custom views like Kanban)
const vr = (app as any)?.viewRegistry;
const registryFileMethods = [
"getViewTypeForFile",
"getViewTypeByFile",
"getTypeByFile",
];
for (const m of registryFileMethods) {
if (vr?.[m]) {
try {
const vt = vr[m](file);
if (typeof vt === "string" && vt) return vt;
} catch {}
}
}
// 2) Try extension mapping from registry
const registryExtMethods = [
"getViewTypeByExtension",
"getTypeByExtension",
];
for (const m of registryExtMethods) {
if (vr?.[m]) {
try {
const vt = vr[m](ext);
if (typeof vt === "string" && vt) return vt;
} catch {}
}
}
// 3) Fallbacks by extension
if (ext === "md") return "markdown";
if (ext === "pdf") return "pdf";
if (ext === "canvas") return "canvas";
if (AUDIO_TYPES.contains(ext)) return "audio";
if (VIDEO_TYPES.contains(ext)) return "video";
return "empty";
}
+2 -3
View File
@@ -4,9 +4,8 @@ import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import ExcalidrawView from "src/view/ExcalidrawView";
import { DynamicStyle } from "src/types/types";
import { cloneElement } from "./excalidrawAutomateUtils";
import { ExcalidrawFrameElement } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { ExcalidrawFrameElement } from "@zsviczian/excalidraw/types/element/src/types";
import { addAppendUpdateCustomData } from "./utils";
import { mutateElement } from "src/constants/constants";
import { CaptureUpdateAction } from "src/constants/constants";
export const setDynamicStyle = (
@@ -176,7 +175,7 @@ export const setDynamicStyle = (
) {
return;
}
mutateElement(e,{customData: f.customData});
(view.excalidrawAPI as ExcalidrawImperativeAPI).mutateElement(e,{customData: f.customData});
});
view.updateScene({
+49 -23
View File
@@ -5,7 +5,7 @@ import {
ExcalidrawElement,
ExcalidrawImageElement,
FileId,
} from "@zsviczian/excalidraw/types/excalidraw/element/types";
} from "@zsviczian/excalidraw/types/element/src/types";
import { normalizePath, TFile } from "obsidian";
import ExcalidrawView, { ExportSettings, getTextMode } from "src/view/ExcalidrawView";
@@ -32,7 +32,7 @@ import {
} from "src/utils/utils";
import { GenericInputPrompt, NewFileActions } from "src/shared/Dialogs/Prompt";
import { t } from "src/lang/helpers";
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import {
postOpenAI as _postOpenAI,
extractCodeBlocks as _extractCodeBlocks,
@@ -42,6 +42,7 @@ import { SVGColorInfo } from "src/types/excalidrawAutomateTypes";
import { ExcalidrawData, getExcalidrawMarkdownHeaderSection, REGEX_LINK } from "src/shared/ExcalidrawData";
import { getFrameBasedOnFrameNameOrId } from "./excalidrawViewUtils";
import { ScriptEngine } from "src/shared/Scripts";
import { getEA } from "src/core";
declare const PLUGIN_VERSION:string;
@@ -280,10 +281,17 @@ export async function getTemplate(
}
}
if(filenameParts.hasFrameref || filenameParts.hasClippedFrameref) {
const el = getFrameBasedOnFrameNameOrId(filenameParts.blockref,scene.elements);
const el = getFrameBasedOnFrameNameOrId(filenameParts.blockref,scene.elements);
if(el) {
groupElements = plugin.ea.getElementsInFrame(el,scene.elements, filenameParts.hasClippedFrameref);
groupElements = el.frameRole === "marker"
? plugin.ea.getElementsInArea(scene.elements, el).concat(el)
: plugin.ea.getElementsInFrame(el,scene.elements, filenameParts.hasClippedFrameref);
}
}
if(filenameParts.hasArearef) {
const el=scene.elements.find((el: ExcalidrawElement)=>el.id===filenameParts.blockref);
if(el) {
groupElements = plugin.ea.getElementsInArea(scene.elements, el);
}
}
@@ -456,12 +464,16 @@ export const updateElementLinksToObsidianLinks = ({elements, hostFile}:{
}
let link = EXCALIDRAW_PLUGIN.app.getObsidianUrl(file);
if(window.ExcalidrawAutomate?.onUpdateElementLinkForExportHook) {
link = window.ExcalidrawAutomate.onUpdateElementLinkForExportHook({
originalLink: el.link,
obsidianLink: link,
linkedFile: file,
hostFile: hostFile
});
try {
link = window.ExcalidrawAutomate.onUpdateElementLinkForExportHook({
originalLink: el.link,
obsidianLink: link,
linkedFile: file,
hostFile: hostFile
}) ?? link;
} catch (e) {
errorlog({where: "excalidrawAutomateUtils.updateElementLinksToObsidianLinks", fn: window.ExcalidrawAutomate.onUpdateElementLinkForExportHook, error: e});
}
}
const newElement: Mutable<ExcalidrawElement> = cloneElement(el);
newElement.link = link;
@@ -547,13 +559,21 @@ export async function createSVG(
if (withTheme && theme === "dark") addFilterToForeignObjects(svg);
if(
!(filenameParts.hasGroupref || filenameParts.hasFrameref || filenameParts.hasClippedFrameref) &&
!(filenameParts.hasGroupref || filenameParts.hasClippedFrameref) &&
(filenameParts.hasBlockref || filenameParts.hasSectionref)
) {
let el = filenameParts.hasSectionref
? getTextElementsMatchingQuery(elements,["# "+filenameParts.sectionref],true)
: elements.filter((el: ExcalidrawElement)=>el.id===filenameParts.blockref);
if(el.length>0) {
if(el.length === 0 && filenameParts.hasFrameref) {
const frame = getFrameBasedOnFrameNameOrId(filenameParts.blockref, elements);
if(frame) {
el = [frame];
}
}
const isNonMarkerFrameRef = filenameParts.hasFrameref && el.length === 1 && el[0].type === "frame" && el[0].frameRole !== "marker";
if(el.length>0 && !isNonMarkerFrameRef) {
const containerId = el[0].containerId;
if(containerId) {
el = el.concat(elements.filter((el: ExcalidrawElement)=>el.id === containerId));
@@ -624,9 +644,9 @@ export function repositionElementsToCursor(
return restore({elements}, null, null).elements;
}
export const insertLaTeXToView = (view: ExcalidrawView) => {
export const insertLaTeXToView = (view: ExcalidrawView, center: boolean = false) => {
const app = view.plugin.app;
const ea = view.plugin.ea;
const ea = getEA(view) as ExcalidrawAutomate;
GenericInputPrompt.Prompt(
view,
view.plugin,
@@ -637,13 +657,19 @@ export const insertLaTeXToView = (view: ExcalidrawView) => {
undefined,
3
).then(async (formula: string) => {
if (!formula) {
return;
if (formula) {
const id = await ea.addLaTex(0, 0, formula);
if(center) {
const el = ea.getElement(id);
let {width, height} = el;
let {x, y} = ea.getViewCenterPosition();
el.x = x - width / 2;
el.y = y - height / 2;
}
await ea.addElementsToView(!center, false, true);
ea.selectElementsInView([id]);
}
ea.reset();
await ea.addLaTex(0, 0, formula);
ea.setView(view);
ea.addElementsToView(true, false, true);
ea.destroy();
});
};
@@ -698,14 +724,14 @@ export const getTextElementsMatchingQuery = (
el.type === "text" &&
query.some((q) => {
if (exactMatch) {
const text = el.rawText.toLowerCase().split("\n")[0].trim();
const text = el.customData?.text2Path?.text ?? el.rawText.toLowerCase().split("\n")[0].trim();
const m = text.match(/^#*(# .*)/);
if (!m || m.length !== 2) {
return false;
}
return m[1] === q.toLowerCase();
}
const text = el.rawText.toLowerCase().replaceAll("\n", " ").trim();
const text = el.customData?.text2Path?.text ?? el.rawText.toLowerCase().replaceAll("\n", " ").trim();
return text.match(q.toLowerCase()); //to distinguish between "# frame" and "# frame 1" https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/530
}));
}
+2 -2
View File
@@ -1,5 +1,5 @@
import { ExcalidrawArrowElement, ExcalidrawElement, ExcalidrawTextElement } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
import { ExcalidrawArrowElement, ExcalidrawElement, ExcalidrawTextElement } from "@zsviczian/excalidraw/types/element/src/types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
export function updateElementIdsInScene(
+60 -13
View File
@@ -1,20 +1,21 @@
import { MAX_IMAGE_SIZE, IMAGE_TYPES, ANIMATED_IMAGE_TYPES, MD_EX_SECTIONS } from "src/constants/constants";
import { App, Modal, Notice, TFile, WorkspaceLeaf } from "obsidian";
import { MAX_IMAGE_SIZE, IMAGE_TYPES, ANIMATED_IMAGE_TYPES, MD_EX_SECTIONS, AUDIO_TYPES, CARD_WIDTH, CARD_HEIGHT } from "src/constants/constants";
import { App, Modal, Notice, TFile } from "obsidian";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { REGEX_LINK, REG_LINKINDEX_HYPERLINK, getExcalidrawMarkdownHeaderSection, REGEX_TAGS } from "../shared/ExcalidrawData";
import { REGEX_LINK, REG_LINKINDEX_HYPERLINK, getExcalidrawMarkdownHeaderSection, REGEX_TAGS, getExcalidrawMarkdownHeader } from "../shared/ExcalidrawData";
import ExcalidrawView from "src/view/ExcalidrawView";
import { ExcalidrawElement, ExcalidrawFrameElement, ExcalidrawImageElement } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { ExcalidrawElement, ExcalidrawFrameElement, ExcalidrawImageElement } from "@zsviczian/excalidraw/types/element/src/types";
import { getEmbeddedFilenameParts, getLinkParts, isImagePartRef } from "./utils";
import { cleanSectionHeading } from "./obsidianUtils";
import { cleanSectionHeading, getAudioElementHeight } from "./obsidianUtils";
import { getEA } from "src/core";
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
import { AppState, ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
import { EmbeddableMDCustomProps } from "src/shared/Dialogs/EmbeddableSettings";
import { nanoid } from "nanoid";
import { t } from "src/lang/helpers";
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { EmbeddedFile } from "src/shared/EmbeddedFileLoader";
import { CaptureUpdateAction } from "src/constants/constants";
import ExcalidrawPlugin from "src/core/main";
export async function insertImageToView(
ea: ExcalidrawAutomate,
@@ -39,6 +40,16 @@ export async function insertImageToView(
return id;
}
export function deleteAppStateKeys(
st: AppState,
[...keys]: (keyof AppState)[],
): Partial<AppState> {
keys.forEach((key) => {
delete (st as Mutable<AppState>)[key];
});
return st;
};
export async function insertEmbeddableToView (
ea: ExcalidrawAutomate,
position: { x: number, y: number },
@@ -65,11 +76,20 @@ export async function insertEmbeddableToView (
if(file && (IMAGE_TYPES.contains(file.extension) || ea.isExcalidrawFile(file)) && !ANIMATED_IMAGE_TYPES.contains(file.extension)) {
return await insertImageToView(ea, position, link??file, undefined, shouldInsertToView);
} else {
let height = MAX_IMAGE_SIZE;
if (
(file && AUDIO_TYPES.contains(file.extension.toLowerCase())) ||
(link && AUDIO_TYPES.contains(link.match(/\[\[[^\]]+?\.([^\.\]]+)]]/)?.[1]?.toLocaleLowerCase()))
) {
ea.style.strokeColor = "transparent";
ea.style.backgroundColor = "transparent";
height = getAudioElementHeight();
}
const id = ea.addEmbeddable(
position.x,
position.y,
MAX_IMAGE_SIZE,
MAX_IMAGE_SIZE,
height,
link,
file,
);
@@ -209,8 +229,8 @@ export function getFrameBasedOnFrameNameOrId(
): ExcalidrawFrameElement | null {
const frames = elements
.filter((el: ExcalidrawElement)=>el.type==="frame")
.map((el: ExcalidrawFrameElement, idx: number)=>{
return {el: el, id: el.id, name: el.name ?? `Frame ${String(idx+1).padStart(2,"0")}`};
.map((el: ExcalidrawFrameElement)=>{
return {el: el, id: el.id, name: el.name ?? "Frame"};
})
.filter((item:any) => item.id === frameName || item.name === frameName)
.map((item:any)=>item.el as ExcalidrawFrameElement);
@@ -223,6 +243,8 @@ export async function addBackOfTheNoteCard(
activate: boolean = true,
cardBody?: string,
embeddableCustomData?: EmbeddableMDCustomProps,
center: boolean = false,
position?: {x: number, y: number},
):Promise<string> {
const data = view.data;
const header = getExcalidrawMarkdownHeaderSection(data);
@@ -252,13 +274,22 @@ export async function addBackOfTheNoteCard(
}
const ea = getEA(view) as ExcalidrawAutomate;
let {x,y} = position ?? ea.targetView.currentPosition;
if(center) {
const centerPos = ea.getViewCenterPosition();
if(centerPos) {
x = centerPos.x - (CARD_WIDTH / 2);
y = centerPos.y - (CARD_HEIGHT / 2);
}
}
const id = ea.addEmbeddable(
0,0,400,500,
x,y,CARD_WIDTH,CARD_HEIGHT,
`[[${view.file.path}#${title}]]`,
undefined,
embeddableCustomData
);
await ea.addElementsToView(true, false, true);
await ea.addElementsToView(!center, false, true);
const api = view.excalidrawAPI as ExcalidrawImperativeAPI;
const el = ea.getViewElements().find(el=>el.id === id);
@@ -267,7 +298,7 @@ export async function addBackOfTheNoteCard(
window.setTimeout(()=>{
api.updateScene({appState: {activeEmbeddable: {element: el, state: "active"}}, captureUpdate: CaptureUpdateAction.NEVER,});
if(found) view.getEmbeddableLeafElementById(el.id)?.editNode?.();
});
},200);
}
ea.destroy();
return el.id;
@@ -465,4 +496,20 @@ export async function toggleImageAnchoring(
}
await ea.addElementsToView(false, false);
ea.destroy();
}
export function onLoadMessages(plugin: ExcalidrawPlugin, scene: {elements: ExcalidrawElement[], appState: AppState}, data: string) {
setTimeout(() => {
if(!(scene.appState.frameRendering?.markerEnabled ?? true) && scene.elements.some(el=>el.type === "frame" && el.frameRole === "marker")) {
new Notice(t("MARKER_FRAME_RENDERING_DISABLED_NOTICE"));
}
/*const backOfTheCardNote = getExcalidrawMarkdownHeader(data)
.header
.replace(/^---\n[\s\S]*?\n---/gm, "")
.replace("==⚠ Switch to EXCALIDRAW VIEW in the MORE OPTIONS menu of this document. ⚠== You can decompress Drawing data with the command palette: 'Decompress current Excalidraw file'. For more info check in plugin settings under 'Saving'","")
.trim();
if(backOfTheCardNote.length>0) {
new Notice(t("DRAWING_HAS_BACK_OF_THE_CARD"));
}*/
});
}
+285 -56
View File
@@ -1,6 +1,8 @@
import { Notice } from 'obsidian';
import { DEVICE } from 'src/constants/constants';
import { t } from 'src/lang/helpers';
import { download } from './fileUtils';
import { svgToBase64 } from './utils';
const DPI = 96;
@@ -54,7 +56,9 @@ export const STANDARD_PAGE_SIZES = {
Legal: { width: 816, height: 1344 }, // 8.5 × 14 inches
Letter: { width: 816, height: 1056 }, // 8.5 × 11 inches
Tabloid: { width: 1056, height: 1632 }, // 11 × 17 inches
Ledger: { width: 1632, height: 1056 } // 17 × 11 inches
Ledger: { width: 1632, height: 1056 }, // 17 × 11 inches
"HD Screen": { width: 1920, height: 1080 },// 16:9 aspect ratio
"MATCH IMAGE": { width: 0, height: 0 }, // 0 means use the current screen size
} as const;
export type PageSize = keyof typeof STANDARD_PAGE_SIZES;
@@ -69,9 +73,15 @@ export function getMarginValue(margin:PDFPageMarginString): PDFMargin {
}
}
export function getPageDimensions(pageSize: PageSize, orientation: PageOrientation): PageDimensions {
const dimensions = STANDARD_PAGE_SIZES[pageSize];
return orientation === "portrait"
export function getPageDimensions(pageSize: PageSize, orientation: PageOrientation, dims?: {width: number, height: number}): PageDimensions {
let dimensions:{width: number, height: number};
dimensions = STANDARD_PAGE_SIZES[pageSize];
if (dims && dimensions.width === 0 && dimensions.height === 0) {
dimensions = { width: dims.width, height: dims.height };
}
return orientation === "portrait" || pageSize === "MATCH IMAGE" || pageSize === "HD Screen"
? { width: dimensions.width, height: dimensions.height }
: { width: dimensions.height, height: dimensions.width };
}
@@ -86,6 +96,10 @@ interface PrintToPDFOptions {
scale: number;
open: boolean;
filepath: string;
// Prefer CSS @page size over the numeric pageSize for mixed-size documents
preferCSSPageSize?: boolean;
// Exclude page ranges from output (Chromium/Electron supports either string "2-" or array)
pageRanges?: string | { from: number; to: number }[];
}
interface SaveDialogOptions {
@@ -162,23 +176,54 @@ async function printPdf(
bgColor: string,
pageSize: PageSize | PageDimensions,
isLandscape: boolean,
margins: { top: number; left: number; right: number; bottom: number }
margins: { top: number; left: number; right: number; bottom: number },
shouldOpen: boolean = true,
extraCss: string = "",
pageRanges?: string | { from: number; to: number }[], // NEW
): Promise<void> {
const styleTag = document.createElement('style');
styleTag.textContent = `
@media print {
/* Ensure the print root expands to the widest page and is not constrained by app layout */
.print {
background-color: ${bgColor} !important;
display: flex !important;
justify-content: center !important;
align-items: center !important;
display: block !important;
width: max-content !important;
max-width: none !important;
overflow: visible !important;
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
flex-direction: column !important;
page-break-before: always;
margin: 0px !important;
padding: 0px !important;
margin: 0 !important;
padding: 0 !important;
position: static !important;
transform: none !important;
box-sizing: content-box !important;
}
.print > * {
width: max-content !important;
max-width: none !important;
}
.print-page {
display: block !important;
break-after: page !important;
page-break-after: always !important;
break-inside: avoid-page !important;
overflow: visible !important;
margin: 0 !important;
position: relative !important;
}
/* Keep spacer tiny; it still establishes the initial page box */
.print-page.dummy-first {
width: 1px !important;
height: 1px !important;
}
.print svg,
.print img,
.print canvas {
max-width: none !important;
max-height: none !important;
}
${extraCss}
}
`;
document.head.appendChild(styleTag);
@@ -196,8 +241,10 @@ async function printPdf(
margins,
scaleFactor: 100,
scale: 1,
open: true,
open: shouldOpen,
filepath: pdfPath,
preferCSSPageSize: true,
...(pageRanges ? { pageRanges } : {}), // NEW
};
try {
@@ -246,8 +293,8 @@ function calculateDimensions(
const mid = (low + high) / 2;
const scaledWidth = svgWidth * mid;
const scaledHeight = svgHeight * mid;
const pages = Math.ceil(scaledWidth / availableWidth) *
Math.ceil(scaledHeight / availableHeight);
const pages = Math.ceil(scaledWidth / availableWidth) *
Math.ceil(scaledHeight / availableHeight);
if (pages > scale.fitToPage) {
high = mid;
@@ -435,60 +482,216 @@ export async function exportToPDF({
const savePath = await getSavePath(filename);
if (!savePath) return;
const {width, height} = getPageSizePixels(pageProps.dimensions, false);
const allPagesDiv = createDiv();
allPagesDiv.style.width = "100%";
allPagesDiv.style.height = "fit-content";
// Decide if we should run multiple print jobs based on requested dimensions
const dims = pageProps?.dimensions as any;
const useMultiJob =
!dims ||
typeof dims.width !== "number" ||
typeof dims.height !== "number" ||
dims.width <= 0 ||
dims.height <= 0;
let j = 0;
for (const svg of SVG) {
const svgWidth = parseFloat(svg.getAttribute('width') || '0');
const svgHeight = parseFloat(svg.getAttribute('height') || '0');
const {tiles} = calculateDimensions(
svg,
svgWidth,
svgHeight,
pageProps.dimensions,
pageProps.margin,
scale,
pageProps.alignment
);
// Single fixed-size job (existing behavior)
if (!useMultiJob) {
const allPagesDiv = createDiv();
allPagesDiv.style.width = "100%";
allPagesDiv.style.height = "fit-content";
let i = 0;
for (const tile of tiles) {
const pageDiv = createDiv();
pageDiv.style.width = `${width}px`;
pageDiv.style.height = `${height}px`;
pageDiv.style.display = "flex";
pageDiv.style.justifyContent = "start";
pageDiv.style.alignItems = "left";
pageDiv.style.padding = `${pageProps.margin.top}px ${pageProps.margin.right}px ${pageProps.margin.bottom}px ${pageProps.margin.left}px`;
let j = 0;
for (const svg of SVG) {
const svgWidth = parseFloat(svg.getAttribute('width') || '0');
const svgHeight = parseFloat(svg.getAttribute('height') || '0');
const clonedSVG = svg.cloneNode(true) as SVGSVGElement;
clonedSVG.setAttribute('viewBox', tile.viewBox);
clonedSVG.style.width = `${tile.width}px`;
clonedSVG.style.height = `${tile.height}px`;
clonedSVG.style.position = 'absolute';
clonedSVG.style.left = `${tile.x}px`;
clonedSVG.style.top = `${tile.y + (i+j)*height}px`;
const pageDimForSvg: PageDimensions = pageProps.dimensions; // fixed size
const { tiles } = calculateDimensions(
svg,
svgWidth,
svgHeight,
pageDimForSvg,
pageProps.margin,
scale,
pageProps.alignment
);
pageDiv.appendChild(clonedSVG);
allPagesDiv.appendChild(pageDiv);
i++;
const { width: pageWidth, height: pageHeight } = getPageSizePixels(pageDimForSvg, false);
let i = 0;
for (const tile of tiles) {
const pageDiv = createDiv();
pageDiv.addClass('print-page');
// NEW: content box sizing
pageDiv.style.width = `${pageWidth}px`;
pageDiv.style.height = `${pageHeight}px`;
pageDiv.style.display = "flex";
pageDiv.style.justifyContent = "start";
pageDiv.style.alignItems = "left";
//pageDiv.style.padding = `${pageProps.margin.top}px ${pageProps.margin.right}px ${pageProps.margin.bottom}px ${pageProps.margin.left}px`;
pageDiv.style.left = `${pageProps.margin.left}px`;
pageDiv.style.top = `${pageProps.margin.top}px`;
pageDiv.style.position = "relative";
const clonedSVG = svg.cloneNode(true) as SVGSVGElement;
clonedSVG.setAttribute('viewBox', tile.viewBox);
clonedSVG.style.width = `${tile.width}px`;
clonedSVG.style.height = `${tile.height}px`;
clonedSVG.style.position = 'absolute';
// NEW: position within padding box (subtract margins)
clonedSVG.style.left = `${tile.x - pageProps.margin.left}px`;
clonedSVG.style.top = `${tile.y - pageProps.margin.top}px`;
pageDiv.appendChild(clonedSVG);
allPagesDiv.appendChild(pageDiv);
i++;
}
j++;
}
j++;
new Notice(t("EXPORTDIALOG_PDF_PROGRESS_NOTICE"));
try {
await printPdf(
allPagesDiv,
savePath,
pageProps.backgroundColor || "#ffffff",
pageProps.dimensions,
false,
{ top: 0, right: 0, bottom: 0, left: 0 },
true,
);
} catch (error) {
console.error("Failed to export to PDF: ", error);
new Notice(t("EXPORTDIALOG_PDF_PROGRESS_ERROR"));
}
new Notice(t("EXPORTDIALOG_PDF_PROGRESS_DONE"));
return;
}
// Mixed-size single job using CSS @page rules
new Notice(t("EXPORTDIALOG_PDF_PROGRESS_NOTICE"));
try {
const allPagesDiv = createDiv();
allPagesDiv.style.width = "100%";
allPagesDiv.style.height = "fit-content";
// Collect unique page sizes -> named @page rules
const pageRuleNames = new Map<string, { name: string; w: number; h: number }>();
const makeKey = (w: number, h: number) => `${w.toFixed(2)}x${h.toFixed(2)}`;
const toIn = (px: number) => (px / DPI);
const toCssName = (key: string) => `p_${key.replace(/[^\w-]/g, "_")}`;
for (const svg of SVG) {
const svgWidth = parseFloat(svg.getAttribute('width') || '0');
const svgHeight = parseFloat(svg.getAttribute('height') || '0');
const pageDimForSvg: PageDimensions = {
width: svgWidth,
height: svgHeight
};
const key = makeKey(pageDimForSvg.width, pageDimForSvg.height);
if (!pageRuleNames.has(key)) {
pageRuleNames.set(key, { name: toCssName(key), w: pageDimForSvg.width, h: pageDimForSvg.height });
}
const { tiles } = calculateDimensions(
svg,
svgWidth,
svgHeight,
pageDimForSvg,
pageProps.margin,
scale,
pageProps.alignment
);
const { width: pageWidth, height: pageHeight } = getPageSizePixels(pageDimForSvg, false);
const pageClass = pageRuleNames.get(key)!.name;
for (const tile of tiles) {
const pageDiv = createDiv();
pageDiv.addClass('print-page');
// bind to @page rule via page: <name>
pageDiv.addClass(pageClass);
pageDiv.style.setProperty('page', pageClass);
pageDiv.style.width = `${pageWidth}px`;
pageDiv.style.height = `${pageHeight}px`;
pageDiv.style.display = "flex";
pageDiv.style.justifyContent = "start";
pageDiv.style.alignItems = "left";
pageDiv.style.left = `${pageProps.margin.left}px`;
pageDiv.style.top = `${pageProps.margin.top}px`;
pageDiv.style.position = "relative";
const clonedSVG = svg.cloneNode(true) as SVGSVGElement;
clonedSVG.setAttribute('viewBox', tile.viewBox);
clonedSVG.style.width = `${tile.width}px`;
clonedSVG.style.height = `${tile.height}px`;
clonedSVG.style.position = 'absolute';
// Position within padding box: subtract margins from tile coordinates
clonedSVG.style.left = `${tile.x - pageProps.margin.left}px`;
clonedSVG.style.top = `${tile.y - pageProps.margin.top}px`;
pageDiv.appendChild(clonedSVG);
allPagesDiv.appendChild(pageDiv);
}
}
// Build @page CSS with named sizes
let extraCss = "";
for (const { name, w, h } of pageRuleNames.values()) {
extraCss += `
@page ${name} {
size: ${toIn(w)}in ${toIn(h)}in;
margin: 0;
}
.print-page.${name} { page: ${name}; }
`;
}
// Determine a base numeric page size large enough for all pages
let baseW = 0, baseH = 0;
for (const { w, h } of pageRuleNames.values()) {
baseW = Math.max(baseW, w);
baseH = Math.max(baseH, h);
}
const basePageSize = { width: baseW || 800, height: baseH || 600 };
// Ensure we have a class for the base size
const baseKey = makeKey(basePageSize.width, basePageSize.height);
if (!pageRuleNames.has(baseKey)) {
pageRuleNames.set(baseKey, { name: toCssName(baseKey), w: basePageSize.width, h: basePageSize.height });
extraCss += `
@page ${pageRuleNames.get(baseKey)!.name} {
size: ${toIn(basePageSize.width)}in ${toIn(basePageSize.height)}in;
margin: 0;
}
.print-page.${pageRuleNames.get(baseKey)!.name} { page: ${pageRuleNames.get(baseKey)!.name}; }
`;
}
const baseClass = pageRuleNames.get(baseKey)!.name;
// Insert a dummy first page to prime Chromium with the largest page box
const dummy = createDiv();
dummy.addClass('print-page');
dummy.addClass('dummy-first');
dummy.addClass(baseClass);
allPagesDiv.prepend(dummy);
// Kick a single print job, excluding the first (dummy) page
await printPdf(
allPagesDiv,
savePath,
pageProps.backgroundColor || "#ffffff",
pageProps.dimensions,
basePageSize,
false,
{ top: 0, right: 0, bottom: 0, left: 0 }
{ top: 0, right: 0, bottom: 0, left: 0 },
true,
extraCss,
"2-" // EXCLUDE PAGE 1, included to prime the Chromium page box
);
} catch (error) {
console.error("Failed to export to PDF: ", error);
@@ -504,4 +707,30 @@ export async function exportSVGToClipboard(svg: SVGSVGElement) {
} catch (error) {
console.error("Failed to copy SVG to clipboard: ", error);
}
}
}
export async function exportPNGToClipboard(png: Blob) {
await navigator.clipboard.write([
new window.ClipboardItem({
"image/png": png,
}),
]);
}
export function exportPNG(png: Blob, filename: string) {
const reader = new FileReader();
reader.readAsDataURL(png);
reader.onloadend = () => {
const base64data = reader.result;
download(null, base64data, `${filename}.png`);
};
}
export function exportSVG(svg: SVGSVGElement, filename: string) {
download(
null,
svgToBase64(svg.outerHTML),
`${filename}.svg`,
);
}
+102 -12
View File
@@ -1,17 +1,17 @@
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import { App, loadPdfJs, normalizePath, Notice, requestUrl, RequestUrlResponse, TAbstractFile, TFile, TFolder, Vault } from "obsidian";
import { App, loadPdfJs, MetadataCache, normalizePath, Notice, requestUrl, RequestUrlResponse, TAbstractFile, TFile, TFolder, Vault } from "obsidian";
import { DEVICE, EXCALIDRAW_PLUGIN, FRONTMATTER_KEYS, URLFETCHTIMEOUT } from "src/constants/constants";
import { IMAGE_MIME_TYPES, MimeType } from "../shared/EmbeddedFileLoader";
import { ExcalidrawSettings } from "src/core/settings";
import { errorlog, getDataURL } from "./utils";
import ExcalidrawPlugin from "src/core/main";
import { ANNOTATED_PREFIX, CROPPED_PREFIX } from "./carveout";
import { getAttachmentsFolderAndFilePath } from "./obsidianUtils";
import ExcalidrawView from "src/view/ExcalidrawView";
/**
* Splits a full path including a folderpath and a filename into separate folderpath and filename components
* @param filepath
* @returns folderpath will be normalized. This means "/" for root folder and no trailing "/" for other folders
* @returns returns "" for root folder and normalized path for subfolders (no trailing "/", e.g. "folder/subfolder")
*/
type ImageExtension = keyof typeof IMAGE_MIME_TYPES;
@@ -23,11 +23,13 @@ export function splitFolderAndFilename(filepath: string): {
} {
const lastIndex = filepath.lastIndexOf("/");
const filename = lastIndex == -1 ? filepath : filepath.substring(lastIndex + 1);
const lastDotIndex = filename.lastIndexOf(".");
const folderpath = filepath.substring(0, lastIndex);
return {
folderpath: normalizePath(filepath.substring(0, lastIndex)),
folderpath: folderpath ? normalizePath(folderpath) : "",
filename,
basename: filename.replace(/\.[^/.]+$/, ""),
extension: filename.substring(filename.lastIndexOf(".") + 1),
extension: lastDotIndex > 0 ? filename.substring(lastDotIndex + 1) : "",
};
}
@@ -404,9 +406,9 @@ export const getAliasWithSize = (alias: string, size: string): string => {
}
export const getCropFileNameAndFolder = async (plugin: ExcalidrawPlugin, hostPath: string, baseNewFileName: string):Promise<{folderpath: string, filename: string}> => {
let prefix = plugin.settings.cropPrefix;
if(!prefix || prefix.trim() === "") prefix = CROPPED_PREFIX;
const filename = prefix + baseNewFileName + ".md";
let prefix = plugin.settings.cropPrefix || "";
let suffix = plugin.settings.cropSuffix || "";
const filename = prefix + baseNewFileName + suffix + ".md";
if(!plugin.settings.cropFolder || plugin.settings.cropFolder.trim() === "") {
const folderpath = (await getAttachmentsFolderAndFilePath(plugin.app, hostPath, filename)).folder;
return {folderpath, filename};
@@ -417,9 +419,9 @@ export const getCropFileNameAndFolder = async (plugin: ExcalidrawPlugin, hostPat
}
export const getAnnotationFileNameAndFolder = async (plugin: ExcalidrawPlugin, hostPath: string, baseNewFileName: string):Promise<{folderpath: string, filename: string}> => {
let prefix = plugin.settings.annotatePrefix;
if(!prefix || prefix.trim() === "") prefix = ANNOTATED_PREFIX;
const filename = prefix + baseNewFileName + ".md";
let prefix = plugin.settings.annotatePrefix || "";
let suffix = plugin.settings.annotateSuffix || "";
const filename = prefix + baseNewFileName + suffix + ".md";
if(!plugin.settings.annotateFolder || plugin.settings.annotateFolder.trim() === "") {
const folderpath = (await getAttachmentsFolderAndFilePath(plugin.app, hostPath, filename)).folder;
return {folderpath, filename};
@@ -494,8 +496,59 @@ export const hasExcalidrawEmbeddedImagesTreeChanged = (sourceFile: TFile, mtime:
return fileList.some(f=>f.stat.mtime > mtime);
}
export async function createOrOverwriteFile(app: App, path: string, content: string | ArrayBuffer): Promise<TFile> {
export async function exportImageToFile(view: ExcalidrawView, path: string, content: string | ArrayBuffer | Blob, extension: string): Promise<TFile> {
const ea = view?.getHookServer();
if(ea?.onImageExportPathHook) {
try {
path = ea.onImageExportPathHook({
exportFilepath: path,
exportExtension: extension,
excalidrawFile: view.file,
action: "export",
}) ?? path;
} catch (e) {
errorlog({where: "fileUtils.exportImageToFile", fn: ea.onImageExportPathHook, error: e});
}
}
return await createOrOverwriteFile(view.app, path, content);
}
export async function importFileToVault(app: App, fname: string, content: string | ArrayBuffer | Blob, excalidrawFile: TFile, view?: ExcalidrawView): Promise<TFile> {
let hookFilepath:string;
const ea = view?.getHookServer();
if(ea?.onImageFilePathHook) {
try {
hookFilepath = ea.onImageFilePathHook({
currentImageName: fname,
drawingFilePath: excalidrawFile.path,
})
} catch (e) {
errorlog({where: "fileUtils.importFileToVault", fn: ea.onImageFilePathHook, error: e});
}
}
let filepath:string;
if(hookFilepath) {
const {folderpath, filename} = splitFolderAndFilename(hookFilepath);
await checkAndCreateFolder(folderpath);
filepath = getNewUniqueFilepath(app.vault,filename,folderpath);
} else {
const {folder} = await getAttachmentsFolderAndFilePath(app, excalidrawFile.path, fname);
filepath = getNewUniqueFilepath(app.vault,fname,folder);
}
return await createOrOverwriteFile(app, filepath, content);
}
export async function createOrOverwriteFile(app: App, path: string, content: string | ArrayBuffer | Blob): Promise<TFile> {
const {folderpath} = splitFolderAndFilename(path);
if(folderpath) {
await checkAndCreateFolder(folderpath);
}
const file = app.vault.getAbstractFileByPath(normalizePath(path));
if (content instanceof Blob) {
content = await content.arrayBuffer();
}
if(content instanceof ArrayBuffer) {
if(file && file instanceof TFile) {
await app.vault.modifyBinary(file, content);
@@ -511,4 +564,41 @@ export async function createOrOverwriteFile(app: App, path: string, content: str
} else {
return await app.vault.create(path, content);
}
}
export async function createFileAndAwaitMetacacheUpdate(
app: App,
path: string,
content: string | ArrayBuffer | Blob,
) : Promise<TFile> {
path = normalizePath(path);
let ready = false;
const extension = path.substring(path.lastIndexOf(".") + 1);
//metadataCache.on("changed", (file:TFile) => void) does not fire for non-markdown files
if(extension === "md") {
const metaCache: MetadataCache = app.metadataCache;
const handler = (file:TFile) => {
if(file.path === path) {
metaCache.off("changed", handler);
ready = true;
}
}
metaCache.on("changed", handler);
const file = await createOrOverwriteFile(app, path, content);
if(!file) {
ready = true; //if file is null, it means it was not created, so we can skip waiting
metaCache.off("changed", handler);
}
let attempts = 0;
while (!ready && attempts++ < 15) await sleep(50);
if(!ready) {
metaCache.off("changed", handler); //if we timed out, remove the handler
}
return file;
}
return await createOrOverwriteFile(app, path, content);
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { ExcalidrawElement, ExcalidrawImageElement, ExcalidrawTextElement } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { ExcalidrawElement, ExcalidrawImageElement, ExcalidrawTextElement } from "@zsviczian/excalidraw/types/element/src/types";
import { REGEX_LINK, REG_LINKINDEX_HYPERLINK } from "../shared/ExcalidrawData";
import ExcalidrawView, { TextMode } from "src/view/ExcalidrawView";
import { rotatedDimensions } from "./utils";
+3 -3
View File
@@ -1,5 +1,5 @@
import { THEME } from "../constants/constants";
import type { Theme } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { EXCALIDRAW_PLUGIN, THEME } from "../constants/constants";
import type { Theme } from "@zsviczian/excalidraw/types/element/src/types";
import type { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import type { OpenAIInput, OpenAIOutput } from "@zsviczian/excalidraw/types/excalidraw/data/ai/types";
@@ -43,7 +43,7 @@ export async function diagramToHTML({
theme?: Theme;
}) {
const body: OpenAIInput.ChatCompletionCreateParamsBase = {
model: "gpt-4-vision-preview",
model: EXCALIDRAW_PLUGIN.settings.openAIDefaultVisionModel,
// 4096 are max output tokens allowed for `gpt-4-vision-preview` currently
max_tokens: 4096,
temperature: 0.1,
+1 -1
View File
@@ -1,4 +1,4 @@
import { ExcalidrawElement, ExcalidrawImageElement } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { ExcalidrawElement, ExcalidrawImageElement } from "@zsviczian/excalidraw/types/element/src/types";
import { requireApiVersion } from "obsidian";
export function getMermaidImageElements (elements: ExcalidrawElement[]):ExcalidrawImageElement[] {
+142 -54
View File
@@ -3,10 +3,10 @@ import {
Editor,
FrontMatterCache,
MarkdownView,
normalizePath, OpenViewState, parseFrontMatterEntry, TFile, View, ViewState, Workspace, WorkspaceLeaf, WorkspaceSplit
OpenViewState, parseFrontMatterEntry, TextFileView, TFile, View, ViewState, Workspace, WorkspaceLeaf, WorkspaceSplit
} from "obsidian";
import ExcalidrawPlugin from "../core/main";
import { checkAndCreateFolder, splitFolderAndFilename } from "./fileUtils";
import { splitFolderAndFilename } from "./fileUtils";
import { linkClickModifierType, ModifierKeys } from "./modifierkeyHelper";
import { DEVICE, EXCALIDRAW_PLUGIN, REG_BLOCK_REF_CLEAN, REG_SECTION_REF_CLEAN, VIEW_TYPE_EXCALIDRAW } from "src/constants/constants";
import yaml from "js-yaml";
@@ -30,6 +30,14 @@ export function getExcalidrawViews(app: App): ExcalidrawView[] {
return leaves.map(l=>l.view as ExcalidrawView);
}
export function getExcalidraAndMarkdowViewsForFile(app: App, file: TFile): TextFileView[] {
const leaves = [
...app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW).filter(l=>l.view instanceof ExcalidrawView),
...app.workspace.getLeavesOfType("markdown").filter(l=>l.view instanceof MarkdownView)
];
return leaves.map(l=>l.view as TextFileView).filter(v=>v.file === file);
}
export const getLeaf = (
plugin: ExcalidrawPlugin,
origo: WorkspaceLeaf,
@@ -174,25 +182,13 @@ export const getAttachmentsFolderAndFilePath = async (
activeViewFilePath: string,
newFileName: string
): Promise<{ folder: string; filepath: string; }> => {
let folder = app.vault.getConfig("attachmentFolderPath");
// folder == null: save to vault root
// folder == "./" save to same folder as current file
// folder == "folder" save to specific folder in vault
// folder == "./folder" save to specific subfolder of current active folder
if (folder && folder.startsWith("./")) {
// folder relative to current file
const activeFileFolder = `${splitFolderAndFilename(activeViewFilePath).folderpath}/`;
folder = normalizePath(activeFileFolder + folder.substring(2));
}
if (!folder || folder === "/") {
folder = "";
}
await checkAndCreateFolder(folder);
const { basename, extension } = splitFolderAndFilename(newFileName);
const activeViewFile = app.vault.getFileByPath(activeViewFilePath);
const attachmentFilePath = await app.vault.getAvailablePathForAttachments(basename, extension, activeViewFile);
const { folderpath } = splitFolderAndFilename(attachmentFilePath);
return {
folder,
filepath: normalizePath(
folder === "" ? newFileName : `${folder}/${newFileName}`
),
folder: folderpath,
filepath: attachmentFilePath
};
};
@@ -308,50 +304,93 @@ export const openLeaf = ({
}
export function mergeMarkdownFiles (template: string, target: string): string {
// Extract frontmatter from the template
const templateFrontmatterEnd = template.indexOf('---', 4); // Find end of frontmatter
const templateFrontmatter = template.substring(4, templateFrontmatterEnd).trim();
const templateContent = template.substring(templateFrontmatterEnd + 3); // Skip frontmatter and ---
// Parse template frontmatter
const templateFrontmatterObj: FrontMatterCache = yaml.load(templateFrontmatter) || {};
// Template frontmatter
const templateFrontmatterEnd = template.indexOf('---', 4);
const templateFrontmatterRaw = template.substring(4, templateFrontmatterEnd).trim();
const templateContent = template.substring(templateFrontmatterEnd + 3);
const templateFrontmatterObj: FrontMatterCache = yaml.load(templateFrontmatterRaw) || {};
// Extract frontmatter from the target if it exists
let targetFrontmatterObj: FrontMatterCache = {};
let targetContent = '';
if (target.startsWith('---\n') && target.indexOf('---\n', 4) > 0) {
const targetFrontmatterEnd = target.indexOf('---\n', 4); // Find end of frontmatter
const targetFrontmatter = target.substring(4, targetFrontmatterEnd).trim();
targetContent = target.substring(targetFrontmatterEnd + 3); // Skip frontmatter and ---
const hasTargetFM = target.startsWith('---\n') && target.indexOf('---\n', 4) > 0;
if (hasTargetFM) {
const targetFrontmatterEnd = target.indexOf('---\n', 4);
let targetFrontmatterRaw = target.substring(4, targetFrontmatterEnd).replace(/\s+$/,''); // keep as-is
const targetContent = target.substring(targetFrontmatterEnd + 3);
// Parse target frontmatter
targetFrontmatterObj = yaml.load(targetFrontmatter) || {};
const targetFrontmatterObj: FrontMatterCache = yaml.load(targetFrontmatterRaw) || {};
// 1. Merge array keys present in both (target has precedence for ordering)
const mergeArrayKeys = Object.keys(templateFrontmatterObj)
.filter(k => Array.isArray(templateFrontmatterObj[k]) && Array.isArray(targetFrontmatterObj[k]));
if (mergeArrayKeys.length) {
for (const k of mergeArrayKeys) {
const tArr = targetFrontmatterObj[k] as any[];
const tplArr = templateFrontmatterObj[k] as any[];
const merged = [...tArr, ...tplArr.filter(v => !tArr.includes(v))];
// Produce YAML for just this key
const mergedYaml = yaml.dump({ [k]: merged }).trimEnd();
targetFrontmatterRaw = replaceYamlKeyBlock(targetFrontmatterRaw, k, mergedYaml) ?? targetFrontmatterRaw;
}
}
// 2. Append only missing keys (not present in target)
const newKeys: Record<string, any> = {};
for (const k of Object.keys(templateFrontmatterObj)) {
if (!(k in targetFrontmatterObj)) {
newKeys[k] = templateFrontmatterObj[k];
}
}
const appended = Object.keys(newKeys).length
? targetFrontmatterRaw + '\n' + yaml.dump(newKeys).trimEnd()
: targetFrontmatterRaw;
return `---\n${appended}\n---\n${targetContent}\n\n${templateContent.trim()}\n`;
} else {
// If target doesn't have frontmatter, consider the entire content as target content
targetContent = target.trim();
// No frontmatter in target: use template FM + target content + template content
const targetContent = target.trim();
const templateFMYaml = yaml.dump(templateFrontmatterObj).trimEnd();
return `---\n${templateFMYaml}\n---\n${targetContent}\n\n${templateContent.trim()}\n`;
}
};
// Merge frontmatter with target values taking precedence
const mergedFrontmatter: FrontMatterCache = { ...templateFrontmatterObj };
// Merge arrays by combining and removing duplicates
for (const key in targetFrontmatterObj) {
if (Array.isArray(targetFrontmatterObj[key]) && Array.isArray(mergedFrontmatter[key])) {
const combinedArray = [...new Set([...mergedFrontmatter[key], ...targetFrontmatterObj[key]])];
mergedFrontmatter[key] = combinedArray;
} else {
mergedFrontmatter[key] = targetFrontmatterObj[key];
// Helper: replace a top-level YAML key block (line-based, avoids partial matches causing duplicates)
function replaceYamlKeyBlock(src: string, key: string, newBlock: string): string | null {
const lines = src.split(/\r?\n/);
let start = -1;
for (let i = 0; i < lines.length; i++) {
if (new RegExp(`^${escapeRegex(key)}\\s*:`).test(lines[i])) {
start = i;
break;
}
}
if (start === -1) return null;
// Convert merged frontmatter back to YAML
const mergedFrontmatterYaml = yaml.dump(mergedFrontmatter);
let end = start + 1;
while (end < lines.length) {
const line = lines[end];
if (line.trim() === "") { // blank line ends block (retain blank after replacement)
break;
}
if (/^[^\s].*?:/.test(line)) { // next top-level key
break;
}
if (!/^\s/.test(line)) { // safety: non-indented (shouldn't happen)
break;
}
end++;
}
// Concatenate frontmatter and content
const mergedMarkdown = `---\n${mergedFrontmatterYaml}---\n${targetContent}\n\n${templateContent.trim()}\n`;
const before = lines.slice(0, start);
const after = lines.slice(end);
const replaced = [...before, newBlock, ...after].join('\n');
return mergedMarkdown;
};
return replaced;
}
function escapeRegex(s: string) {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
export const editorInsertText = (editor: Editor, text: string)=> {
const cursor = editor.getCursor();
@@ -424,4 +463,53 @@ export function isUnwantedLeaf(leaf:WorkspaceLeaf):boolean {
leaf.view?.getViewType() === "empty" && leaf.parent && !leaf.parent.parent &&
//@ts-ignore
leaf.parent.type === "split" && leaf.parent.children.length === 1
}
/**
* Gets the height of an audio element in Obsidian's CSS environment
* @returns The height of the audio element in pixels
*/
export function getAudioElementHeight(): number {
// Create a temporary audio element with controls
const audioElement = document.createElement("audio");
audioElement.controls = true;
audioElement.src = "data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"; // Minimal valid audio
// Create a wrapper to avoid affecting page layout
const wrapper = document.createElement("div");
wrapper.style.position = "absolute";
wrapper.style.left = "-9999px";
wrapper.style.visibility = "hidden";
wrapper.style.pointerEvents = "none";
wrapper.appendChild(audioElement);
// Add to document to allow CSS to be applied
document.body.appendChild(wrapper);
// Get height
let height = 0;
try {
// Force layout calculation
document.body.offsetHeight;
// Get height from bounding rect
const rect = audioElement.getBoundingClientRect();
height = rect.height;
// Fallback to computed style if bounding rect returns 0
if (height === 0) {
const computedStyle = window.getComputedStyle(audioElement);
height = parseFloat(computedStyle.height) || 0;
// If still 0, try measuring the wrapper
if (height === 0) {
height = wrapper.getBoundingClientRect().height;
}
}
} finally {
// Clean up
document.body.removeChild(wrapper);
}
return Math.round(height);
}
+298
View File
@@ -0,0 +1,298 @@
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
import { Notice } from "obsidian";
import { DEVICE } from "src/constants/constants";
import { getEA } from "src/core";
import { t } from "src/lang/helpers";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import ExcalidrawView from "src/view/ExcalidrawView";
export interface ScreenshotOptions {
zoom: number;
margin: number;
selectedOnly: boolean;
theme: string;
}
export async function captureScreenshot(view: ExcalidrawView, options: ScreenshotOptions): Promise<Blob | null> {
if (!DEVICE.isDesktop) {
new Notice(t("SCREENSHOT_DESKTOP_ONLY"));
return null;
}
const wasFullscreen = view.isFullscreen();
if (!wasFullscreen) {
view.gotoFullscreen();
}
const api = view.excalidrawAPI as ExcalidrawImperativeAPI;
api.setForceRenderAllEmbeddables(true);
options.selectedOnly = options.selectedOnly && (view.getViewSelectedElements().length > 0);
const remote = window.require("electron").remote;
const elementsToInclude = options.selectedOnly
? view.getViewSelectedElements()
: view.getViewElements();
const includedElementIDs = new Set(elementsToInclude.map(el => el.id));
const savedOpacity: { id: string; opacity: number }[] = [];
const ea = getEA(view) as ExcalidrawAutomate;
// Save the current browser zoom level
const webContents = remote.getCurrentWebContents();
const originalZoomFactor = webContents.getZoomFactor();
// Set browser zoom to 100%
webContents.setZoomFactor(1.0);
await sleep(100); // Give the browser time to apply zoom
const devicePixelRatio = window.devicePixelRatio || 1;
if (options.selectedOnly) {
ea.copyViewElementsToEAforEditing(view.getViewElements().filter(el=>!includedElementIDs.has(el.id)));
ea.getElements().forEach(el => {
savedOpacity.push({
id: el.id,
opacity: el.opacity
});
el.opacity = 0;
});
if (savedOpacity.length > 0) {
await ea.addElementsToView(false, false, false, false);
}
}
let boundingBox = ea.getBoundingBox(elementsToInclude);
boundingBox = {
topX: Math.ceil(boundingBox.topX),
topY: Math.ceil(boundingBox.topY),
width: Math.ceil(boundingBox.width),
height: Math.ceil(boundingBox.height)
}
const margin = options.margin;
const availableWidth = Math.floor(api.getAppState().width);
const availableHeight = Math.floor(api.getAppState().height);
// Apply zoom to the total dimensions
const totalWidth = Math.ceil(boundingBox.width * options.zoom + margin * 2);
const totalHeight = Math.ceil(boundingBox.height * options.zoom + margin * 2);
// Calculate number of tiles
const cols = Math.ceil(totalWidth / availableWidth);
const rows = Math.ceil(totalHeight / availableHeight);
// Use exact tile sizes to avoid rounding issues
const tileWidth = Math.ceil(totalWidth / cols);
const tileHeight = Math.ceil(totalHeight / rows);
// Adjust totalWidth and totalHeight to be multiples of tileWidth and tileHeight
const adjustedTotalWidth = tileWidth * cols;
const adjustedTotalHeight = tileHeight * rows;
// Save and set state
const saveState = () => {
const {
scrollX,
scrollY,
zoom,
viewModeEnabled,
linkOpacity,
theme,
} = api.getAppState();
return {
scrollX,
scrollY,
zoom,
viewModeEnabled,
linkOpacity,
theme,
};
}
const restoreState = (st: any) => {
view.updateScene({
appState: {
...st
}
});
}
const savedState = saveState();
// Switch to view mode for layerUIWrapper to be rendered so it can be hidden
view.updateScene({
appState: {
viewModeEnabled: true,
linkOpacity: 0,
theme: options.theme,
},
});
await sleep(50);
// Hide UI elements (must be after changing to view mode)
const container = view.excalidrawWrapperRef.current;
let layerUIWrapperOriginalDisplay = "block";
let appBottonBarOriginalDisplay = "block";
let layerUIWrapper: HTMLElement | null = null;
let appBottomBar: HTMLElement | null = null;
const originalStyle = {
width: container.style.width,
height: container.style.height,
left: container.style.left,
top: container.style.top,
position: container.style.position,
overflow: container.style.overflow,
};
try {
container.style.width = tileWidth + "px";
container.style.height = tileHeight + "px";
container.style.overflow = "visible";
// Set canvas size and zoom value for capture
view.updateScene({
appState: {
zoom: {
value: options.zoom
},
width: tileWidth,
height: tileHeight
},
});
await sleep(200); // wait for frame to render
// Prepare to collect tile images as data URLs
const { left,top } = container.getBoundingClientRect();
//const { offsetLeft, offsetTop } = api.getAppState();
const tiles = [];
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
// Calculate scroll position for this tile (adjusted for zoom)
const scrollX = boundingBox.topX - margin / options.zoom + (col * tileWidth) / options.zoom;
const scrollY = boundingBox.topY - margin / options.zoom + (row * tileHeight) / options.zoom;
view.updateScene({
appState: {
scrollX: -scrollX,
scrollY: -scrollY,
zoom: {
value: options.zoom
},
width: tileWidth,
height: tileHeight
},
});
await sleep(50);
//set tileWidth/tileHeight will reset the button bar
layerUIWrapper = container.querySelector(".layer-ui__wrapper");
appBottomBar = container.querySelector(".App-bottom-bar");
if (layerUIWrapper) {
layerUIWrapperOriginalDisplay = layerUIWrapper.style.display;
layerUIWrapper.style.display = "none";
}
if (appBottomBar) {
appBottonBarOriginalDisplay = appBottomBar.style.display;
appBottomBar.style.display = "none";
}
await sleep(50);
// Calculate the exact width/height for this tile
const captureWidth = col === cols - 1 ? adjustedTotalWidth - tileWidth * (cols - 1) : tileWidth;
const captureHeight = row === rows - 1 ? adjustedTotalHeight - tileHeight * (rows - 1) : tileHeight;
const image = await remote.getCurrentWebContents().capturePage({
x: left, //offsetLeft,
y: top, //offsetTop,
width: captureWidth * devicePixelRatio,
height: captureHeight * devicePixelRatio,
});
tiles.push({
url: "data:image/png;base64," + image.toPNG().toString("base64"),
width: captureWidth,
height: captureHeight,
col: col,
row: row
});
}
}
// Restore original styles
Object.assign(container.style, originalStyle);
// Stitch tiles together using a browser canvas
const canvas = document.createElement("canvas");
canvas.width = adjustedTotalWidth * devicePixelRatio;
canvas.height = adjustedTotalHeight * devicePixelRatio;
canvas.style.width = `${adjustedTotalWidth}px`;
canvas.style.height = `${adjustedTotalHeight}px`;
const ctx = canvas.getContext("2d");
ctx.scale(1, 1);
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
let y = 0;
for (let row = 0; row < rows; row++) {
let x = 0;
for (let col = 0; col < cols; col++) {
const tile = tiles[row * cols + col];
const img = new window.Image();
img.src = tile.url;
await new Promise(res => {
img.onload = res;
});
ctx.drawImage(img, x, y);
x += tile.width * devicePixelRatio;
}
y += tiles[row * cols].height * devicePixelRatio; // Use the height of the first tile in the row
}
// Return the blob for the caller to handle
return new Promise<Blob>((resolve) => {
canvas.toBlob((blob) => {
resolve(blob);
}, "image/png");
});
} catch (e) {
console.error(e);
new Notice(t("SCREENSHOT_ERROR"));
return null;
} finally {
// Restore opacity for selected elements if necessary
if (options.selectedOnly && savedOpacity.length > 0) {
ea.clear();
ea.copyViewElementsToEAforEditing(view.getViewElements().filter(el => !includedElementIDs.has(el.id)));
savedOpacity.forEach(x => {
ea.getElement(x.id).opacity = x.opacity;
});
await ea.addElementsToView(false, false, false, false);
}
// Restore browser zoom to its original value
webContents.setZoomFactor(originalZoomFactor);
// Restore UI elements
if (layerUIWrapper) {
layerUIWrapper.style.display = layerUIWrapperOriginalDisplay;
}
if (appBottomBar) {
appBottomBar.style.display = appBottonBarOriginalDisplay;
}
// Restore original state
restoreState(savedState);
if(!wasFullscreen) {
view.exitFullscreen();
}
}
}
+113 -6
View File
@@ -16,14 +16,15 @@ import {
getCommonBoundingBox,
DEVICE,
getContainerElement,
SCRIPT_INSTALL_FOLDER,
} from "../constants/constants";
import ExcalidrawPlugin from "../core/main";
import { ExcalidrawElement, ExcalidrawImageElement, ExcalidrawTextElement, ImageCrop } from "@zsviczian/excalidraw/types/excalidraw/element/types";
import { ExcalidrawElement, ExcalidrawImageElement, ExcalidrawTextElement, ImageCrop } from "@zsviczian/excalidraw/types/element/src/types";
import { ExportSettings } from "../view/ExcalidrawView";
import { getDataURLFromURL, getIMGFilename, getMimeType, getURLImageExtension } from "./fileUtils";
import { generateEmbeddableLink } from "./customEmbeddableUtils";
import { FILENAMEPARTS } from "../types/utilTypes";
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { cleanBlockRef, cleanSectionHeading, getFileCSSClasses } from "./obsidianUtils";
import { updateElementLinksToObsidianLinks } from "./excalidrawAutomateUtils";
import { CropImage } from "../shared/CropImage";
@@ -32,7 +33,8 @@ import { runCompressionWorker } from "src/shared/Workers/compression-worker";
import Pool from "es6-promise-pool";
import { FileData } from "../shared/EmbeddedFileLoader";
import { t } from "src/lang/helpers";
import ExcalidrawScene from "src/shared/svgToExcalidraw/elements/ExcalidrawScene";
import { log } from "./debugHelper";
import { VersionMismatchPrompt } from "src/shared/Dialogs/VersionMismatch";
declare const PLUGIN_VERSION:string;
declare var LZString: any;
@@ -45,10 +47,25 @@ declare module "obsidian" {
): WorkspaceLeaf;
}
interface Vault {
getConfig(option: "attachmentFolderPath"): string;
getAvailablePathForAttachments(filename: string, extension: string, file: TFile | null): Promise<string>
}
}
let versionMismatchChecked = false;
export async function checkVersionMismatch(plugin: ExcalidrawPlugin) {
if (!versionMismatchChecked && plugin.manifest.version !== PLUGIN_VERSION) {
versionMismatchChecked = true;
const versionMismatchPrompt = new VersionMismatchPrompt(plugin);
const result = await versionMismatchPrompt.start();
if(result) {
plugin.manifest.version = PLUGIN_VERSION;
await plugin.app.setting.open();
plugin.app.setting.openTabById("community-plugins");
}
}
};
export let versionUpdateCheckTimer: number = null;
let versionUpdateChecked = false;
export async function checkExcalidrawVersion() {
@@ -82,8 +99,11 @@ export async function checkExcalidrawVersion() {
t("UPDATE_AVAILABLE") + ` ${latestVersion}`,
);
}
// Check for script updates
await checkScriptUpdates();
} catch (e) {
errorlog({ where: "Utils/checkExcalidrawVersion", error: e });
console.log({ where: "Utils/checkExcalidrawVersion", error: e });
}
versionUpdateCheckTimer = window.setTimeout(() => {
versionUpdateChecked = false;
@@ -91,6 +111,56 @@ export async function checkExcalidrawVersion() {
}, 28800000); //reset after 8 hours
};
async function checkScriptUpdates() {
try {
if (!EXCALIDRAW_PLUGIN?.settings?.scriptFolderPath) {
return;
}
const folder = `${EXCALIDRAW_PLUGIN.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}/`;
const installedScripts = EXCALIDRAW_PLUGIN.app.vault.getFiles()
.filter(f => f.path.startsWith(folder) && f.extension === "md");
if (installedScripts.length === 0) {
return;
}
// Get directory info from GitHub
const files = new Map<string, number>();
const directoryInfo = JSON.parse(
await request({
url: "https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/directory-info.json",
}),
);
directoryInfo.forEach((f: any) => files.set(f.fname, f.mtime));
if (files.size === 0) {
return;
}
// Check if any installed scripts have updates
const updates:string[] = [];
let hasUpdates = false;
for (const scriptFile of installedScripts) {
const filename = scriptFile.name;
if (files.has(filename)) {
const mtime = files.get(filename);
if (mtime > scriptFile.stat.mtime) {
updates.push(scriptFile.path.split(folder)?.[1]?.split(".md")[0]);
hasUpdates = true;
}
}
}
if (hasUpdates) {
const message = `${t("SCRIPT_UPDATES_AVAILABLE")}\n\n${updates.sort().join("\n")}`;
new Notice(message,8000+updates.length*1000);
log(message);
}
} catch (e) {
console.log({ where: "Utils/checkScriptUpdates", error: e });
}
}
const random = new Random(Date.now());
export function randomInteger () {
@@ -570,6 +640,8 @@ export function getLinkParts (fname: string, file?: TFile): LinkParts {
const REG = /(^[^#\|]*)#?(\^)?([^\|]*)?\|?(\d*)x?(\d*)/;
const parts = fname.match(REG);
const isBlockRef = parts[2] === "^";
let page = parseInt(parts[3]?.match(/page=(\d*)/)?.[1]);
page = isNaN(page) ? null : page;
return {
original: fname,
path: file && (parts[1] === "") ? file.path : parts[1],
@@ -579,7 +651,7 @@ export function getLinkParts (fname: string, file?: TFile): LinkParts {
: isBlockRef ? cleanBlockRef(parts[3]) : cleanSectionHeading(parts[3]),
width: parts[4] ? parseInt(parts[4]) : undefined,
height: parts[5] ? parseInt(parts[5]) : undefined,
page: parseInt(parts[3]?.match(/page=(\d*)/)?.[1])
page,
};
};
@@ -911,6 +983,41 @@ export function hyperlinkIsImage (data: string):boolean {
return IMAGE_TYPES.contains(corelink.substring(corelink.lastIndexOf(".")+1));
}
export function getFilePathFromObsidianURL (data: string): string {
if(!data) return null;
if(!data.startsWith("obsidian://")) return null;
try {
const url = new URL(data);
const fileParam = url.searchParams.get("file");
if(!fileParam) return null;
return decodeURIComponent(fileParam);
} catch {
return null;
}
}
export function obsidianURLIsImage (data: string):boolean {
if(!data) return false;
if(!data.startsWith("obsidian://")) return false;
try {
const url = new URL(data);
const fileParam = url.searchParams.get("file");
if(!fileParam) return false;
const decodedFile = decodeURIComponent(fileParam);
const lastDotIndex = decodedFile.lastIndexOf(".");
if(lastDotIndex === -1) return false;
const extension = decodedFile.substring(lastDotIndex + 1);
return IMAGE_TYPES.contains(extension);
} catch {
return false;
}
}
export function hyperlinkIsYouTubeLink (link:string): boolean {
return isHyperLink(link) &&
(link.startsWith("https://youtu.be") || link.startsWith("https://www.youtube.com") || link.startsWith("https://youtube.com") || link.startsWith("https//www.youtu.be")) &&
Loaded 100 of 107 files, more files were not shown because too many files have changed in this diff. Show more