Compare commits

...
Author SHA1 Message Date
zsviczian a043ee131f updated training files 2025-10-24 13:44:59 +02:00
zsviczian 7e9f1f6350 Auto generate training file 2025-10-24 13:14:07 +02:00
zsviczian ffc209d4b0 carved out types 2025-10-24 12:31:28 +02:00
zsviczian c1ea206d9d updated invert colors script 2025-10-23 16:44:26 +02:00
zsviczian 4587d36997 2.17.0-beta-1; 0.18.0-42 2025-10-23 07:53:39 +02:00
zsviczian 4f4035b8ef Merge pull request #2519 from rlan/feat/zh-tw/27d30c6
Update zh-tw.ts to 27d30c6
2025-10-23 07:45:57 +02:00
Rick Lan de5da38474 Update zh-tw.ts to 27d30c6 2025-10-22 22:23:46 -07:00
zsviczian 27d30c609e fix #2514
Updated documentation link for support requests.
2025-10-22 12:46:54 +02:00
zsviczian 9aaaf77daf updated slideshow script to support marker frames during printout 2025-10-17 09:07:50 +02:00
zsviczian ba0fac6f74 Palette loader date issues 2025-10-15 07:48:14 +02:00
zsviczian 802e0f2dcd Update directory-info.json with new file metadata
Updated the directory-info.json file to reflect changes in file metadata.
2025-10-09 16:10:09 +02:00
zsviczian 7bcb14b72f Merge pull request #2506 from Joakim31/master
Update es.ts to 8b198a57
2025-10-09 15:19:19 +02:00
Joakim31 21ddc4b90f Update es.ts to 8b198a57 2025-10-07 22:33:42 -05:00
zsviczian 8035e489ca 2.16.1 removing iframes 2025-10-04 22:37:01 +02:00
zsviczian bf8ae6f8bb updated script files 2025-10-04 22:03:11 +02:00
zsviczian 8b557a8461 remove iframes from index-new 2025-10-04 21:50:20 +02:00
zsviczian 35bc375356 2.16.0, 0.18.0-41 2025-10-04 16:42:15 +02:00
zsviczian 09890d8890 Merge pull request #2501 from playermiller109/2025-10-03
Update zh-cn.ts to 3e55719
2025-10-03 20:02:07 +02:00
zsviczian 5d8370234c Merge pull request #2502 from spinualexandru/chore/outdated-gallery-link
chore: Fix the outdated link to the catalogue
2025-10-03 20:01:54 +02:00
Alex Spinu e11664c826 chore: fix outdated catalogue link 2025-10-03 11:41:40 +03:00
Alex Spinu fc33805fbe chore: fix outdated catalogue link 2025-10-03 11:34:36 +03:00
playermiller109 21f202a725 Update zh-cn.ts to 3e55719 2025-10-03 15:42:38 +08:00
zsviczian 3e55719035 2.16.0-beta-2, 0.18.0-40 2025-10-02 23:14:19 +02:00
zsviczian c5ca730946 2.16.0-beta-1, 0.18.0-39 2025-09-30 19:09:07 +02:00
zsviczian 537b01f461 Merge pull request #2483 from rlan/feat/zh-tw/b976a5d
Update zh-tw.ts to b976a5d. Ran zh-cn.ts through OpenCC.
2025-09-21 12:09:28 +02:00
Rick Lan 428f2c50b6 Update zh-tw.ts to b976a5d. Ran zh-cn.ts through OpenCC. 2025-09-14 09:46:01 -07:00
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
90 changed files with 51665 additions and 2534 deletions

No files matched your search

+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://excalidraw-obsidian.online/wiki/welcome)** – 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)** Here's the [direct link to a preloaded NotebookLM](https://notebooklm.google.com/notebook/42d76a2f-c11d-4002-9286-1683c43d0ab0)
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.
+3
View File
@@ -21,3 +21,6 @@ yarn.lock
.DS_Store
.lock
.lock
# Obsidian files
Obsidian
+6 -3
View File
@@ -6,13 +6,15 @@
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>
<a href="https://youtu.be/QKnQgSjJVuc" target="_blank"><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/thumbnail-getting-started.jpg" width="300"/></a>
### Here's my complete catalog of videos:
<a href="https://excalidraw-obsidian.online/Hobbies/Excalidraw+Blog/Catalogue+of+Videos"><img width="380" alt="image" src="https://github.com/zsviczian/obsidian-excalidraw-plugin/assets/14358394/2577e5ad-7a21-4c62-acd5-4fe80c8a8a95"></a>
<a href="https://excalidraw-obsidian.online/wiki/catalogue"><img width="380" alt="image" src="https://github.com/zsviczian/obsidian-excalidraw-plugin/assets/14358394/2577e5ad-7a21-4c62-acd5-4fe80c8a8a95"></a>
<br>
<details><summary>10 Part (slightly outdated) Video Walkthrough</summary>
@@ -225,7 +227,7 @@ For more details, see this [video](https://youtu.be/yZQoJg2RCKI)
- `excalidraw-link-brackets: true|false` whether or not to display brackets around links in preview
- `excalidraw-default-mode: view|zen` Open this document in view mode or zen mode by defult. The default view mode is excellent for presentation slides.
- Frontmatter tags to customize image export at a file level [519](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/519). If these keys are present, they will override the default Excalidraw embed and export settings.
- `excalidraw-export-transparent: true`:  true == Transparent / false == with background.
- `excalidraw-export-transparent: true`: true == Transparent / false == with background.
- `excalidraw-export-dark`: true == Dark mode / false == light mode.
- `excalidraw-export-padding`: Specify the export padding for the image.
- `excalidraw-export-pngscale`: This only affects export to PNG. Specify the export scale for the image. The typical range is between 0.5 and 5, but you can experiment with other values as well.
@@ -243,7 +245,7 @@ Drag the desired file from the Obsidian file explorer and hold down <kbd>SHIFT</
- Open Obsidian Developer Console (<kbd>CTRL+Shift+i</kbd>/<kbd>CMD+OPT+i</kbd>) and
- Execute the following command: `ExcalidrawAutomate.mostRecentMarkdownSVG`
- You can control the appearance of the embedded markdown file on a file by file
  bases by adding the following front matter keys to your markdown document:
bases by adding the following front matter keys to your markdown document:
- `excalidraw-font: Virgil|Cascadia|font_file_name.extension`
- `excalidraw-font-color: css-color-name|#HEXcolor|any-other-html-standard-format`,
- You can find css color names [here](https://www.w3schools.com/colors/colors_names.asp).
@@ -306,3 +308,4 @@ You can find me on Twitter [@zsviczian](https://twitter.com/zsviczian), and on m
If you enjoy Excalidraw, consider giving [ExcaliBrain](https://github.com/zsviczian/excalibrain) a try (also available via Obsidian Community Plugins).
<a href="https://youtu.be/gOkniMkDPyM" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/169708346-9e41289d-9536-43ec-8f70-2d2ad2d369d6.png" width="300"/></a>
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,727 @@
/*
#exclude
```js*/
// -----------------------------
// -----------------------------
// Icon Library / Bases Search
// -----------------------------
// -----------------------------
const IMAGE_LIBRARY_FOLDER = ea.obsidian.normalizePath("Assets/nosync");
const IMAGE_LIBRARY_FILENAME = "Image Library.base"
const ICONTYPES = [
{name: "Icon", pattern: "icon"},
{name: "Stickfigure", pattern: "stickfigure"},
{name: "Logo", pattern: "logo"}
];
const IMAGE_LIBRARY_PATH = ea.obsidian.normalizePath(IMAGE_LIBRARY_FOLDER + "/" + IMAGE_LIBRARY_FILENAME);
async function initializeImageLibrary() {
await ea.checkAndCreateFolder(IMAGE_LIBRARY_FOLDER);
const syncPlugin = app.internalPlugins.plugins["sync"]?.instance;
if(syncPlugin && !syncPlugin.ignoreFolders.includes(IMAGE_LIBRARY_FOLDER)) {
syncPlugin.setIgnoreFolders(syncPlugin.ignoreFolders.concat(IMAGE_LIBRARY_FOLDER));
}
const imgLibFile = app.vault.getFileByPath(IMAGE_LIBRARY_PATH);
if(!imgLibFile) {
//The bases file is very sensitive to spaces, indents, and formatting
//take care when modifying this
const baseTemplate = `formulas:\n` +
` Icon: image(file.path)\n` +
` keywords: file.name.split(" - ")[1]\n` +
` icon-path: link(if(file.ext == "md", "Assets/" + file.name.split(" - ")[0] + "s/" + file.name + ".svg", file.path))\n` +
`views:\n` +
` - type: cards\n` +
` name: View\n` +
` filters:\n` +
` and:\n` +
` - /^(icon|stickfigure|logo) \\- /i.matches(file.name.lower())\n` +
` - '!file.path.startsWith("Assets/")'\n` +
` - /./i.matches(formula.keywords)\n` +
` order:\n` +
` - formula.keywords\n` +
` sort:\n` +
` - property: formula.keywords\n` +
` direction: ASC\n` +
` cardSize: 130\n` +
` imageFit: contain\n` +
` image: formula.icon-path\n` +
` imageAspectRatio: 0.8\n`;
await app.vault.create(IMAGE_LIBRARY_PATH, baseTemplate);
}
}
initializeImageLibrary();
async function revealIconLibrary() {
const file = app.vault.getFileByPath(IMAGE_LIBRARY_PATH);
if(!file) return;
let leaf;
app.workspace.iterateAllLeaves(l=>{
if(leaf) return;
if(l.view?.getViewType() === "bases" && l.view.getState().file === file.path) leaf = l;
});
if(leaf) {
app.workspace.revealLeaf(leaf);
return file;
}
leaf = app.workspace.getRightLeaf();
await leaf.openFile(file);
app.workspace.revealLeaf(leaf);
return file;
}
if(ea.verifyMinimumPluginVersion("2.13.2")) {
ea.plugin.addCommand({
id: "base-filter-keywords",
name: "Icon Library",
icon: "images",
callback: async () => {
// Check if the active file is a .base file
const file = await revealIconLibrary();
if(!file) return false;
let baseContent = await app.vault.read(file);
// Check if the file has the specific patterns for filtering
if (!baseContent.includes(".matches(formula.keywords)")) return;
// Create a modal using Obsidian's Modal class
const Modal = ea.FloatingModal;
const modal = new Modal(app);
const { contentEl } = modal;
contentEl.createEl("style", {
text: `
input[type="checkbox"]:focus-visible {
outline: 2px solid ${app.getAccentColor()} !important;
outline-offset: 2px !important;
}
`
});
// Set title
contentEl.createEl("h3", {
text: "Icon Library"
});
// ---------------------
// Create keyword filter
// ---------------------
const inputContainer = contentEl.createDiv();
inputContainer.style.margin = "20px 0";
const input = contentEl.createEl("input", {
type: "text",
placeholder: "Enter filter term (leave empty for wildcard, you may use regular expression)",
});
input.style.width = "100%";
input.style.padding = "8px";
// Extract current keyword filter
const keywordFilterRegex = /(- +)\/(.*?)\/i?\.matches\(formula\.keywords\)/;
const keywordMatch = baseContent.match(keywordFilterRegex);
if (keywordMatch && keywordMatch[2] && keywordMatch[2] !== ".") {
input.value = keywordMatch[2];
}
// Set focus on the input
setTimeout(() => input.focus(), 50);
// ------------------
// Create toggle switches for file type filters
// ------------------
const toggleContainer = contentEl.createDiv();
toggleContainer.style.margin = "20px 0";
toggleContainer.style.display = "flex";
toggleContainer.style.gap = "15px";
toggleContainer.style.flexWrap = "wrap";
// Get current filter pattern to determine initial toggle states
const fileNameFilterRegex = /\/\^(.*?) \\- \/i?\.matches\(file\.name\.lower\(\)\)/;
const match = baseContent.match(fileNameFilterRegex);
let currentFilters = [];
if (match && match[1]) {
currentFilters = match[1].replace(/[\(\)]/g, '').split('|');
}
// Create toggle function
const createToggle = (label, value) => {
const toggleWrapper = toggleContainer.createDiv();
toggleWrapper.style.display = "flex";
toggleWrapper.style.alignItems = "center";
const checkbox = toggleWrapper.createEl("input", {
type: "checkbox",
attr: { id: `toggle-${value}` }
});
checkbox.checked = currentFilters.includes(value);
const labelEl = toggleWrapper.createEl("label", {
text: label,
attr: { for: `toggle-${value}` }
});
labelEl.style.marginLeft = "5px";
return checkbox;
};
// Create toggles dynamically based on ICONTYPES array
const typeToggles = {};
ICONTYPES.forEach(iconType => {
typeToggles[iconType.pattern] = createToggle(iconType.name, iconType.pattern);
});
// Function to apply the filter
const applyFilter = async () => {
// Get selected file types
const selectedTypes = [];
ICONTYPES.forEach(iconType => {
if (typeToggles[iconType.pattern].checked) selectedTypes.push(iconType.pattern);
});
// Build file type filter pattern
const fileTypePattern = selectedTypes.length > 0
? `/^(${selectedTypes.join('|')}) \\- /i`
: `/^() \\- /i`; // Empty pattern if none selected
// Get keyword filter
const keywordTerm = input.value.trim() || ".";
// Update both filter patterns in the base file
let updatedContent = baseContent;
// Update file name filter
updatedContent = updatedContent.replace(
/\/\^.*? \\\- \/i?\.matches\(file\.name\.lower\(\)\)/,
`${fileTypePattern}.matches(file.name.lower())`
);
// Update keyword filter
updatedContent = updatedContent.replace(
/(- +)\/.*\/i?\.matches\(formula\.keywords\)/g,
`$1/${keywordTerm}/i.matches(formula.keywords)`
);
// Save the updated file
if (updatedContent !== baseContent) {
await app.vault.modify(file, updatedContent);
baseContent = updatedContent; // Update base content to prevent duplicate updates
}
};
// -------------------
// Add event listeners for input changes to apply filter immediately
// -------------------
contentEl.querySelectorAll("input").forEach(el => {
el.addEventListener("input", applyFilter);
});
// Handle Enter key in the input field
contentEl.querySelectorAll("input").forEach(el => {
el.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
modal.close();
}
});
});
modal.open();
},
});
} else {
new Notice("Icon Library not initialized. Please update to the latest Excalidraw Plugin version", 0);
}
// -----------------
// -----------------
// Throttle Sync
// -----------------
// -----------------
const sync = app.internalPlugins.plugins["sync"]?.instance
function throttleSync() {
function setPause(newState) {
if (newState && sync.getStatus() !== "synced") {
setTimeout(() => setPause(true), 10000) //20 seconds
return;
}
sync.setPause(newState);
//console.log(`${moment().format("HH:mm:ss")} - ${sync.getStatus()}`);
if (newState) {
//unpause after 2 minutes
setTimeout(() => setPause(false), 120000) //2 minutes
} else {
//pause after 20 seconds of sync
setTimeout(() => setPause(true), 20000) //20 seconds
}
}
if (sync) {
if (ea.DEVICE.isDesktop) {
setPause(false);
console.log("Sync throttle started");
} else {
sync.setPause(false);
}
}
}
if (sync) {
sync.setPause(false);
}
//throttleSync();
// ----------------------
// ----------------------
// Move settings button
// ----------------------
// ----------------------
try {
if (ea.DEVICE.isDesktop) {
const actions = document.querySelector(".workspace-drawer-vault-actions");
actions.style.display = "none";
const setting = actions.children[1];
const header = document.querySelector(".workspace-tab-header-container");
const toggle = document.querySelector(".sidebar-toggle-button.mod-left");
header.appendChild(setting);
if (header === toggle.parentElement) header.insertBefore(setting, toggle);
}
} catch (e) {
console.log("Excalidraw Startup Move Settings Button", e);
}
// --------------
// --------------
// Debug logger
// --------------
// --------------
window.logger = (label, values) => {
if (!window.log) window.log = [];
window.log.push({
label,
timestamp: performance.now(),
stack: new Error().stack,
values,
});
return false;
}
window.printLog = () => {
console.log(window.log.map(l => {
return `${moment(l.timestamp).format("HH:mm:ss.SSS")} ${
l.label}\n${l.stack.split("\n").slice(3).map(x=>x.trim()).join("\n")
}\n------------------------`;
}).join("\n"))
}
if (window.electron) {
const alignElectronSpellcheckWithObsidianSettings = () => {
const session = window.electron.remote.getCurrentWebContents().session;
session.setSpellCheckerEnabled(app.vault.config.spellcheck);
if (app.vault.config.spellcheck) {
session.setSpellCheckerLanguages(navigator.languages);
}
};
const body = document.body;
const observer = new MutationObserver((mutationsList, observer) => {
for (let mutation of mutationsList) {
if (mutation.type === 'childList') {
mutation.removedNodes.forEach(node => {
if (node.classList && node.classList.contains('modal-container')) {
alignElectronSpellcheckWithObsidianSettings();
}
});
}
}
});
const config = {
childList: true
};
observer.observe(body, config);
alignElectronSpellcheckWithObsidianSettings();
}
// ------------------------
// ------------------------
// Excalidraw Event Hooks
// ------------------------
// ------------------------
/**
* If set, this callback is triggered when the user closes an Excalidraw view.
* onViewUnloadHook: (view: ExcalidrawView) => void = null;
*/
//ea.onViewUnloadHook = (view) => {};
/**
* If set, this callback is triggered, when the user changes the view mode.
* You can use this callback in case you want to do something additional when the user switches to view mode and back.
* onViewModeChangeHook: (isViewModeEnabled:boolean, view: ExcalidrawView, ea: ExcalidrawAutomate) => void = null;
*/
//ea.onViewModeChangeHook = (isViewModeEnabled, view, ea) => {};
/**
* If set, this callback is triggered, when the user hovers a link in the scene.
* You can use this callback in case you want to do something additional when the onLinkHover event occurs.
* This callback must return a boolean value.
* In case you want to prevent the excalidraw onLinkHover action you must return false, it will stop the native excalidraw onLinkHover management flow.
* onLinkHoverHook: (
* element: NonDeletedExcalidrawElement,
* linkText: string,
* view: ExcalidrawView,
* ea: ExcalidrawAutomate
* ) => boolean = null;
*/
//ea.onLinkHoverHook = (element, linkText, view, ea) => {};
/**
* If set, this callback is triggered, when the user clicks a link in the scene.
* You can use this callback in case you want to do something additional when the onLinkClick event occurs.
* This callback must return a boolean value.
* In case you want to prevent the excalidraw onLinkClick action you must return false, it will stop the native excalidraw onLinkClick management flow.
* onLinkClickHook:(
* element: ExcalidrawElement,
* linkText: string,
* event: MouseEvent,
* view: ExcalidrawView,
* ea: ExcalidrawAutomate
* ) => boolean = null;
*/
//ea.onLinkClickHook = (element,linkText,event, view, ea) => {};
/**
* If set, this callback is triggered, when Excalidraw receives an onDrop event.
* You can use this callback in case you want to do something additional when the onDrop event occurs.
* This callback must return a boolean value.
* In case you want to prevent the excalidraw onDrop action you must return false, it will stop the native excalidraw onDrop management flow.
* onDropHook: (data: {
* ea: ExcalidrawAutomate;
* event: React.DragEvent<HTMLDivElement>;
* draggable: any; //Obsidian draggable object
* type: "file" | "text" | "unknown";
* payload: {
* files: TFile[]; //TFile[] array of dropped files
* text: string; //string
* };
* excalidrawFile: TFile; //the file receiving the drop event
* view: ExcalidrawView; //the excalidraw view receiving the drop
* pointerPosition: { x: number; y: number }; //the pointer position on canvas at the time of drop
* }) => boolean = null;
*/
ea.onDropHook = (data) => {
const {view,draggable} = data;
if(!draggable) return;
const {file, type} = draggable;
if(!file || type !== "link") return;
const {extension} = file;
if(!(
data.ea.isExcalidrawFile(file) ||
["jpeg", "jpg", "png", "gif", "svg", "webp", "bmp", "ico", "jtif", "tif", "jfif", "avif"].contains(extension)
)) return;
const ea = data.ea.getAPI(view);
const idBefore = new Set(ea.getViewElements().map(el=>el.id));
setTimeout(()=>{
const newElements = ea.getViewElements().filter(el=>!idBefore.has(el.id));
if(newElements.length !== 1 || newElements[0].type !== "image") return;
const f = ea.getViewFileForImageElement(newElements[0]);
if(f !== file) return;
ea.copyViewElementsToEAforEditing(newElements);
ea.getElements().forEach(el=>{
const l = Math.max(el.width, el.height);
el.width = Math.round(el.width * 180/l);
el.height = Math.round(el.height * 180/l);
});
ea.addElementsToView();
},100);
}
/**
* If set, this callback is triggered, when Excalidraw receives an onPaste event.
* You can use this callback in case you want to do something additional when the
* onPaste event occurs.
* This callback must return a boolean value.
* In case you want to prevent the excalidraw onPaste action you must return false,
* it will stop the native excalidraw onPaste management flow.
* onPasteHook: (data: {
* ea: ExcalidrawAutomate;
* payload: ClipboardData;
* event: ClipboardEvent;
* excalidrawFile: TFile; //the file receiving the paste event
* view: ExcalidrawView; //the excalidraw view receiving the paste
* pointerPosition: { x: number; y: number }; //the pointer position on canvas
* }) => boolean = null;
*/
ea.onPasteHook = (data) => {
const {ea,payload} = data;
if (payload?.elements) {
payload.elements.filter(el => el.locked).forEach(el => {
el.locked = false;
});
/* data.payload.elements
.filter(el=>el.type==="text" && !el.hasOwnProperty("rawText"))
.forEach(el=>el.rawText = el.originalText);*/
}
/*
const getFileFromObsidianURL = (data) => {
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;
}
}
if(payload.text) {
link = getFileFromObsidianURL(payload.text);
await ea.addImage(0,0,link);
await ea.addElementsToView(true,true,true);
return false;
}
*/
};
/**
* if set, this callback is triggered, when an Excalidraw file is opened
* You can use this callback in case you want to do something additional when the file is opened.
* This will run before the file level script defined in the `excalidraw-onload-script` frontmatter.
* onFileOpenHook: (data: {
* ea: ExcalidrawAutomate;
* excalidrawFile: TFile; //the file being loaded
* view: ExcalidrawView;
* }) => Promise<void>;
*/
//ea.onFileOpenHook = (data) => {};
/**
* if set, this callback is triggered, when an Excalidraw file is created
* see also: https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1124
* onFileCreateHook: (data: {
* ea: ExcalidrawAutomate;
* excalidrawFile: TFile; //the file being created
* view: ExcalidrawView;
* }) => Promise<void>;
*/
/*ea.onFileCreateHook = (data) => {
app.fileManager.promptForFileRename(data.excalidrawFile);
};*/
/**
* If set, this callback is triggered when a image is being saved in Excalidraw.
* You can use this callback to customize the naming and path of pasted images to avoid
* default names like "Pasted image 123147170.png" being saved in the attachments folder,
* and instead use more meaningful names based on the Excalidraw file or other criteria,
* plus save the image in a different folder.
*
* If the function returns null or undefined, the normal Excalidraw operation will continue
* with the excalidraw generated name and default path.
* If a filepath is returned, that will be used. Include the full Vault filepath and filename
* with the file extension.
* The currentImageName is the name of the image generated by excalidraw or provided during paste.
*
* @param data - An object containing the following properties:
* @property {string} [currentImageName] - Default name for the image.
* @property {string} drawingFilePath - The file path of the Excalidraw file where the image is being used.
*
* @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: {
* 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) => { 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 {ExcalidrawAutomate} ea - The ExcalidrawAutomate instance associated with the hook.
* @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.
*
* 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
* onCanvasColorChangeHook: (
* ea: ExcalidrawAutomate,
* view: ExcalidrawView, //the excalidraw view
* color: string,
* ) => void = null;
*/
//ea.onCanvasColorChangeHook = (ea, view, color) => {};
/**
* If set, this callback is triggered whenever a drawing is exported to SVG.
* The string returned will replace the link in the exported SVG.
* The hook is only executed if the link is to a file internal to Obsidian
* see: https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1605
* onUpdateElementLinkForExportHook: (data: {
* originalLink: string,
* obsidianLink: string,
* linkedFile: TFile | null,
* hostFile: TFile,
* }) => string = null;
*/
//ea.onUpdateElementLinkForExportHook = (data) => {
// const decodedObsidianURI = decodeURIComponent(data.obsidianLink);
//};
+3 -2
View File
@@ -7,7 +7,8 @@ If you are enjoying the Excalidraw plugin then please support my work and enthus
Jump ahead to the [[#List of available scripts]]
# Introducing Excalidraw Automate Script Engine
<iframe width="560" height="315" src="https://www.youtube.com/embed/hePJcObHIso" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a href="https://www.youtube.com/watch?v=hePJcObHIso" target="_blank"><img src ="https://i.ytimg.com/vi/hePJcObHIso/maxresdefault.jpg" style="width:560px;"></a>
Script Engine scripts are installed in the `Downloaded` subfolder of the `Excalidraw Automate script folder` specified in plugin settings.
@@ -243,7 +244,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/OCR%20-%20Optical%20Character%20Recognition.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/OCR%20-%20Optical%20Character%20Recognition.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">REQUIRES EXCALIDRAW 1.5.15<br>The script will 1) send the selected image file to [taskbone.com](https://taskbone.com) to extract the text from the image, and 2) will add the text to your drawing as a text element.<br><mark>⚠ Note that you will need to manually paste your token into the script after the first run! ⚠</mark><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-ocr.jpg'><br><iframe width="560" height="315" src="https://www.youtube.com/embed/W2NMzR8s4eE" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></td></tr></table>
<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/OCR%20-%20Optical%20Character%20Recognition.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">REQUIRES EXCALIDRAW 1.5.15<br>The script will 1) send the selected image file to [taskbone.com](https://taskbone.com) to extract the text from the image, and 2) will add the text to your drawing as a text element.<br><mark>⚠ Note that you will need to manually paste your token into the script after the first run! ⚠</mark><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-ocr.jpg'><br><a href="https://www.youtube.com/watch?v=W2NMzR8s4eE" target="_blank"><img src ="https://i.ytimg.com/vi/W2NMzR8s4eE/maxresdefault.jpg" style="width:560px;"></a></td></tr></table>
## Organic Line
```excalidraw-script-install
@@ -3,9 +3,9 @@
Select some elements in the scene. The script will take these elements and move them into a new Excalidraw file, and open that file. The selected elements will also be replaced in your original drawing with the embedded Excalidraw file (the one that was just created). You will be prompted for the file name of the new deconstructed image. The script is useful if you want to break a larger drawing into smaller reusable parts that you want to reference in multiple drawings.
<iframe width="560" height="315" src="https://www.youtube.com/embed/HRtaaD34Zzg" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a href="https://www.youtube.com/watch?v=HRtaaD34Zzg" target="_blank"><img src ="https://i.ytimg.com/vi/HRtaaD34Zzg/maxresdefault.jpg" style="width:560px;"></a>
<iframe width="560" height="315" src="https://www.youtube.com/embed/mvMQcz401yo" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a href="https://www.youtube.com/watch?v=mvMQcz401yo" target="_blank"><img src ="https://i.ytimg.com/vi/mvMQcz401yo/maxresdefault.jpg" style="width:560px;"></a>
```javascript
*/
+3 -1
View File
@@ -1,5 +1,7 @@
/*
<iframe width="560" height="315" src="https://www.youtube.com/embed/A1vrSGBbWgo" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a href="https://www.youtube.com/watch?v=A1vrSGBbWgo" target="_blank"><img src ="https://i.ytimg.com/vi/A1vrSGBbWgo/maxresdefault.jpg" style="width:560px;"></a>
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg)
```js*/
+2 -1
View File
@@ -1,5 +1,6 @@
/*
<iframe width="560" height="315" src="https://www.youtube.com/embed/A1vrSGBbWgo" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a href="https://www.youtube.com/watch?v=A1vrSGBbWgo" target="_blank"><img src ="https://i.ytimg.com/vi/A1vrSGBbWgo/maxresdefault.jpg" style="width:560px;"></a>
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg)
```js*/
+1 -2
View File
@@ -6,8 +6,7 @@ The script performs two different functions depending on the elements selected i
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/golden-ratio.jpg)
<iframe width="560" height="315" src="https://www.youtube.com/embed/2SHn_ruax-s" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a href="https://www.youtube.com/watch?v=2SHn_ruax-s" target="_blank"><img src ="https://i.ytimg.com/vi/2SHn_ruax-s/maxresdefault.jpg" style="width:560px;"></a>
Gravitational point of spiral: $$\left[x,y\right]=\left[ x + \frac{{\text{width} \cdot \phi^2}}{{\phi^2 + 1}}\;, \; y + \frac{{\text{height} \cdot \phi^2}}{{\phi^2 + 1}} \right]$$
Dimensions of inner rectangles in case of Double Spiral: $$[width, height] = \left[\frac{width\cdot(\phi^2+1)}{2\phi^2}\;, \;\frac{height\cdot(\phi^2+1)}{2\phi^2}\right]$$
+100 -44
View File
@@ -1,65 +1,121 @@
/*
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-invert-colors.jpg)
The script inverts the colors on the canvas including the color palette in Element Properties.
```javascript
*/
const defaultColorPalette = { // https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.6.8
elementStroke:["#000000","#343a40","#495057","#c92a2a","#a61e4d","#862e9c","#5f3dc4","#364fc7","#1864ab","#0b7285","#087f5b","#2b8a3e","#5c940d","#e67700","#d9480f"],
elementBackground:["transparent","#ced4da","#868e96","#fa5252","#e64980","#be4bdb","#7950f2","#4c6ef5","#228be6","#15aabf","#12b886","#40c057","#82c91e","#fab005","#fd7e14"],
canvasBackground:["#ffffff","#f8f9fa","#f1f3f5","#fff5f5","#fff0f6","#f8f0fc","#f3f0ff","#edf2ff","#e7f5ff","#e3fafc","#e6fcf5","#ebfbee","#f4fce3","#fff9db","#fff4e6"]
This script inverts all the colors in the current Excalidraw drawing. It applies the inversion to:
1. The stroke and background colors of every element on the canvas.
2. The main canvas background color.
3. All colors within the user's custom color palette, handling all possible configurations (simple arrays, nested arrays, and objects).
4. The currently selected stroke and background colors in the UI.
A default color palette is defined to use as a fallback if the current drawing's palette is missing or empty. // This is based on the standard Excalidraw palette from version [1.6.8.](https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.6.8)
You'll find a detailed description of the color palette data structure on the [Excalidraw-Obsidian Wiki](https://excalidraw-obsidian.online/wiki/color-palette)
```js*/
const defaultColorPalette = {
elementStroke: ["#000000", "#343a40", "#495057", "#c92a2a", "#a61e4d", "#862e9c", "#5f3dc4", "#364fc7", "#1864ab", "#0b7285", "#087f5b", "#2b8a3e", "#5c940d", "#e67700", "#d9480f"],
elementBackground: ["transparent", "#ced4da", "#868e96", "#fa5252", "#e64980", "#be4bdb", "#7950f2", "#4c6ef5", "#228be6", "#15aabf", "#12b886", "#40c057", "#82c91e", "#fab005", "#fd7e14"],
canvasBackground: ["#ffffff", "#f8f9fa", "#f1f3f5", "#fff5f5", "#fff0f6", "#f8f0fc", "#f3f0ff", "#edf2ff", "#e7f5ff", "#e3fafc", "#e6fcf5", "#ebfbee", "#f4fce3", "#fff9db", "#fff4e6"]
};
// Get the Excalidraw API and the current application state.
const api = ea.getExcalidrawAPI();
const st = api.getAppState();
// Retrieve the current color palette, falling back to the default if necessary.
let colorPalette = st.colorPalette ?? defaultColorPalette;
if (Object.entries(colorPalette).length === 0) colorPalette = defaultColorPalette;
if(!colorPalette.elementStroke || Object.entries(colorPalette.elementStroke).length === 0) colorPalette.elementStroke = defaultColorPalette.elementStroke;
if(!colorPalette.elementBackground || Object.entries(colorPalette.elementBackground).length === 0) colorPalette.elementBackground = defaultColorPalette.elementBackground;
if(!colorPalette.canvasBackground || Object.entries(colorPalette.canvasBackground).length === 0) colorPalette.canvasBackground = defaultColorPalette.canvasBackground;
if (!colorPalette || Object.keys(colorPalette).length === 0) {
colorPalette = defaultColorPalette;
}
// Ensure each key in the palette has a default value if it's missing.
if (!colorPalette.elementStroke || colorPalette.elementStroke.length === 0) {
colorPalette.elementStroke = defaultColorPalette.elementStroke;
}
if (!colorPalette.elementBackground || colorPalette.elementBackground.length === 0) {
colorPalette.elementBackground = defaultColorPalette.elementBackground;
}
if (!colorPalette.canvasBackground || colorPalette.canvasBackground.length === 0) {
colorPalette.canvasBackground = defaultColorPalette.canvasBackground;
}
/**
* Inverts a single color string by reversing its lightness value.
* This function uses the ColorMaster utility provided by Excalidraw Automate.
* It correctly handles various color formats (HEX, RGB, HSL) and preserves transparency.
* @param {string} color - The color to be inverted (e.g., "#FF0000").
* @returns {string} The inverted color string.
*/
const invertColor = (color) => {
if(color.toLowerCase()==="transparent") return color;
const cm = ea.getCM(color);
const lightness = cm.lightness;
cm.lightnessTo(Math.abs(lightness-100));
switch (cm.format) {
case "hsl": return cm.stringHSL();
case "rgb": return cm.stringRGB();
case "hsv": return cm.stringHSV();
default: return cm.stringHEX({alpha: false});
}
}
function invertColorsRecursively(obj) {
if (typeof obj === 'string') {
return invertColor(obj);
} else if (Array.isArray(obj)) {
return obj.map(item => invertColorsRecursively(item));
} else if (typeof obj === 'object' && obj !== null) {
const result = {};
Object.keys(obj).forEach(key => result[key] = invertColorsRecursively(obj[key]));
return result;
} else {
return obj;
const cm = ea.getCM(color);
const opts = cm.alpha !== 1 ? { alpha: true } : { alpha: false };
const lightness = cm.lightness;
cm.lightnessTo(Math.abs(lightness - 100)); // Invert lightness on a 0-100 scale.
switch (cm.format) {
case "hsl": return cm.stringHSL(opts);
case "rgb": return cm.stringRGB(opts);
case "hsv": return cm.stringHSV(opts);
default: return cm.stringHEX(opts);
}
}
colorPalette = invertColorsRecursively(colorPalette);
};
/**
* Recursively traverses a color palette data structure and inverts every color string found.
* This robustly handles all valid `colorPalette` configurations, including nested arrays
* (`string[][]`), simple arrays (`string[]`), and objects (`topPicks`).
* @param {any} palette - A color string, an array of colors, an array of arrays, or an object palette.
* @returns {any} A new palette structure with all colors inverted.
*/
const invertPaletteStructure = (palette) => {
if (typeof palette === 'string') {
// Base case: If the item is a color string, invert it.
return invertColor(palette);
}
if (Array.isArray(palette)) {
// If it's an array, recursively call this function for each item.
return palette.map(item => invertPaletteStructure(item));
}
if (typeof palette === 'object' && palette !== null) {
// If it's an object, create a new object and recursively process its values.
const newPalette = {};
for (const key in palette) {
if (Object.prototype.hasOwnProperty.call(palette, key)) {
newPalette[key] = invertPaletteStructure(palette[key]);
}
}
return newPalette;
}
// Return any other data types (like numbers or null) unchanged.
return palette;
};
// Generate the new, fully inverted color palette.
const invertedColorPalette = invertPaletteStructure(colorPalette);
// Load all elements from the current view into the Excalidraw Automate workbench for editing.
ea.copyViewElementsToEAforEditing(ea.getViewElements());
ea.getElements().forEach(el=>{
el.strokeColor = invertColor(el.strokeColor);
el.backgroundColor = invertColor(el.backgroundColor);
// Iterate over all elements and invert their stroke and background colors.
ea.getElements().forEach(el => {
if (el.strokeColor) {
el.strokeColor = invertColor(el.strokeColor);
}
if (el.backgroundColor) {
el.backgroundColor = invertColor(el.backgroundColor);
}
});
// Finally, update the Excalidraw scene with the inverted elements and application state.
ea.viewUpdateScene({
appState:{
colorPalette,
viewBackgroundColor: invertColor(st.viewBackgroundColor),
currentItemStrokeColor: invertColor(st.currentItemStrokeColor),
currentItemBackgroundColor: invertColor(st.currentItemBackgroundColor)
appState: {
colorPalette: invertedColorPalette,
viewBackgroundColor: invertColor(st.viewBackgroundColor),
currentItemStrokeColor: invertColor(st.currentItemStrokeColor),
currentItemBackgroundColor: invertColor(st.currentItemBackgroundColor)
},
elements: ea.getElements()
elements: ea.getElements(),
storeAction: "capture" // Ensures the change is saved and added to the undo/redo history.
});
+1 -2
View File
@@ -1,8 +1,7 @@
/*
Copies the text from the selected PDF page on the Excalidraw canvas to the clipboard.
<iframe width="560" height="315" src="https://www.youtube.com/embed/Kwt_8WdOUT4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Link:: https://youtu.be/Kwt_8WdOUT4
<a href="https://www.youtube.com/watch?v=Kwt_8WdOUT4" target="_blank"><img src ="https://i.ytimg.com/vi/Kwt_8WdOUT4/maxresdefault.jpg" style="width:560px;"></a>
```js*/
+2 -5
View File
@@ -1,11 +1,8 @@
/*
<a href="https://www.youtube.com/watch?v=epYNx2FSf2w" target="_blank"><img src ="https://i.ytimg.com/vi/epYNx2FSf2w/maxresdefault.jpg" style="width:560px;"></a>
<iframe width="560" height="315" src="https://www.youtube.com/embed/epYNx2FSf2w" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Link:: https://youtu.be/epYNx2FSf2w
<iframe width="560" height="315" src="https://www.youtube.com/embed/diBT5iaoAYo" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
Link:: https://youtu.be/diBT5iaoAYo
<a href="https://www.youtube.com/watch?v=diBT5iaoAYo" target="_blank"><img src ="https://i.ytimg.com/vi/diBT5iaoAYo/maxresdefault.jpg" style="width:560px;"></a>
Design your palette at http://paletton.com/
Once you are happy with your colors, click Tables/Export in the bottom right of the screen:
+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

+411 -207
View File
@@ -6,13 +6,27 @@ Export Excalidraw to PDF Pages: Define printable page areas using frames, then e
![](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;
}
async function run() {
// Help text for the script
const HELP_TEXT = `
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.
@@ -59,19 +73,30 @@ You can also access script settings at the bottom of Excalidraw Plugin settings.
---
**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();
const {enabled, clip, name, outline} = st.frameRendering;
if(!enabled || clip || !name || !outline) {
let {enabled, clip, name, outline, markerName, markerEnabled} = st.frameRendering;
if(!enabled || !name || !outline || !markerEnabled || !markerName) {
ea.viewUpdateScene({
appState: {
frameRendering: {
enabled: true,
clip: false,
clip: clip,
name: true,
outline: true
outline: true,
markerName: true,
markerEnabled: true
}
}
});
@@ -103,35 +128,74 @@ You can also access script settings at the bottom of Excalidraw Plugin settings.
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[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 };
await ea.setScriptSettings(settings);
settings[PRINT_EMPTY] = { value: false };
settings[PRINT_MARKERS_ONLY] = { value: true };
dirty = true;
}
const getSortedFrames = () => ea.getViewElements()
.filter(el => el.type === "frame")
.sort((a, b) => {
const nameA = a.name || "";
const nameB = b.name || "";
return nameA.localeCompare(nameB);
});
//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;
}
// Find existing page frames and determine next page number
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);
const match = frame.name?.match(/(?:Page\s+)?(\d+)/i);
return match ? parseInt(match[1]) : 0;
})
.filter(num => !isNaN(num));
@@ -150,10 +214,13 @@ const getSortedFrames = () => ea.getViewElements()
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 => el.type === "frame");
let selectedFrame = ea.getViewSelectedElements().find(el => el.type === "frame");
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)) {
@@ -162,14 +229,20 @@ const getSortedFrames = () => ea.getViewElements()
ea.selectElementsInView([selectedFrame]);
} else {
findExistingPages(true);
selectedFrame = ea.getViewSelectedElements().find(el => el.type === "frame");
selectedFrame = ea.getViewSelectedElements().find(el => isEligibleFrame(el));
}
}
const hasSelectedFrame = !!selectedFrame;
const modal = new ea.FloatingModal(ea.plugin.app);
let lockFrame = !!settings[LOCK_FRAME]?.value;
let shouldClose = settings[SHOULD_CLOSE].value;
let shouldZoom = settings[SHOULD_ZOOM].value;
// 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) {
@@ -199,7 +272,7 @@ const getSortedFrames = () => ea.getViewElements()
}
// Format page number with leading zero
const pageName = "Page 01";
const pageName = "01";
// Calculate position to center the frame
const appState = ea.getExcalidrawAPI().getAppState();
@@ -211,19 +284,26 @@ const getSortedFrames = () => ea.getViewElements()
// Add new page frame
const addPage = async (direction, pageSize, orientation) => {
selectedFrame = ea.getViewSelectedElements().find(el => el.type === "frame");
if (!selectedFrame) return;
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
// Get dimensions from selected frame, support optional rotation
const dimensions = {
width: selectedFrame.width,
height: selectedFrame.height
width: rotateOnAdd ? selectedFrame.height : selectedFrame.width,
height: rotateOnAdd ? selectedFrame.width : selectedFrame.height
};
// Format page number with leading zero
const pageName = `Page ${nextPageNumber.toString().padStart(2, '0')}`;
const pageName = `${nextPageNumber.toString().padStart(2, '0')}`;
// Calculate position based on direction and selected frame
let x = 0;
@@ -248,11 +328,16 @@ const getSortedFrames = () => ea.getViewElements()
break;
}
return await addFrameElement(x, y, dimensions.width, dimensions.height, pageName);
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;
}
@@ -273,8 +358,9 @@ const getSortedFrames = () => ea.getViewElements()
return addedFrame;
}
const translateToZero = ({ top, left, bottom, right }, padding=0) => {
const {topX, topY, width, height} = ea.getBoundingBox(ea.getViewElements());
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);
@@ -288,7 +374,9 @@ const getSortedFrames = () => ea.getViewElements()
};
}
// Check if all frames have the same size
// 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;
@@ -301,7 +389,6 @@ const getSortedFrames = () => ea.getViewElements()
);
};
// Print frames to PDF
const printToPDF = async (marginSize) => {
const margin = MARGINS[marginSize] || 0;
@@ -318,12 +405,6 @@ const getSortedFrames = () => ea.getViewElements()
new Notice("No frames found to print");
return;
}
// Check if all frames have the same size
if (!checkFrameSizes(frames)) {
new Notice("Only same sized pages are supported currently", 7000);
return;
}
// Create a notice during processing
const notice = new Notice("Preparing PDF, please wait...", 0);
@@ -331,23 +412,33 @@ const getSortedFrames = () => ea.getViewElements()
// 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 },
//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) {
const { top, left, bottom, right } = translateToZero({
top: frame.y,
left: frame.x,
bottom: frame.y + frame.height,
right: frame.x + frame.width,
});
// 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();
@@ -361,6 +452,14 @@ const getSortedFrames = () => ea.getViewElements()
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;
@@ -370,7 +469,8 @@ const getSortedFrames = () => ea.getViewElements()
SVG: svgPages,
scale: { fitToPage: true },
pageProps: {
dimensions: { width, height },
dimensions: {},
//dimensions: { width, height },
backgroundColor: "#ffffff",
margin: {
left: margin,
@@ -392,11 +492,17 @@ const getSortedFrames = () => ea.getViewElements()
modal.titleEl.setText("Page Management");
modal.titleEl.style.textAlign = "center";
// Handle save settings on modal close
modal.onClose = () => {
modal.onClose = async () => {
delete window.excalidrawPrintableLayoutWizardModal;
if (dirty) {
ea.setScriptSettings(settings);
await ea.setScriptSettings(settings);
}
ea.viewUpdateScene({
appState: {
frameRendering: {enabled, clip, name, outline, markerName, markerEnabled}
}
});
if(shouldRestart) setTimeout(()=>run());
};
// Create modal content
@@ -407,13 +513,12 @@ const getSortedFrames = () => ea.getViewElements()
}
});
// Add help section at the top
// Help section
const helpDiv = container.createDiv({
attr: {
style: "margin-bottom: 10px;"
}
});
helpDiv.createEl("details", {}, (details) => {
details.createEl("summary", {
text: "Help & Information",
@@ -430,128 +535,153 @@ const getSortedFrames = () => ea.getViewElements()
ea.obsidian.MarkdownRenderer.render(ea.plugin.app, HELP_TEXT, div, "", ea.plugin)
});
});
let pageSizeDropdown, orientationDropdown, marginDropdown;
// Settings section - only show for first frame creation
if (!hasFrames) {
const settingsContainer = container.createDiv({
attr: {
style: "display: grid; grid-template-columns: auto 1fr; gap: 10px; align-items: center;"
}
});
// Page size dropdown
settingsContainer.createEl("label", { text: "Page Size:" });
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 dropdown
settingsContainer.createEl("label", { text: "Orientation:" });
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;
}
// Show margin settings only if frames exist
// Tabs (show only when frames exist)
let framesTabEl, printingTabEl, tabsHeaderEl, marginDropdown;
if (hasFrames) {
const marginContainer = container.createDiv({
attr: {
style: "display: grid; grid-template-columns: auto 1fr; gap: 10px; align-items: center;"
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")
});
// Margin dropdown (for printing)
marginContainer.createEl("label", { text: "Print Margin:" });
marginDropdown = marginContainer.createEl("select", {
cls: "dropdown",
attr: { style: "width: 100%;" }
printingTabBtn.addEventListener("click", () => {
window.excalidrawPrintLayoutWizard = "printing";
activate("printing")
});
Object.keys(MARGINS).forEach(margin => {
marginDropdown.createEl("option", { text: margin, value: margin });
});
marginDropdown.value = settings[MARGIN].value;
activate(window.excalidrawPrintLayoutWizard ?? "frames");
} else {
// No frames yet, only frames tab content
framesTabEl = container.createDiv();
}
// Add checkboxes for zoom and modal behavior only when frames exist
const optionsContainer = container.createDiv({
attr: {
style: "margin-top: 10px;"
}
});
new ea.obsidian.Setting(optionsContainer)
.setName("Lock")
.setDesc("Lock the new frame element after it is created.")
.addToggle(toggle => {
toggle.setValue(lockFrame)
.onChange(value => {
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;
settings[LOCK_FRAME].value = value; dirty = true;
}
});
});
});
// Zoom to added frame checkbox
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 => {
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;
settings[SHOULD_ZOOM].value = value; dirty = true;
}
});
});
// Close after adding checkbox
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 => {
});
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;
settings[SHOULD_CLOSE].value = value; dirty = true;
}
});
});
// Buttons section
const buttonContainer = container.createDiv({
attr: {
style: "display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-top: 10px;"
}
});
});
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) {
// First frame creation button (centered)
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: "grid-column: 1 / span 3; height: 40px; background-color: var(--interactive-accent); color: var(--text-on-accent);"
}
attr: { style: "height: 40px; background-color: var(--interactive-accent); color: var(--text-on-accent);" }
});
createFirstBtn.textContent = "Create First Frame";
createFirstBtn.addEventListener("click", async () => {
@@ -559,77 +689,106 @@ const getSortedFrames = () => ea.getViewElements()
shouldClose = true;
await createFirstFrame(pageSizeDropdown.value, orientationDropdown.value);
shouldClose = tmpShouldClose;
if(!shouldClose) run();
});
} else if (hasSelectedFrame) {
// Only show navigation buttons and print when a frame is selected
// Up button (in middle of top row)
const upBtn = buttonContainer.createEl("button", {
cls: "page-btn",
attr: {
style: "grid-column: 2; grid-row: 1; height: 40px;"
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");
});
// Add empty space
buttonContainer.createDiv({
attr: { style: "grid-column: 3; grid-row: 1;" }
});
// Left button
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");
});
// Print button (center)
const printBtn = buttonContainer.createEl("button", {
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; background-color: var(--interactive-accent);"
}
attr: { style: "grid-column: 2; grid-row: 2; height: 40px;" }
});
printBtn.innerHTML = ea.obsidian.getIcon("printer").outerHTML;
printBtn.addEventListener("click", async () => {
await printToPDF(marginDropdown.value);
centerRotateBtn.textContent = "Rotate next page";
centerRotateBtn.addEventListener("click", () => {
rotateOnAdd = !rotateOnAdd;
setRotateBtnActive(rotateOnAdd);
});
// Right button
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");
});
// Down button (in middle of bottom row)
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");
});
// Add empty space
buttonContainer.createDiv({
attr: { style: "grid-column: 1; grid-row: 3;" }
});
downBtn.addEventListener("click", async () => { await addPage("down"); });
buttonContainer.createDiv({ attr: { style: "grid-column: 1; grid-row: 3;" } });
}
// Add CSS
// 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 {
@@ -650,6 +809,51 @@ const getSortedFrames = () => ea.getViewElements()
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));
}
`
});
});
+1 -1
View File
@@ -3,7 +3,7 @@
Scribble Helper can improve handwriting and add links. It lets you create and edit text elements, including wrapped text and sticky notes, by double-tapping on the canvas. When you run the script, it creates an event handler that will activate the editor when you double-tap. If you select a text element on the canvas before running the script, it will open the editor for that element. If you use a pen, you can set it up to only activate Scribble Helper when you double-tap with the pen. The event handler is removed when you run the script a second time or switch to a different tab.
<iframe width="560" height="315" src="https://www.youtube.com/embed/BvYkOaly-QM" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a href="https://www.youtube.com/watch?v=BvYkOaly-QM" target="_blank"><img src ="https://i.ytimg.com/vi/BvYkOaly-QM/maxresdefault.jpg" style="width:560px;"></a>
```javascript
*/
+2 -1
View File
@@ -23,7 +23,8 @@ const HELP_TEXT = `
- 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)
<a href="https://www.youtube.com/watch?v=ISuORbVKyhQ" target="_blank"><img src ="https://i.ytimg.com/vi/ISuORbVKyhQ/maxresdefault.jpg" style="max-width:560px; width:100%"></a>
`;
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.7.2")) {
+20 -1
View File
@@ -48,6 +48,7 @@ const EDIT_ZOOMOUT = 0.7; //70% of original slide zoom, set to a value between 1
const FADE_LEVEL = 0.1; //opacity of the slideshow controls after fade delay (value between 0 and 1)
const PRINT_SLIDE_WIDTH = 1920;
const PRINT_SLIDE_HEIGHT = 1080;
const MAX_ZOOM = 30; //3000%
//using outerHTML because the SVG object returned by Obsidin is in the main workspace window
//but excalidraw might be open in a popout window which has a different document object
const SVG_COG = ea.obsidian.getIcon("lucide-settings").outerHTML;
@@ -278,7 +279,7 @@ const getNavigationRect = ({ x1, y1, x2, y2, printDimensions }) => {
const { width, height } = printDimensions ? printDimensions : excalidrawAPI.getAppState();
const ratioX = width / Math.abs(x1 - x2);
const ratioY = height / Math.abs(y1 - y2);
let ratio = Math.min(Math.max(ratioX, ratioY), 30);
let ratio = Math.min(Math.max(ratioX, ratioY), MAX_ZOOM);
const scaledWidth = Math.abs(x1 - x2) * ratio;
const scaledHeight = Math.abs(y1 - y2) * ratio;
@@ -793,6 +794,22 @@ const translateToZero = ({ top, left, bottom, right }, padding) => {
};
}
const getElementPlaceholdersForMarkerFrames = () => {
const viewMarkerFrames = ea.getViewElements().filter(el=>el.type === "frame" && el.frameRole === "marker");
if(viewMarkerFrames.length === 0) return;
ea.clear();
ea.style.opacity = 0;
ea.style.roughness = 0;
ea.style.fillStyle = "solid";
ea.style.backgroundColor = "black"
ea.style.strokeWidth = 0.01;
for (const frame of viewMarkerFrames) {
ea.addRect(frame.x, frame.y, frame.width, frame.height);
}
return ea.getViewElements().concat(ea.getElements());
}
const printToPDF = async (e) => {
const slideWidth = e.shiftKey ? excalidrawAPI.getAppState().width : PRINT_SLIDE_WIDTH;
const slideHeight = e.shiftKey ? excalidrawAPI.getAppState().height : PRINT_SLIDE_HEIGHT;
@@ -803,6 +820,7 @@ const printToPDF = async (e) => {
const padding = shouldClipFrames ? 0 : Math.round(Math.max(slideWidth,slideHeight)/2)+10;
const st = ea.getExcalidrawAPI().getAppState();
setSingleNotice("Generating image. This can take a longer time depending on the size of the image and speed of your device");
const elementsOverride = getElementPlaceholdersForMarkerFrames();
const svg = await ea.createViewSVG({
withBackground: true,
theme: st.theme,
@@ -811,6 +829,7 @@ const printToPDF = async (e) => {
selectedOnly: false,
skipInliningFonts: false,
embedScene: false,
elementsOverride,
});
const pages = [];
for(i=0;i<slides.length;i++) {
+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":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
[{"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
+53 -13
View File
@@ -7,7 +7,7 @@ If you are enjoying the Excalidraw plugin then please support my work and enthus
Jump ahead to the [[#List of available scripts]]
# Introducing Excalidraw Automate Script Engine
<iframe width="560" height="315" src="https://www.youtube.com/embed/hePJcObHIso" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<a href="https://www.youtube.com/watch?v=hePJcObHIso" target="_blank"><img src ="https://i.ytimg.com/vi/hePJcObHIso/maxresdefault.jpg" style="width:560px;"></a>
Script Engine scripts are installed in the `Downloaded` subfolder of the `Excalidraw Automate script folder` specified in plugin settings.
@@ -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
@@ -124,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]]|
@@ -258,7 +289,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20DrawIO%20file.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Create%20DrawIO%20file.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will prompt you for a filename, then create a new draw.io diagram file and open the file in the <a href='https://github.com/zapthedingbat/drawio-obsidian'>Diagram plugin</a>, in a new tab.<br><iframe width="400" height="225" src="https://www.youtube.com/embed/DJcosmN-q2s" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></td></tr></table>
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Create%20DrawIO%20file.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will prompt you for a filename, then create a new draw.io diagram file and open the file in the <a href='https://github.com/zapthedingbat/drawio-obsidian'>Diagram plugin</a>, in a new tab.<br><a href="https://www.youtube.com/watch?v=DJcosmN-q2s" target="_blank"><img src ="https://i.ytimg.com/vi/DJcosmN-q2s/maxresdefault.jpg" style="width:400px;"></a></td></tr></table>
## Create new markdown file and embed into active drawing
```excalidraw-script-install
@@ -290,7 +321,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.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/Deconstruct%20selected%20elements%20into%20new%20drawing.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Select some elements in the scene. The script will take these elements and move them into a new Excalidraw file, and open that file. The selected elements will also be replaced in your original drawing with the embedded Excalidraw file (the one that was just created). You will be prompted for the file name of the new deconstructed image. The script is useful if you want to break a larger drawing into smaller reusable parts that you want to reference in multiple drawings.<br><iframe width="400" height="225" src="https://www.youtube.com/embed/HRtaaD34Zzg" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-deconstruct.jpg'></td></tr></table>
<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/Deconstruct%20selected%20elements%20into%20new%20drawing.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Select some elements in the scene. The script will take these elements and move them into a new Excalidraw file, and open that file. The selected elements will also be replaced in your original drawing with the embedded Excalidraw file (the one that was just created). You will be prompted for the file name of the new deconstructed image. The script is useful if you want to break a larger drawing into smaller reusable parts that you want to reference in multiple drawings.<br><a href="https://www.youtube.com/watch?v=HRtaaD34Zzg" target="_blank"><img src ="https://i.ytimg.com/vi/HRtaaD34Zzg/maxresdefault.jpg" style="width:400px;"></a><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-deconstruct.jpg'></td></tr></table>
## Elbow connectors
```excalidraw-script-install
@@ -308,7 +339,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Excalidraw%20Collaboration%20Frame.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/1-2-3'>@1-2-3</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Excalidraw%20Collaboration%20Frame.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Creates a new Excalidraw.com collaboration room and places the link to the room on the clipboard.<iframe width="400" height="225" src="https://www.youtube.com/embed/7isRfeAhEH4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></td></tr></table>
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/1-2-3'>@1-2-3</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Excalidraw%20Collaboration%20Frame.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Creates a new Excalidraw.com collaboration room and places the link to the room on the clipboard.<a href="https://www.youtube.com/watch?v=7isRfeAhEH4" target="_blank"><img src ="https://i.ytimg.com/vi/7isRfeAhEH4/maxresdefault.jpg" style="width:400px;"></a></td></tr></table>
## Expand rectangles horizontally keep text centered
```excalidraw-script-install
@@ -376,7 +407,7 @@ 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/Golden%20Ratio.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script performs two different functions depending on the elements selected in the view.<br>
1) In case you select text elements, the script will cycle through a set of font scales. First the 2 larger fonts following the Fibonacci sequence (fontsize * φ; fonsize * φ^2), then the 2 smaller fonts (fontsize / φ; fontsize / φ^2), finally the original size, followed again by the 2 larger fonts. If you wait 2 seconds, the sequence clears and starts from which ever font size you are on. So if you want the 3rd larges font, then toggle twice, wait 2 sec, then toggle again.<br>
2) In case you select a single rectangle, the script will open the "Golden Grid", "Golden Spiral" window, where you can set up the type of grid or spiral you want to insert into the document.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/golden-ratio.jpg'><br><iframe width="400" height="225" src="https://www.youtube.com/embed/2SHn_ruax-s" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></td></tr></table>
2) In case you select a single rectangle, the script will open the "Golden Grid", "Golden Spiral" window, where you can set up the type of grid or spiral you want to insert into the document.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/golden-ratio.jpg'><br><a href="https://www.youtube.com/watch?v=2SHn_ruax-s" target="_blank"><img src ="https://i.ytimg.com/vi/2SHn_ruax-s/maxresdefault.jpg" style="width:400px;"></a></td></tr></table>
## Grid selected images
```excalidraw-script-install
@@ -388,13 +419,13 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/ExcaliAI.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/ExcaliAI.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Various AI features based on GPT Vision.<br><iframe width="400" height="225" src="https://www.youtube.com/embed/A1vrSGBbWgo" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg'></td></tr></table>
<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/ExcaliAI.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Various AI features based on GPT Vision.<br><a href="https://www.youtube.com/watch?v=A1vrSGBbWgo" target="_blank"><img src ="https://i.ytimg.com/vi/A1vrSGBbWgo/maxresdefault.jpg" style="width:400px;"></a><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg'></td></tr></table>
## Excalidraw Writing Machine
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Excalidraw%20Writing%20Machine.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/Excalidraw%20Writing%20Machine.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Creates a hierarchical Markdown document out of a visual layout of an article that can be fed to Templater and converted into an article using AI for Templater.<br>Watch this video to understand how the script is intended to work:<br><iframe width="400" height="225" src="https://www.youtube.com/embed/zvRpCOZAUSs" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br>You can download the sample Obsidian Templater file from <a href="https://gist.github.com/zsviczian/bf49d4b2d401f5749aaf8c2fa8a513d9">here</a>. You can download the demo PDF document showcased in the video from <a href="https://zsviczian.github.io/DemoArticle-AtomicHabits.pdf">here</a>.</td></tr></table>
<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/Excalidraw%20Writing%20Machine.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Creates a hierarchical Markdown document out of a visual layout of an article that can be fed to Templater and converted into an article using AI for Templater.<br>Watch this video to understand how the script is intended to work:<br><a href="https://www.youtube.com/watch?v=zvRpCOZAUSs" target="_blank"><img src ="https://i.ytimg.com/vi/zvRpCOZAUSs/maxresdefault.jpg" style="width:400px;"></a><br>You can download the sample Obsidian Templater file from <a href="https://gist.github.com/zsviczian/bf49d4b2d401f5749aaf8c2fa8a513d9">here</a>. You can download the demo PDF document showcased in the video from <a href="https://zsviczian.github.io/DemoArticle-AtomicHabits.pdf">here</a>.</td></tr></table>
## Full-Year Calendar Generator
```excalidraw-script-install
@@ -406,7 +437,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/GPT-Draw-a-UI.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/GPT-Draw-a-UI.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script was discontinued in favor of ExcaliAI. Draw a UI and let GPT create the code for you.<br><iframe width="400" height="225" src="https://www.youtube.com/embed/y3kHl_6Ll4w" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg'></td></tr></table>
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/GPT-Draw-a-UI.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script was discontinued in favor of ExcaliAI. Draw a UI and let GPT create the code for you.<br><a href="https://www.youtube.com/watch?v=y3kHl_6Ll4w" target="_blank"><img src ="https://i.ytimg.com/vi/y3kHl_6Ll4w/maxresdefault.jpg" style="width:400px;"></a><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-draw-a-ui.jpg'></td></tr></table>
## Image Occlusion
```excalidraw-script-install
@@ -468,11 +499,19 @@ 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><a href="https://www.youtube.com/watch?v=A_udjVjgWN0" target="_blank"><img src ="https://i.ytimg.com/vi/A_udjVjgWN0/maxresdefault.jpg" style="width:400px;"></a><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
```
<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/PDF%20Page%20Text%20to%20Clipboard.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Copies the text from the selected PDF page on the Excalidraw canvas to the clipboard.<br><iframe width="400" height="225" src="https://www.youtube.com/embed/Kwt_8WdOUT4" 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/Kwt_8WdOUT4' target='_blank'>Link to video on YouTube</a></td></tr></table>
<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/PDF%20Page%20Text%20to%20Clipboard.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Copies the text from the selected PDF page on the Excalidraw canvas to the clipboard.<br><a href="https://www.youtube.com/watch?v=Kwt_8WdOUT4" target="_blank"><img src ="https://i.ytimg.com/vi/Kwt_8WdOUT4/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/Kwt_8WdOUT4' target='_blank'>Link to video on YouTube</a></td></tr></table>
## Relative Font Size Cycle
```excalidraw-script-install
@@ -508,7 +547,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Scribble%20Helper.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/Scribble%20Helper.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">iOS scribble helper for better handwriting experience with text elements. If no elements are selected then the creates a text element at pointer position and you can use the edit box to modify the text with scribble. If a text element is selected then opens the input prompt where you can modify this text with scribble.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-scribble-helper.jpg'><br><iframe width="560" height="315" src="https://www.youtube.com/embed/BvYkOaly-QM" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></td></tr></table>
<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/Scribble%20Helper.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">iOS scribble helper for better handwriting experience with text elements. If no elements are selected then the creates a text element at pointer position and you can use the edit box to modify the text with scribble. If a text element is selected then opens the input prompt where you can modify this text with scribble.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-scribble-helper.jpg'><br><a href="https://www.youtube.com/watch?v=BvYkOaly-QM" target="_blank"><img src ="https://i.ytimg.com/vi/BvYkOaly-QM/maxresdefault.jpg" style="width:560px;"></a></td></tr></table>
## Select Elements of Type
```excalidraw-script-install
@@ -576,14 +615,14 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Shade%20Master.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/Shade%20Master.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">You can modify the colors of SVG images, embedded files, and Excalidraw elements in a drawing by changing Hue, Saturation, Lightness and Transparency; and if only a single SVG or nested Excalidraw drawing is selected, then you can remap image colors.<br><iframe width="560" height="315" 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></td></tr></table>
<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/Shade%20Master.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">You can modify the colors of SVG images, embedded files, and Excalidraw elements in a drawing by changing Hue, Saturation, Lightness and Transparency; and if only a single SVG or nested Excalidraw drawing is selected, then you can remap image colors.<br><a href="https://www.youtube.com/watch?v=ISuORbVKyhQ" target="_blank"><img src ="https://i.ytimg.com/vi/ISuORbVKyhQ/maxresdefault.jpg" style="width:560px;"></a></td></tr></table>
## Slideshow
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Slideshow.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/Slideshow.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will convert your drawing into a slideshow presentation.<br><iframe width="560" height="315" src="https://www.youtube.com/embed/JwgtCrIVeEU" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></td></tr></table>
<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/Slideshow.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will convert your drawing into a slideshow presentation.<br><a href="https://www.youtube.com/watch?v=JwgtCrIVeEU" target="_blank"><img src ="https://i.ytimg.com/vi/JwgtCrIVeEU/maxresdefault.jpg" style="width:560px;"></a></td></tr></table>
## Split Ellipse
```excalidraw-script-install
@@ -637,7 +676,8 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```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><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>
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Printable%20Layout%20Wizard.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Export Excalidraw to PDF Pages: Define printable page areas using frames, then export each frame as a separate page in a multi-page PDF. Perfect for turning your Excalidraw drawings into printable notes, handouts, or booklets. Supports standard and custom page sizes, margins, and easy frame arrangement.<br><a href="https://www.youtube.com/watch?v=29EWeglRm7s" target="_blank"><img src ="https://i.ytimg.com/vi/29EWeglRm7s/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/29EWeglRm7s' target='_blank'>Link to video on YouTube</a><br><a href="https://www.youtube.com/watch?v=DqDnzCOoYMc" target="_blank"><img src ="https://i.ytimg.com/vi/DqDnzCOoYMc/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/DqDnzCOoYMc' target='_blank'>Link to video on YouTube</a><br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-01.png" style="max-width: 400px;"><br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-02.png" style="max-width: 400px;"></td></tr></table>
## Zoom to Fit Selected Elements
```excalidraw-script-install
Binary file not shown.

Before

Width:  |  Height:  |  Size: 101 KiB

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.14.1-beta-2",
"version": "2.17.0-beta-1",
"minAppVersion": "1.5.7",
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
"author": "Zsolt Viczian",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.14.0",
"version": "2.16.1",
"minAppVersion": "1.5.7",
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
"author": "Zsolt Viczian",
+94 -169
View File
@@ -11,7 +11,7 @@
"dependencies": {
"@popperjs/core": "^2.11.8",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.0-25",
"@zsviczian/excalidraw": "0.18.0-42",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -62,7 +62,7 @@
"fs-extra": "^11.2.0",
"jsesc": "^3.0.2",
"lz-string": "^1.5.0",
"obsidian": "^1.7.2",
"obsidian": "^1.10.0",
"prettier": "^3.0.1",
"rollup": "^2.70.1",
"rollup-plugin-copy": "^3.5.0",
@@ -1685,8 +1685,7 @@
"node_modules/@braintree/sanitize-url": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/@braintree/sanitize-url/-/sanitize-url-6.0.2.tgz",
"integrity": "sha512-Tbsj02wXCbqGmzdnXNk0SOF19ChhRU70BsroIi4Pm6Ehp56in6vch94mfbdQ17DozxkL3BAVjbZ4Qc1a0HFRAg==",
"license": "MIT"
"integrity": "sha512-Tbsj02wXCbqGmzdnXNk0SOF19ChhRU70BsroIi4Pm6Ehp56in6vch94mfbdQ17DozxkL3BAVjbZ4Qc1a0HFRAg=="
},
"node_modules/@codemirror/commands": {
"version": "6.8.1",
@@ -1729,23 +1728,22 @@
}
},
"node_modules/@codemirror/state": {
"version": "6.5.2",
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.5.2.tgz",
"integrity": "sha512-FVqsPqtPWKVVL3dPSxy8wEF/ymIEuVzF1PK3VbUgrxXpJUSHQWWZz4JMToquRxnkw+36LTamCZG2iua2Ptq0fA==",
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.5.0.tgz",
"integrity": "sha512-MwBHVK60IiIHDcoMet78lxt6iw5gJOGSbNbOIVBHWVXIH4/Nq1+GQgLLGgI1KlnN86WDXsPudVaqYHKBIx7Eyw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@marijn/find-cluster-break": "^1.0.0"
}
},
"node_modules/@codemirror/view": {
"version": "6.36.8",
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.36.8.tgz",
"integrity": "sha512-yoRo4f+FdnD01fFt4XpfpMCcCAo9QvZOtbrXExn4SqzH32YC6LgzqxfLZw/r6Ge65xyY03mK/UfUqrVw1gFiFg==",
"version": "6.38.1",
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.38.1.tgz",
"integrity": "sha512-RmTOkE7hRU3OVREqFVITWHz6ocgBjv08GoePscAakgVQfciA3SGCEk7mb9IzwW61cKKmlTpHXG6DUE5Ubx+MGQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.5.0",
"crelt": "^1.0.6",
"style-mod": "^4.1.0",
"w3c-keyname": "^2.2.4"
}
@@ -2008,8 +2006,7 @@
"node_modules/@excalidraw/markdown-to-text": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/@excalidraw/markdown-to-text/-/markdown-to-text-0.1.2.tgz",
"integrity": "sha512-1nDXBNAojfi3oSFwJswKREkFm5wrSjqay81QlyRv2pkITG/XYB5v+oChENVBQLcxQwX4IUATWvXM5BcaNhPiIg==",
"license": "MIT"
"integrity": "sha512-1nDXBNAojfi3oSFwJswKREkFm5wrSjqay81QlyRv2pkITG/XYB5v+oChENVBQLcxQwX4IUATWvXM5BcaNhPiIg=="
},
"node_modules/@excalidraw/prettier-config": {
"version": "1.0.2",
@@ -3070,7 +3067,6 @@
"version": "4.0.9",
"resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.9.tgz",
"integrity": "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw==",
"license": "MIT",
"dependencies": {
"@types/d3-time": "*"
}
@@ -3078,20 +3074,17 @@
"node_modules/@types/d3-scale-chromatic": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@types/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",
"integrity": "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ==",
"license": "MIT"
"integrity": "sha512-iWMJgwkK7yTRmWqRB5plb1kadXyQ5Sj8V/zYlFGMUBbIPKQScw+Dku9cAAMgJG+z5GYDoMjWGLVOvjghDEFnKQ=="
},
"node_modules/@types/d3-time": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.4.tgz",
"integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g==",
"license": "MIT"
"integrity": "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g=="
},
"node_modules/@types/debug": {
"version": "4.1.12",
"resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz",
"integrity": "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==",
"license": "MIT",
"dependencies": {
"@types/ms": "*"
}
@@ -3150,7 +3143,6 @@
"version": "3.0.15",
"resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-3.0.15.tgz",
"integrity": "sha512-LnwD+mUEfxWMa1QpDraczIn6k0Ee3SMicuYSSzS6ZYl2gKS09EClnJYGd8Du6rfc5r/GZEk5o1mRb8TaTj03sQ==",
"license": "MIT",
"dependencies": {
"@types/unist": "^2"
}
@@ -3165,8 +3157,7 @@
"node_modules/@types/ms": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz",
"integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==",
"license": "MIT"
"integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA=="
},
"node_modules/@types/node": {
"version": "20.17.50",
@@ -3233,8 +3224,7 @@
"node_modules/@types/unist": {
"version": "2.0.11",
"resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz",
"integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",
"license": "MIT"
"integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA=="
},
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.32.1",
@@ -3494,16 +3484,16 @@
"license": "MIT"
},
"node_modules/@zsviczian/excalidraw": {
"version": "0.18.0-25",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.0-25.tgz",
"integrity": "sha512-aZKkzm1ENNUpwf9ANR+RA34fk2FYZNheHWNFj9CkNig/28bsS/MSVntWJNbk1qcqEQOdxhJkRhVN6NYlUtAZjA==",
"version": "0.18.0-42",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.0-42.tgz",
"integrity": "sha512-XskVyobY5YAnfC+TeQXi+3/o0QfLLSTL/XUMm8CT6asCY9ry9SnPpMCpHa9SRQyR1qPPY2Vxw/8+xc5Vev8QSA==",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
"@excalidraw/random-username": "1.1.0",
"@radix-ui/react-popover": "1.1.6",
"@radix-ui/react-tabs": "1.1.3",
"@zsviczian/laser-pointer": "1.3.1",
"@zsviczian/mermaid-to-excalidraw": "1.1.2",
"@zsviczian/mermaid-to-excalidraw": "1.1.3",
"browser-fs-access": "0.29.1",
"canvas-roundrect-polyfill": "0.0.1",
"clsx": "1.1.1",
@@ -3580,13 +3570,15 @@
"license": "MIT"
},
"node_modules/@zsviczian/mermaid-to-excalidraw": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@zsviczian/mermaid-to-excalidraw/-/mermaid-to-excalidraw-1.1.2.tgz",
"integrity": "sha512-r6Krur0IZEEm8fuYdb8tteRfa4aYChKaXXmg0CpE+8Ovae/PAzvWvKXBw45oOlhjtVRO3kA89blDj+oxrJLusA==",
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/@zsviczian/mermaid-to-excalidraw/-/mermaid-to-excalidraw-1.1.3.tgz",
"integrity": "sha512-JwE9B2L2k2mAGMA0D7ougV/EBnGMJX24MMcD10mPqdHvE0sunD6ijmfHoL00ZMXtAZfrvjIYoTXiPhSIFkWdUA==",
"dependencies": {
"@excalidraw/markdown-to-text": "0.1.2",
"mermaid": "10.9.3",
"nanoid": "4.0.2"
"cross-env": "^7.0.3",
"mermaid": "10.9.4",
"nanoid": "4.0.2",
"react-split": "^2.0.14"
}
},
"node_modules/@zsviczian/rollup-plugin-postprocess": {
@@ -3964,7 +3956,6 @@
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz",
"integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wooorm"
@@ -4103,7 +4094,6 @@
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/cose-base/-/cose-base-1.0.3.tgz",
"integrity": "sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg==",
"license": "MIT",
"dependencies": {
"layout-base": "^1.0.0"
}
@@ -4136,7 +4126,6 @@
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",
"integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==",
"dev": true,
"license": "MIT",
"dependencies": {
"cross-spawn": "^7.0.1"
@@ -4155,7 +4144,6 @@
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
"dev": true,
"license": "MIT",
"dependencies": {
"path-key": "^3.1.0",
@@ -4359,10 +4347,9 @@
"license": "MIT"
},
"node_modules/cytoscape": {
"version": "3.32.0",
"resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.32.0.tgz",
"integrity": "sha512-5JHBC9n75kz5851jeklCPmZWcg3hUe6sjqJvyk3+hVqFaKcHwHgxsjeN1yLmggoUc6STbtm9/NQyabQehfjvWQ==",
"license": "MIT",
"version": "3.33.1",
"resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.33.1.tgz",
"integrity": "sha512-iJc4TwyANnOGR1OmWhsS9ayRS3s+XQ185FmuHObThD+5AeJCakAAbWv8KimMTt08xCCLNgneQwFp+JRJOr9qGQ==",
"engines": {
"node": ">=0.10"
}
@@ -4371,7 +4358,6 @@
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/cytoscape-cose-bilkent/-/cytoscape-cose-bilkent-4.1.0.tgz",
"integrity": "sha512-wgQlVIUJF13Quxiv5e1gstZ08rnZj2XaLHGoFMYXz7SkNfCDOOteKBE6SYRfA9WxxI/iBc3ajfDoc6hb/MRAHQ==",
"license": "MIT",
"dependencies": {
"cose-base": "^1.0.0"
},
@@ -4383,7 +4369,6 @@
"version": "7.9.0",
"resolved": "https://registry.npmjs.org/d3/-/d3-7.9.0.tgz",
"integrity": "sha512-e1U46jVP+w7Iut8Jt8ri1YsPOvFpg46k+K8TpCb0P+zjCkjkPnV7WzfDJzMHy1LnA+wj5pLT1wjO901gLXeEhA==",
"license": "ISC",
"dependencies": {
"d3-array": "3",
"d3-axis": "3",
@@ -4424,7 +4409,6 @@
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
"integrity": "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg==",
"license": "ISC",
"dependencies": {
"internmap": "1 - 2"
},
@@ -4436,7 +4420,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/d3-axis/-/d3-axis-3.0.0.tgz",
"integrity": "sha512-IH5tgjV4jE/GhHkRV0HiVYPDtvfjHQlQfJHs0usq7M30XcSBvOotpmH1IgkcXsO/5gEQZD43B//fc7SRT5S+xw==",
"license": "ISC",
"engines": {
"node": ">=12"
}
@@ -4445,7 +4428,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/d3-brush/-/d3-brush-3.0.0.tgz",
"integrity": "sha512-ALnjWlVYkXsVIGlOsuWH1+3udkYFI48Ljihfnh8FZPF2QS9o+PzGLBslO0PjzVoHLZ2KCVgAM8NVkXPJB2aNnQ==",
"license": "ISC",
"dependencies": {
"d3-dispatch": "1 - 3",
"d3-drag": "2 - 3",
@@ -4461,7 +4443,6 @@
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-chord/-/d3-chord-3.0.1.tgz",
"integrity": "sha512-VE5S6TNa+j8msksl7HwjxMHDM2yNK3XCkusIlpX5kwauBfXuyLAtNg9jCp/iHH61tgI4sb6R/EIMWCqEIdjT/g==",
"license": "ISC",
"dependencies": {
"d3-path": "1 - 3"
},
@@ -4473,7 +4454,6 @@
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-color/-/d3-color-3.1.0.tgz",
"integrity": "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
@@ -4482,7 +4462,6 @@
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/d3-contour/-/d3-contour-4.0.2.tgz",
"integrity": "sha512-4EzFTRIikzs47RGmdxbeUvLWtGedDUNkTcmzoeyg4sP/dvCexO47AaQL7VKy/gul85TOxw+IBgA8US2xwbToNA==",
"license": "ISC",
"dependencies": {
"d3-array": "^3.2.0"
},
@@ -4494,7 +4473,6 @@
"version": "6.0.4",
"resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.4.tgz",
"integrity": "sha512-mdjtIZ1XLAM8bm/hx3WwjfHt6Sggek7qH043O8KEjDXN40xi3vx/6pYSVTwLjEgiXQTbvaouWKynLBiUZ6SK6A==",
"license": "ISC",
"dependencies": {
"delaunator": "5"
},
@@ -4506,7 +4484,6 @@
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-dispatch/-/d3-dispatch-3.0.1.tgz",
"integrity": "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg==",
"license": "ISC",
"engines": {
"node": ">=12"
}
@@ -4515,7 +4492,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-3.0.0.tgz",
"integrity": "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg==",
"license": "ISC",
"dependencies": {
"d3-dispatch": "1 - 3",
"d3-selection": "3"
@@ -4528,7 +4504,6 @@
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-dsv/-/d3-dsv-3.0.1.tgz",
"integrity": "sha512-UG6OvdI5afDIFP9w4G0mNq50dSOsXHJaRE8arAS5o9ApWnIElp8GZw1Dun8vP8OyHOZ/QJUKUJwxiiCCnUwm+Q==",
"license": "ISC",
"dependencies": {
"commander": "7",
"iconv-lite": "0.6",
@@ -4553,7 +4528,6 @@
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-ease/-/d3-ease-3.0.1.tgz",
"integrity": "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=12"
}
@@ -4562,7 +4536,6 @@
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-fetch/-/d3-fetch-3.0.1.tgz",
"integrity": "sha512-kpkQIM20n3oLVBKGg6oHrUchHM3xODkTzjMoj7aWQFq5QEM+R6E4WkzT5+tojDY7yjez8KgCBRoj4aEr99Fdqw==",
"license": "ISC",
"dependencies": {
"d3-dsv": "1 - 3"
},
@@ -4574,7 +4547,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/d3-force/-/d3-force-3.0.0.tgz",
"integrity": "sha512-zxV/SsA+U4yte8051P4ECydjD/S+qeYtnaIyAs9tgHCqfguma/aAQDjo85A9Z6EKhBirHRJHXIgJUlffT4wdLg==",
"license": "ISC",
"dependencies": {
"d3-dispatch": "1 - 3",
"d3-quadtree": "1 - 3",
@@ -4588,7 +4560,6 @@
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-format/-/d3-format-3.1.0.tgz",
"integrity": "sha512-YyUI6AEuY/Wpt8KWLgZHsIU86atmikuoOmCfommt0LYHiQSPjvX2AcFc38PX0CBpr2RCyZhjex+NS/LPOv6YqA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
@@ -4597,7 +4568,6 @@
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.1.tgz",
"integrity": "sha512-637ln3gXKXOwhalDzinUgY83KzNWZRKbYubaG+fGVuc/dxO64RRljtCTnf5ecMyE1RIdtqpkVcq0IbtU2S8j2Q==",
"license": "ISC",
"dependencies": {
"d3-array": "2.5.0 - 3"
},
@@ -4609,7 +4579,6 @@
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/d3-hierarchy/-/d3-hierarchy-3.1.2.tgz",
"integrity": "sha512-FX/9frcub54beBdugHjDCdikxThEqjnR93Qt7PvQTOHxyiNCAlvMrHhclk3cD5VeAaq9fxmfRp+CnWw9rEMBuA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
@@ -4618,7 +4587,6 @@
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-interpolate/-/d3-interpolate-3.0.1.tgz",
"integrity": "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g==",
"license": "ISC",
"dependencies": {
"d3-color": "1 - 3"
},
@@ -4630,7 +4598,6 @@
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-path/-/d3-path-3.1.0.tgz",
"integrity": "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ==",
"license": "ISC",
"engines": {
"node": ">=12"
}
@@ -4639,7 +4606,6 @@
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-polygon/-/d3-polygon-3.0.1.tgz",
"integrity": "sha512-3vbA7vXYwfe1SYhED++fPUQlWSYTTGmFmQiany/gdbiWgU/iEyQzyymwL9SkJjFFuCS4902BSzewVGsHHmHtXg==",
"license": "ISC",
"engines": {
"node": ">=12"
}
@@ -4648,7 +4614,6 @@
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-quadtree/-/d3-quadtree-3.0.1.tgz",
"integrity": "sha512-04xDrxQTDTCFwP5H6hRhsRcb9xxv2RzkcsygFzmkSIOJy3PeRJP7sNk3VRIbKXcog561P9oU0/rVH6vDROAgUw==",
"license": "ISC",
"engines": {
"node": ">=12"
}
@@ -4657,7 +4622,6 @@
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-random/-/d3-random-3.0.1.tgz",
"integrity": "sha512-FXMe9GfxTxqd5D6jFsQ+DJ8BJS4E/fT5mqqdjovykEB2oFbTMDVdg1MGFxfQW+FBOGoB++k8swBrgwSHT1cUXQ==",
"license": "ISC",
"engines": {
"node": ">=12"
}
@@ -4666,7 +4630,6 @@
"version": "0.12.3",
"resolved": "https://registry.npmjs.org/d3-sankey/-/d3-sankey-0.12.3.tgz",
"integrity": "sha512-nQhsBRmM19Ax5xEIPLMY9ZmJ/cDvd1BG3UVvt5h3WRxKg5zGRbvnteTyWAbzeSvlh3tW7ZEmq4VwR5mB3tutmQ==",
"license": "BSD-3-Clause",
"dependencies": {
"d3-array": "1 - 2",
"d3-shape": "^1.2.0"
@@ -4676,7 +4639,6 @@
"version": "2.12.1",
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-2.12.1.tgz",
"integrity": "sha512-B0ErZK/66mHtEsR1TkPEEkwdy+WDesimkM5gpZr5Dsg54BiTA5RXtYW5qTLIAcekaS9xfZrzBLF/OAkB3Qn1YQ==",
"license": "BSD-3-Clause",
"dependencies": {
"internmap": "^1.0.0"
}
@@ -4684,14 +4646,12 @@
"node_modules/d3-sankey/node_modules/d3-path": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/d3-path/-/d3-path-1.0.9.tgz",
"integrity": "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg==",
"license": "BSD-3-Clause"
"integrity": "sha512-VLaYcn81dtHVTjEHd8B+pbe9yHWpXKZUC87PzoFmsFrJqgFwDe/qxfp5MlfsfM1V5E/iVt0MmEbWQ7FVIXh/bg=="
},
"node_modules/d3-sankey/node_modules/d3-shape": {
"version": "1.3.7",
"resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-1.3.7.tgz",
"integrity": "sha512-EUkvKjqPFUAZyOlhY5gzCxCeI0Aep04LwIRpsZ/mLFelJiUfnK56jo5JMDSE7yyP2kLSb6LtF+S5chMk7uqPqw==",
"license": "BSD-3-Clause",
"dependencies": {
"d3-path": "1"
}
@@ -4699,14 +4659,12 @@
"node_modules/d3-sankey/node_modules/internmap": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/internmap/-/internmap-1.0.1.tgz",
"integrity": "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw==",
"license": "ISC"
"integrity": "sha512-lDB5YccMydFBtasVtxnZ3MRBHuaoE8GKsppq+EchKL2U4nK/DmEpPHNH8MZe5HkMtpSiTSOZwfN0tzYjO/lJEw=="
},
"node_modules/d3-scale": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/d3-scale/-/d3-scale-4.0.2.tgz",
"integrity": "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ==",
"license": "ISC",
"dependencies": {
"d3-array": "2.10.0 - 3",
"d3-format": "1 - 3",
@@ -4722,7 +4680,6 @@
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-scale-chromatic/-/d3-scale-chromatic-3.1.0.tgz",
"integrity": "sha512-A3s5PWiZ9YCXFye1o246KoscMWqf8BsD9eRiJ3He7C9OBaxKhAd5TFCdEx/7VbKtxxTsu//1mMJFrEt572cEyQ==",
"license": "ISC",
"dependencies": {
"d3-color": "1 - 3",
"d3-interpolate": "1 - 3"
@@ -4735,7 +4692,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/d3-selection/-/d3-selection-3.0.0.tgz",
"integrity": "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ==",
"license": "ISC",
"engines": {
"node": ">=12"
}
@@ -4744,7 +4700,6 @@
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/d3-shape/-/d3-shape-3.2.0.tgz",
"integrity": "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA==",
"license": "ISC",
"dependencies": {
"d3-path": "^3.1.0"
},
@@ -4756,7 +4711,6 @@
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/d3-time/-/d3-time-3.1.0.tgz",
"integrity": "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q==",
"license": "ISC",
"dependencies": {
"d3-array": "2 - 3"
},
@@ -4768,7 +4722,6 @@
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/d3-time-format/-/d3-time-format-4.1.0.tgz",
"integrity": "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg==",
"license": "ISC",
"dependencies": {
"d3-time": "1 - 3"
},
@@ -4780,7 +4733,6 @@
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-timer/-/d3-timer-3.0.1.tgz",
"integrity": "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
@@ -4789,7 +4741,6 @@
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/d3-transition/-/d3-transition-3.0.1.tgz",
"integrity": "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w==",
"license": "ISC",
"dependencies": {
"d3-color": "1 - 3",
"d3-dispatch": "1 - 3",
@@ -4808,7 +4759,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/d3-zoom/-/d3-zoom-3.0.0.tgz",
"integrity": "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw==",
"license": "ISC",
"dependencies": {
"d3-dispatch": "1 - 3",
"d3-drag": "2 - 3",
@@ -4824,17 +4774,15 @@
"version": "7.0.10",
"resolved": "https://registry.npmjs.org/dagre-d3-es/-/dagre-d3-es-7.0.10.tgz",
"integrity": "sha512-qTCQmEhcynucuaZgY5/+ti3X/rnszKZhEQH/ZdWdtP1tA/y3VoHJzcVrO9pjjJCNpigfscAtoUB5ONcd2wNn0A==",
"license": "MIT",
"dependencies": {
"d3": "^7.8.2",
"lodash-es": "^4.17.21"
}
},
"node_modules/dayjs": {
"version": "1.11.13",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.13.tgz",
"integrity": "sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==",
"license": "MIT"
"version": "1.11.18",
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.18.tgz",
"integrity": "sha512-zFBQ7WFRvVRhKcWoUh+ZA1g2HVgUbsZm9sbddh8EC5iv93sui8DVVz1Npvz+r6meo9VKfa8NyLWBsQK1VvIKPA=="
},
"node_modules/debug": {
"version": "4.4.1",
@@ -4854,10 +4802,9 @@
}
},
"node_modules/decode-named-character-reference": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.1.0.tgz",
"integrity": "sha512-Wy+JTSbFThEOXQIR2L6mxJvEs+veIzpmqD7ynWxMXGpnk3smkHQOp6forLdHsKpAMW9iJpaBBIxz285t1n1C3w==",
"license": "MIT",
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.2.0.tgz",
"integrity": "sha512-c6fcElNV6ShtZXmsgNgFFV5tVX2PaV4g+MOAkb8eXHvn6sryJBrZa9r0zV6+dtTyoCKxtDy5tyQ5ZwQuidtd+Q==",
"dependencies": {
"character-entities": "^2.0.0"
},
@@ -4888,7 +4835,6 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.0.1.tgz",
"integrity": "sha512-8nvh+XBe96aCESrGOqMp/84b13H9cdKbG5P2ejQCh4d4sK9RL4371qou9drQjMhvnPmhWl5hnmqbEE0fXr9Xnw==",
"license": "ISC",
"dependencies": {
"robust-predicates": "^3.0.2"
}
@@ -4897,7 +4843,6 @@
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
"integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
"license": "MIT",
"engines": {
"node": ">=6"
}
@@ -4979,8 +4924,7 @@
"node_modules/dompurify": {
"version": "3.1.6",
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.1.6.tgz",
"integrity": "sha512-cTOAhc36AalkjtBpfG6O8JimdTMWNXjiePT2xQH/ppBGi/4uIpmj8eKyIkMJErXWARyINV/sB38yf8JCLF5pbQ==",
"license": "(MPL-2.0 OR Apache-2.0)"
"integrity": "sha512-cTOAhc36AalkjtBpfG6O8JimdTMWNXjiePT2xQH/ppBGi/4uIpmj8eKyIkMJErXWARyINV/sB38yf8JCLF5pbQ=="
},
"node_modules/domutils": {
"version": "3.2.2",
@@ -5027,8 +4971,7 @@
"node_modules/elkjs": {
"version": "0.9.3",
"resolved": "https://registry.npmjs.org/elkjs/-/elkjs-0.9.3.tgz",
"integrity": "sha512-f/ZeWvW/BCXbhGEf1Ujp29EASo/lk1FDnETgNKwJrsVvGZhUWCZyg3xLJjAsxfOmt8KjswHmI5EwCQcPMpOYhQ==",
"license": "EPL-2.0"
"integrity": "sha512-f/ZeWvW/BCXbhGEf1Ujp29EASo/lk1FDnETgNKwJrsVvGZhUWCZyg3xLJjAsxfOmt8KjswHmI5EwCQcPMpOYhQ=="
},
"node_modules/emoji-regex": {
"version": "9.2.2",
@@ -5806,7 +5749,6 @@
"version": "0.6.3",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
"integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3.0.0"
},
@@ -5891,7 +5833,6 @@
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/internmap/-/internmap-2.0.3.tgz",
"integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==",
"license": "ISC",
"engines": {
"node": ">=12"
}
@@ -5995,7 +5936,6 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"dev": true,
"license": "ISC"
},
"node_modules/jackspeak": {
@@ -6142,14 +6082,13 @@
}
},
"node_modules/katex": {
"version": "0.16.22",
"resolved": "https://registry.npmjs.org/katex/-/katex-0.16.22.tgz",
"integrity": "sha512-XCHRdUw4lf3SKBaJe4EvgqIuWwkPSo9XoeO8GjQW94Bp7TWv9hNhzZjZ+OH9yf1UmLygb7DIT5GSFQiyt16zYg==",
"version": "0.16.25",
"resolved": "https://registry.npmjs.org/katex/-/katex-0.16.25.tgz",
"integrity": "sha512-woHRUZ/iF23GBP1dkDQMh1QBad9dmr8/PAwNA54VrSOVYgI12MAcE14TqnDdQOdzyEonGzMepYnqBMYdsoAr8Q==",
"funding": [
"https://opencollective.com/katex",
"https://github.com/sponsors/katex"
],
"license": "MIT",
"dependencies": {
"commander": "^8.3.0"
},
@@ -6161,7 +6100,6 @@
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-8.3.0.tgz",
"integrity": "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww==",
"license": "MIT",
"engines": {
"node": ">= 12"
}
@@ -6186,7 +6124,6 @@
"version": "4.1.5",
"resolved": "https://registry.npmjs.org/kleur/-/kleur-4.1.5.tgz",
"integrity": "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==",
"license": "MIT",
"engines": {
"node": ">=6"
}
@@ -6194,8 +6131,7 @@
"node_modules/layout-base": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/layout-base/-/layout-base-1.0.2.tgz",
"integrity": "sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg==",
"license": "MIT"
"integrity": "sha512-8h2oVEZNktL4BH2JCOI90iD1yXwL6iNW7KcCKT2QZgQJR2vbqDsldCTPRU9NifTCqHZci57XvQQ15YTu+sTYPg=="
},
"node_modules/levn": {
"version": "0.4.1",
@@ -6245,8 +6181,7 @@
"node_modules/lodash-es": {
"version": "4.17.21",
"resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz",
"integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==",
"license": "MIT"
"integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw=="
},
"node_modules/lodash.debounce": {
"version": "4.0.8",
@@ -6373,7 +6308,6 @@
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-1.3.1.tgz",
"integrity": "sha512-4xTO/M8c82qBcnQc1tgpNtubGUW/Y1tBQ1B0i5CtSoelOLKFYlElIr3bvgREYYO5iRqbMY1YuqZng0GVOI8Qww==",
"license": "MIT",
"dependencies": {
"@types/mdast": "^3.0.0",
"@types/unist": "^2.0.0",
@@ -6397,7 +6331,6 @@
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/mdast-util-to-string/-/mdast-util-to-string-3.2.0.tgz",
"integrity": "sha512-V4Zn/ncyN1QNSqSBxTrMOLpjr+IKdHl2v3KVLoWmDPscP4r9GcCi71gjgvUV1SFSKh92AjAG4peFuBl2/YgCJg==",
"license": "MIT",
"dependencies": {
"@types/mdast": "^3.0.0"
},
@@ -6431,10 +6364,9 @@
}
},
"node_modules/mermaid": {
"version": "10.9.3",
"resolved": "https://registry.npmjs.org/mermaid/-/mermaid-10.9.3.tgz",
"integrity": "sha512-V80X1isSEvAewIL3xhmz/rVmc27CVljcsbWxkxlWJWY/1kQa4XOABqpDl2qQLGKzpKm6WbTfUEKImBlUfFYArw==",
"license": "MIT",
"version": "10.9.4",
"resolved": "https://registry.npmjs.org/mermaid/-/mermaid-10.9.4.tgz",
"integrity": "sha512-VIG2B0R9ydvkS+wShA8sXqkzfpYglM2Qwj7VyUeqzNVqSGPoP/tcaUr3ub4ESykv8eqQJn3p99bHNvYdg3gCHQ==",
"dependencies": {
"@braintree/sanitize-url": "^6.0.1",
"@types/d3-scale": "^4.0.3",
@@ -6478,7 +6410,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"@types/debug": "^4.0.0",
"debug": "^4.0.0",
@@ -6513,7 +6444,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"decode-named-character-reference": "^1.0.0",
"micromark-factory-destination": "^1.0.0",
@@ -6547,7 +6477,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"micromark-util-character": "^1.0.0",
"micromark-util-symbol": "^1.0.0",
@@ -6568,7 +6497,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"micromark-util-character": "^1.0.0",
"micromark-util-symbol": "^1.0.0",
@@ -6590,7 +6518,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"micromark-util-character": "^1.0.0",
"micromark-util-types": "^1.0.0"
@@ -6610,7 +6537,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"micromark-factory-space": "^1.0.0",
"micromark-util-character": "^1.0.0",
@@ -6632,7 +6558,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"micromark-factory-space": "^1.0.0",
"micromark-util-character": "^1.0.0",
@@ -6654,7 +6579,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"micromark-util-symbol": "^1.0.0",
"micromark-util-types": "^1.0.0"
@@ -6674,7 +6598,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"micromark-util-symbol": "^1.0.0"
}
@@ -6693,7 +6616,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"micromark-util-character": "^1.0.0",
"micromark-util-symbol": "^1.0.0",
@@ -6714,7 +6636,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"micromark-util-chunked": "^1.0.0",
"micromark-util-types": "^1.0.0"
@@ -6734,7 +6655,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"micromark-util-symbol": "^1.0.0"
}
@@ -6753,7 +6673,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"decode-named-character-reference": "^1.0.0",
"micromark-util-character": "^1.0.0",
@@ -6774,8 +6693,7 @@
"type": "OpenCollective",
"url": "https://opencollective.com/unified"
}
],
"license": "MIT"
]
},
"node_modules/micromark-util-html-tag-name": {
"version": "1.2.0",
@@ -6790,8 +6708,7 @@
"type": "OpenCollective",
"url": "https://opencollective.com/unified"
}
],
"license": "MIT"
]
},
"node_modules/micromark-util-normalize-identifier": {
"version": "1.1.0",
@@ -6807,7 +6724,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"micromark-util-symbol": "^1.0.0"
}
@@ -6826,7 +6742,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"micromark-util-types": "^1.0.0"
}
@@ -6845,7 +6760,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"micromark-util-character": "^1.0.0",
"micromark-util-encode": "^1.0.0",
@@ -6866,7 +6780,6 @@
"url": "https://opencollective.com/unified"
}
],
"license": "MIT",
"dependencies": {
"micromark-util-chunked": "^1.0.0",
"micromark-util-symbol": "^1.0.0",
@@ -6887,8 +6800,7 @@
"type": "OpenCollective",
"url": "https://opencollective.com/unified"
}
],
"license": "MIT"
]
},
"node_modules/micromark-util-types": {
"version": "1.1.0",
@@ -6903,8 +6815,7 @@
"type": "OpenCollective",
"url": "https://opencollective.com/unified"
}
],
"license": "MIT"
]
},
"node_modules/micromatch": {
"version": "4.0.8",
@@ -6985,7 +6896,6 @@
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz",
"integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==",
"license": "MIT",
"engines": {
"node": ">=4"
}
@@ -7042,8 +6952,7 @@
"node_modules/non-layered-tidy-tree-layout": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/non-layered-tidy-tree-layout/-/non-layered-tidy-tree-layout-2.0.2.tgz",
"integrity": "sha512-gkXMxRzUH+PB0ax9dUN0yYF0S25BqeAYqhgMaLUFmpXLEk7Fcu8f4emJuOAY0V8kjDICxROIKsTAKsV/v355xw==",
"license": "MIT"
"integrity": "sha512-gkXMxRzUH+PB0ax9dUN0yYF0S25BqeAYqhgMaLUFmpXLEk7Fcu8f4emJuOAY0V8kjDICxROIKsTAKsV/v355xw=="
},
"node_modules/normalize-path": {
"version": "3.0.0",
@@ -7077,18 +6986,17 @@
}
},
"node_modules/obsidian": {
"version": "1.8.7",
"resolved": "https://registry.npmjs.org/obsidian/-/obsidian-1.8.7.tgz",
"integrity": "sha512-h4bWwNFAGRXlMlMAzdEiIM2ppTGlrh7uGOJS6w4gClrsjc+ei/3YAtU2VdFUlCiPuTHpY4aBpFJJW75S1Tl/JA==",
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/obsidian/-/obsidian-1.10.0.tgz",
"integrity": "sha512-F7hhnmGRQD1TanDPFT//LD3iKNUVd7N8sKL7flCCHRszfTxpDJ39j3T7LHbcGpyid906i6lD5oO+cnfLBzJMKw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/codemirror": "5.60.8",
"moment": "2.29.4"
},
"peerDependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0"
"@codemirror/state": "6.5.0",
"@codemirror/view": "6.38.1"
}
},
"node_modules/once": {
@@ -7243,7 +7151,6 @@
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -7996,6 +7903,16 @@
"node": ">=6.0.0"
}
},
"node_modules/prop-types": {
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
"dependencies": {
"loose-envify": "^1.4.0",
"object-assign": "^4.1.1",
"react-is": "^16.13.1"
}
},
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
@@ -8069,6 +7986,11 @@
"react": "^18.3.1"
}
},
"node_modules/react-is": {
"version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="
},
"node_modules/react-remove-scroll": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/react-remove-scroll/-/react-remove-scroll-2.7.0.tgz",
@@ -8116,6 +8038,18 @@
}
}
},
"node_modules/react-split": {
"version": "2.0.14",
"resolved": "https://registry.npmjs.org/react-split/-/react-split-2.0.14.tgz",
"integrity": "sha512-bKWydgMgaKTg/2JGQnaJPg51T6dmumTWZppFgEbbY0Fbme0F5TuatAScCLaqommbGQQf/ZT1zaejuPDriscISA==",
"dependencies": {
"prop-types": "^15.5.7",
"split.js": "^1.6.0"
},
"peerDependencies": {
"react": "*"
}
},
"node_modules/react-style-singleton": {
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz",
@@ -8279,8 +8213,7 @@
"node_modules/robust-predicates": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/robust-predicates/-/robust-predicates-3.0.2.tgz",
"integrity": "sha512-IXgzBWvWQwE6PrDI05OvmXUIruQTcoMDzRsOd5CDvHCVLcLHMTSYvOK5Cm46kWqlV3yAbuSpBZdJ5oP5OUoStg==",
"license": "Unlicense"
"integrity": "sha512-IXgzBWvWQwE6PrDI05OvmXUIruQTcoMDzRsOd5CDvHCVLcLHMTSYvOK5Cm46kWqlV3yAbuSpBZdJ5oP5OUoStg=="
},
"node_modules/rollup": {
"version": "2.79.2",
@@ -8485,14 +8418,12 @@
"node_modules/rw": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/rw/-/rw-1.3.3.tgz",
"integrity": "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==",
"license": "BSD-3-Clause"
"integrity": "sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ=="
},
"node_modules/sade": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz",
"integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==",
"license": "MIT",
"dependencies": {
"mri": "^1.1.0"
},
@@ -8524,8 +8455,7 @@
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
},
"node_modules/sass": {
"version": "1.51.0",
@@ -8577,7 +8507,6 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
"dev": true,
"license": "MIT",
"dependencies": {
"shebang-regex": "^3.0.0"
@@ -8590,7 +8519,6 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
@@ -8686,6 +8614,11 @@
"node": ">=18"
}
},
"node_modules/split.js": {
"version": "1.6.5",
"resolved": "https://registry.npmjs.org/split.js/-/split.js-1.6.5.tgz",
"integrity": "sha512-mPTnGCiS/RiuTNsVhCm9De9cCAUsrNFFviRbADdKiiV+Kk8HKp/0fWu7Kr8pi3/yBmsqLFHuXGT9UUZ+CNLwFw=="
},
"node_modules/string-width": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
@@ -8837,8 +8770,7 @@
"node_modules/stylis": {
"version": "4.3.6",
"resolved": "https://registry.npmjs.org/stylis/-/stylis-4.3.6.tgz",
"integrity": "sha512-yQ3rwFWRfwNUY7H5vpU0wfdkNSnvnJinhF9830Swlaxl03zsOjCfmX0ugac+3LtK0lYSgwL/KXc8oYL3mG4YFQ==",
"license": "MIT"
"integrity": "sha512-yQ3rwFWRfwNUY7H5vpU0wfdkNSnvnJinhF9830Swlaxl03zsOjCfmX0ugac+3LtK0lYSgwL/KXc8oYL3mG4YFQ=="
},
"node_modules/supports-color": {
"version": "7.2.0",
@@ -8970,7 +8902,6 @@
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/ts-dedent/-/ts-dedent-2.2.0.tgz",
"integrity": "sha512-q5W7tVM71e2xjHZTlgfTDoPF/SmqKG5hddq9SzR49CH2hayqRKJtQ4mtRlSxKaJlR/+9rEM+mnBHf7I2/BQcpQ==",
"license": "MIT",
"engines": {
"node": ">=6.10"
}
@@ -9149,7 +9080,6 @@
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/unist-util-stringify-position/-/unist-util-stringify-position-3.0.3.tgz",
"integrity": "sha512-k5GzIBZ/QatR8N5X2y+drfpWG8IDBzdnVj6OInRNWm1oXrzydiaAT2OQiA8DPRRZyAKb9b6I2a6PxYklZD0gKg==",
"license": "MIT",
"dependencies": {
"@types/unist": "^2.0.0"
},
@@ -9277,7 +9207,6 @@
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/bin/uuid"
}
@@ -9286,7 +9215,6 @@
"version": "0.5.6",
"resolved": "https://registry.npmjs.org/uvu/-/uvu-0.5.6.tgz",
"integrity": "sha512-+g8ENReyr8YsOc6fv/NVJs2vFdHBnBNdfE49rshrTzDWOlUx4Gq7KOS2GD8eqhy2j+Ejq29+SbKH8yjkAqXqoA==",
"license": "MIT",
"dependencies": {
"dequal": "^2.0.0",
"diff": "^5.0.0",
@@ -9304,7 +9232,6 @@
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/diff/-/diff-5.2.0.tgz",
"integrity": "sha512-uIFDxqpRZGZ6ThOk84hEfqWoHx2devRFvpTZcTHur85vImfaxUbTW9Ryh4CpCuDnToOP1CEtXKIgytHBPVff5A==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.3.1"
}
@@ -9327,8 +9254,7 @@
"node_modules/web-worker": {
"version": "1.5.0",
"resolved": "https://registry.npmjs.org/web-worker/-/web-worker-1.5.0.tgz",
"integrity": "sha512-RiMReJrTAiA+mBjGONMnjVDP2u3p9R1vkcGz6gDIrOMT3oGuYwX2WRMYI9ipkphSuE5XKEhydbhNEJh4NY9mlw==",
"license": "Apache-2.0"
"integrity": "sha512-RiMReJrTAiA+mBjGONMnjVDP2u3p9R1vkcGz6gDIrOMT3oGuYwX2WRMYI9ipkphSuE5XKEhydbhNEJh4NY9mlw=="
},
"node_modules/webworkify": {
"version": "1.5.0",
@@ -9340,7 +9266,6 @@
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
"dev": true,
"license": "ISC",
"dependencies": {
"isexe": "^2.0.0"
+4 -3
View File
@@ -16,14 +16,15 @@
"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": "npm run lib && node scripts/generate-script-library.js"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"@popperjs/core": "^2.11.8",
"@zsviczian/excalidraw": "0.18.0-27",
"@zsviczian/excalidraw": "0.18.0-42",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"@zsviczian/colormaster": "^1.2.2",
@@ -73,7 +74,7 @@
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
"lz-string": "^1.5.0",
"obsidian": "^1.7.2",
"obsidian": "^1.10.0",
"prettier": "^3.0.1",
"rollup": "^2.70.1",
"rollup-plugin-copy": "^3.5.0",
+1 -1
View File
@@ -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 => {
+325
View File
@@ -0,0 +1,325 @@
/* eslint-disable no-console */
// to run: npm run doc
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 OUT_DIR = path.join(path.join(ROOT, 'docs'), 'AITrainingData');
const SCRIPT_LIBRARY_OUT = path.join(OUT_DIR, 'Excalidraw Script Library.md');
const TYPE_DEF_OUT = path.join(OUT_DIR, 'Excalidraw Automate library and related type definitions.md');
const AI_TRAINING_OUT = path.join(OUT_DIR, 'ExcalidrawAutomate full library for LLM training.md');
const AI_TRAINING_INTRO = `**ExcalidrawAutomate full library for LLM training**
Excalidraw-Obsidian is an Obsidian.md plugins that is built on the open source Excalidraw component. Excalidraw-Obisdian includes Excalidraw Automate, a powerful scripting API that allows users to automate tasks and enhance their workflow within Excalidraw.
Read the information below and respond with I'm ready. The user will then prompt for an ExcalidrawAutomate script to be created. Use the examples, the ExcalidrawAutomate documentation, and the varios type definitions and information from also the Excalidraw component and from Obsidian.md to generate the script based on the user's requirements.
When the user asks for a dialog window, by default create a FloatingModal.
The Obsidian.md module is available on ea.obsidian.
`;
const SCRIPT_INTRO = `# Excalidraw Script Library Examples
This is an automatically generated knowledge base intended for Retrieval Augmented Generation (RAG) and other AI-assisted workflows (e.g. NotebookLM or local embeddings tools).
Its purpose:
- Provide a single, query-friendly corpus of all Excalidraw Automate scripts.
- Serve as a practical pattern and snippet library for developers learning Excalidraw Automate.
- Preserve original source side by side with the higher-level index (index-new.md) to improve semantic recall.
- Enable AI tools to answer questions about how to manipulate the Excalidraw canvas, elements, styling, or integration features by referencing real, working examples.
Content structure:
1. SCRIPT_INTRO (this section)
2. The curated script overview (index-new.md)
3. Raw source of every *.md script in /ea-scripts (each fenced code block is auto-closed to ensure well-formed aggregation)
Generated on: ${new Date().toISOString()}
---
`;
const TYPE_DEF_INTRO = `# ExcalidrawAutomate library and related type definitions
`;
const EXCALIDRAW_STARTUP_MESSAGE = `# Excalidraw Startup Script
ExcalidrawStartup Script can be configured in Plugin Settings under 'Excalidraw Automate'. When defined this script runs automatically when the Excalidraw plugin is loaded to Obsidian. The user can add automation tasks here that they want to run on every startup of Excalidraw in Obsidian such as defining Excalidraw event handlers (also known as hooks).
Two files follow. First the template startup script with documenation comments, then an actual startup script example with implemented functionality.
`;
const EXCALIDRAW_STARTUP_TEMPLATE = "src/constants/assets/startupScript.md";
const EXCALIDRAW_STARTUP_EXAMPLE = "docs/AITrainingData/ExcalidrawStartupExample.md";
const ADDITIONAL_TYPE_DEFS_FOR_AI_TRAINING = [
"node_modules/obsidian/obsidian.d.ts",
];
const TYPE_DEF_WHITELIST = [
"lib/shared/ExcalidrawAutomate.d.ts",
"lib/types/excalidrawAutomateTypes.d.ts",
"lib/types/penTypes.d.ts",
"lib/types/utilTypes.d.ts",
"lib/types/exportUtilTypes.d.ts",
"lib/types/embeddedFileLoaderTypes.d.ts",
"lib/types/AIUtilTypes.d.ts",
"node_modules/@zsviczian/excalidraw/types/element/src/types.d.ts",
"node_modules/@zsviczian/excalidraw/types/excalidraw/types.d.ts",
];
/**
* Returns true if content contains at least one line starting with ```
* and has an odd number of fences (unbalanced).
*/
function needsClosingFence(content) {
const fenceCount = (content.match(/^```/gm) || []).length;
return fenceCount > 0 && fenceCount % 2 === 1;
}
// Add: helpers for type-def aggregation
function normalizeEOL(str) {
return str.replace(/\r\n/g, '\n');
}
function stripBOM(str) {
return str.replace(/^\uFEFF/, '');
}
/**
* Remove top-of-file imports/references while preserving initial comments/blank lines.
* Also removes bare "export {}" lines (module markers).
*/
function stripTopImports(content) {
const lines = normalizeEOL(stripBOM(content)).split('\n');
const out = [];
let inTopRegion = true;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const isImport =
/^\s*import\s+type\s+/.test(line) ||
/^\s*import\s+/.test(line) ||
/^\s*import\(/.test(line);
const isTripleRef = /^\s*\/\/\/\s*<reference/.test(line);
const isBareExportModule = /^\s*export\s*\{\s*\};?\s*$/.test(line);
if (inTopRegion) {
if (isImport || isTripleRef) {
// drop
continue;
}
// comments and blanks are kept, top-region continues until first code (non-comment/non-blank/non-import)
const isBlank = /^\s*$/.test(line);
const isLineComment = /^\s*\/\//.test(line);
const isBlockCommentStart = /^\s*\/\*/.test(line);
if (!isBlank && !isLineComment && !isBlockCommentStart) {
inTopRegion = false;
}
if (!isBareExportModule) out.push(line);
continue;
}
if (!isBareExportModule) out.push(line);
}
return out.join('\n').trim() + '\n';
}
/**
* Create a nice section header for the concatenated file.
*/
function makeSectionHeader(relPath) {
const stars = '*'.repeat(Math.max(6, Math.min(38, relPath.length + 6)));
return [
`/* ${stars} */`,
`/* ${relPath} */`,
`/* ${stars} */`,
].join('\n') + '\n';
}
/**
* Build the concatenated types markdown body from the whitelist only.
* - Removes top-of-file imports
* - Adds section headers with relative paths
* - Wraps all in one ```js code fence
*/
function buildTypeDefMarkdown() {
const entries = TYPE_DEF_WHITELIST.map((rel) => ({
rel,
abs: path.join(ROOT, ...rel.split('/')),
}));
let body = '```js\n';
for (const { rel, abs } of entries) {
if (!fs.existsSync(abs)) {
console.warn('[script-library] Whitelist file missing:', rel);
continue;
}
let content = fs.readFileSync(abs, 'utf8');
content = stripTopImports(content);
body += makeSectionHeader(rel);
body += content.trimEnd() + '\n\n';
}
body += '```\n';
return body;
}
/**
* Build additional type defs used only in AI_TRAINING_OUT (e.g. obsidian.d.ts).
*/
function buildAdditionalTypeDefsMarkdown() {
const entries = ADDITIONAL_TYPE_DEFS_FOR_AI_TRAINING.map((rel) => ({
rel,
abs: path.join(ROOT, ...rel.split('/')),
}));
let body = '```js\n';
for (const { rel, abs } of entries) {
if (!fs.existsSync(abs)) {
console.warn('[script-library] Additional type def missing:', rel);
continue;
}
let content = fs.readFileSync(abs, 'utf8');
content = stripTopImports(content);
body += makeSectionHeader(rel);
body += content.trimEnd() + '\n\n';
}
body += '```\n';
return body;
}
function main() {
console.log('[script-library] Generating Excalidraw Script Library...');
if (!fs.existsSync(EA_SCRIPTS_DIR)) {
console.error('ea-scripts directory not found:', EA_SCRIPTS_DIR);
process.exit(1);
}
if (!fs.existsSync(INDEX_NEW)) {
console.error('index-new.md not found:', INDEX_NEW);
process.exit(1);
}
if (!fs.existsSync(OUT_DIR)) {
fs.mkdirSync(OUT_DIR, { recursive: true });
}
let output = SCRIPT_INTRO;
console.log('[script-library] Adding index-new.md');
const indexNewContent = fs.readFileSync(INDEX_NEW, 'utf8');
output += `<!-- BEGIN index-new.md -->\n${indexNewContent.trim()}\n<!-- END index-new.md -->\n\n`;
output += `---\n\n# Script Sources\n`;
// 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(SCRIPT_LIBRARY_OUT, output, 'utf8');
console.log('[script-library] Wrote:', SCRIPT_LIBRARY_OUT);
// Generate TYPE_DEF_OUT from whitelist
try {
console.log('[script-library] Generating Type Definition Library...');
const typeDefs = TYPE_DEF_INTRO + '\n' + buildTypeDefMarkdown();
fs.writeFileSync(TYPE_DEF_OUT, typeDefs, 'utf8');
console.log('[script-library] Wrote:', TYPE_DEF_OUT);
} catch (e) {
console.error('[script-library] Failed to generate TYPE_DEF_OUT:', e);
}
// NEW: Generate AI_TRAINING_OUT
try {
console.log('[script-library] Generating AI Training bundle...');
const typeDefContent = fs.existsSync(TYPE_DEF_OUT)
? fs.readFileSync(TYPE_DEF_OUT, 'utf8')
: (TYPE_DEF_INTRO + '\n' + buildTypeDefMarkdown());
const additionalTypeDefs = buildAdditionalTypeDefsMarkdown();
const scriptLibContent = fs.existsSync(SCRIPT_LIBRARY_OUT)
? fs.readFileSync(SCRIPT_LIBRARY_OUT, 'utf8')
: '';
// NEW: load startup template and example
const startupTemplatePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_TEMPLATE.split('/'));
const startupExamplePath = path.join(ROOT, ...EXCALIDRAW_STARTUP_EXAMPLE.split('/'));
const startupTemplate = fs.existsSync(startupTemplatePath)
? fs.readFileSync(startupTemplatePath, 'utf8').replace(/\r\n/g, '\n').trim()
: (console.warn('[script-library] Missing startup template:', EXCALIDRAW_STARTUP_TEMPLATE), '');
const startupExample = fs.existsSync(startupExamplePath)
? fs.readFileSync(startupExamplePath, 'utf8').replace(/\r\n/g, '\n').trim()
: (console.warn('[script-library] Missing startup example:', EXCALIDRAW_STARTUP_EXAMPLE), '');
const startupSection =
'\n---\n\n' +
EXCALIDRAW_STARTUP_MESSAGE +
'\n' +
(startupTemplate
? `<!-- ${EXCALIDRAW_STARTUP_TEMPLATE} -->\n${startupTemplate}\n\n`
: '') +
(startupExample
? `<!-- ${EXCALIDRAW_STARTUP_EXAMPLE} -->\n${startupExample}\n`
: '');
const combined =
AI_TRAINING_INTRO +
'\n---\n\n' +
typeDefContent.trim() +
'\n\n---\n\n' +
additionalTypeDefs +
'\n\n---\n\n' +
scriptLibContent.trim() +
startupSection + // NEW: append startup message + files
'\n';
fs.writeFileSync(AI_TRAINING_OUT, combined, 'utf8');
console.log('[script-library] Wrote:', AI_TRAINING_OUT);
} catch (e) {
console.error('[script-library] Failed to generate AI_TRAINING_OUT:', e);
}
console.log('[script-library] Done.');
}
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: (
+4 -3
View File
@@ -234,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}} = {
+37 -1
View File
@@ -40,7 +40,7 @@ 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 {
@@ -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;
@@ -1077,6 +1079,15 @@ export default class ExcalidrawPlugin extends Plugin {
this.eventManager.setDebounceActiveLeafChangeHandler();
}
private getPathForFile(file: File) {
let path = "";
const { webUtils } = require('electron');
if(webUtils && webUtils.getPathForFile) {
path = webUtils.getPathForFile(file);
}
return path;
}
public registerHotkeyOverrides() {
//this is repeated here because the same function is called when settings is closed after hotkeys have changed
if (this.popScope) {
@@ -1446,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);
}
}
+23 -20
View File
@@ -709,7 +709,7 @@ export class CommandManager {
}
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (view) {
showFrameSettings(getEA(view));
showFrameSettings(view);
return true;
}
return false;
@@ -781,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,
@@ -1281,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) {
@@ -1290,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;
}
@@ -1300,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;
}
@@ -1707,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()
})();
},
});
+1 -1
View File
@@ -9,7 +9,6 @@ import {
import { DEVICE, RERENDER_EVENT } from "../../constants/constants";
import { EmbeddedFilesLoader } from "../../shared/EmbeddedFileLoader";
import { createPNG, createSVG } from "../../utils/excalidrawAutomateUtils";
import { ExportSettings } from "../../view/ExcalidrawView";
import ExcalidrawPlugin from "../main";
import {getIMGFilename,} from "../../utils/fileUtils";
import {
@@ -30,6 +29,7 @@ import { CustomMutationObserver, debug, DEBUGGING } from "../../utils/debugHelpe
import { getExcalidrawFileForwardLinks } from "../../utils/excalidrawViewUtils";
import { linkPrompt } from "../../shared/Dialogs/Prompt";
import { isHTMLElement } from "../../utils/typechecks";
import { ExportSettings } from "src/types/exportUtilTypes";
interface imgElementAttributes {
file?: TFile;
+8 -4
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;
@@ -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
+130 -20
View File
@@ -3,10 +3,8 @@ import {
ButtonComponent,
DropdownComponent,
getIcon,
htmlToMarkdown,
Modifier,
normalizePath,
Notice,
PluginSettingTab,
Setting,
TextComponent,
@@ -26,9 +24,10 @@ import {
} from "src/utils/fileUtils";
import { PENS } from "src/utils/pens";
import {
addIframe,
addYouTubeThumbnail,
fragWithHTML,
setLeftHandedMode,
setTrayMode,
} from "src/utils/utils";
import { imageCache } from "src/shared/ImageCache";
import { MultiOptionConfirmationPrompt } from "src/shared/Dialogs/Prompt";
@@ -98,6 +97,7 @@ export interface ExcalidrawSettings {
penModeDoubleTapEraser: boolean;
penModeSingleFingerPanning: boolean;
penModeCrosshairVisible: boolean;
panWithRightMouseButton: boolean; //mfuria #329
renderImageInMarkdownReadingMode: boolean,
renderImageInHoverPreviewForMDNotes: boolean,
renderImageInMarkdownToPDF: boolean,
@@ -106,6 +106,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;
@@ -175,8 +178,10 @@ export interface ExcalidrawSettings {
}
};
defaultTrayMode: boolean;
compactModeOnTablets: boolean;
previousRelease: string;
showReleaseNotes: boolean;
compareManifestToPluginVersion: boolean;
showNewVersionNotification: boolean;
//mathjaxSourceURL: string;
latexBoilerplate: string;
@@ -283,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,
@@ -355,8 +364,10 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
mdCSS: "",
scriptEngineSettings: {},
defaultTrayMode: true,
compactModeOnTablets: 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}",
@@ -718,6 +729,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")))
@@ -804,7 +827,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
}),
);
addIframe(detailsEl, "jgUpYznHP9A",216);
addYouTubeThumbnail(detailsEl, "jgUpYznHP9A",216);
new Setting(detailsEl)
.setName(t("SCRIPT_FOLDER_NAME"))
@@ -1221,6 +1244,39 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}),
);
detailsEl = displayDetailsEl.createEl("details");
detailsEl.createEl("summary", {
text: t("MODES_HEAD"),
cls: "excalidraw-setting-h3",
});
new Setting(detailsEl)
.setName(t("TRAY_MODE_NAME"))
.setDesc(fragWithHTML(t("ARIA_LABEL_TRAY_MODE")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.defaultTrayMode)
.onChange((value) => {
this.plugin.settings.defaultTrayMode = value;
setTrayMode(this.app, this.plugin.settings);
this.applySettingsUpdate();
})
);
new Setting(detailsEl)
.setName(t("COMPACT_MODE_NAME"))
.setDesc(fragWithHTML(t("COMPACT_MODE_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.compactModeOnTablets)
.onChange((value) => {
this.plugin.settings.compactModeOnTablets = value;
setTrayMode(this.app, this.plugin.settings);
this.applySettingsUpdate();
}),
);
new Setting(detailsEl)
.setName(t("LEFTHANDED_MODE_NAME"))
.setDesc(fragWithHTML(t("LEFTHANDED_MODE_DESC")))
@@ -1236,7 +1292,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
}),
);
addIframe(detailsEl, "H8Njp7ZXYag",999);
addYouTubeThumbnail(detailsEl, "H8Njp7ZXYag",999);
detailsEl = displayDetailsEl.createEl("details");
detailsEl.createEl("summary", {
@@ -1283,7 +1339,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
}),
);
addIframe(detailsEl, "fypDth_-8q0");
addYouTubeThumbnail(detailsEl, "fypDth_-8q0");
new Setting(detailsEl)
.setName(t("IFRAME_MATCH_THEME_NAME"))
@@ -1296,7 +1352,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate(true);
}),
);
addIframe(detailsEl, "ICpoyMv6KSs");
addYouTubeThumbnail(detailsEl, "ICpoyMv6KSs");
new Setting(detailsEl)
.setName(t("MATCH_THEME_NAME"))
@@ -1357,9 +1413,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")))
@@ -1372,7 +1443,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
}),
);
addIframe(detailsEl, "rBarRfcSxNo",107);
addYouTubeThumbnail(detailsEl, "rBarRfcSxNo",107);
new Setting(detailsEl)
.setName(t("DEFAULT_WHEELZOOM_NAME"))
@@ -1425,6 +1496,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
// ------------------------------------------------
@@ -1993,8 +2103,8 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
})
);
addIframe(detailsEl, "yZQoJg2RCKI");
addIframe(detailsEl, "opLd1SqaH_I",8);
addYouTubeThumbnail(detailsEl, "yZQoJg2RCKI");
addYouTubeThumbnail(detailsEl, "opLd1SqaH_I",8);
let dropdown: DropdownComponent;
let embedComment: Setting;
@@ -2153,7 +2263,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
text: t("EXPORT_SUBHEAD"),
cls: "excalidraw-setting-h3",
});
addIframe(detailsEl, "wTtaXmRJ7wg",171);
addYouTubeThumbnail(detailsEl, "wTtaXmRJ7wg",171);
const pdfExportEl = new Setting(detailsEl)
.setName(t("SHOW_DRAWING_OR_MD_IN_EXPORTPDF_NAME"))
@@ -2398,7 +2508,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
cls: "excalidraw-setting-h3",
});
addIframe(detailsEl, "nB4cOfn0xAs");
addYouTubeThumbnail(detailsEl, "nB4cOfn0xAs");
new Setting(detailsEl)
.setName(t("PDF_TO_IMAGE_SCALE_NAME"))
.setDesc(fragWithHTML(t("PDF_TO_IMAGE_SCALE_DESC")))
@@ -2575,7 +2685,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", {
@@ -2609,7 +2719,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
text: t("CUSTOM_PEN_HEAD"),
cls: "excalidraw-setting-h3",
});
addIframe(detailsEl, "OjNhjaH2KjI",69);
addYouTubeThumbnail(detailsEl, "OjNhjaH2KjI",69);
new Setting(detailsEl)
.setName(t("CUSTOM_PEN_NAME"))
.setDesc(t("CUSTOM_PEN_DESC"))
@@ -2651,7 +2761,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
text: t("CUSTOM_FONT_HEAD"),
cls: "excalidraw-setting-h3",
});
addIframe(detailsEl, "eKFmrSQhFA4");
addYouTubeThumbnail(detailsEl, "eKFmrSQhFA4");
new Setting(detailsEl)
.setName(t("ENABLE_FOURTH_FONT_NAME"))
.setDesc(fragWithHTML(t("ENABLE_FOURTH_FONT_DESC")))
@@ -2757,7 +2867,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
cls: "excalidraw-setting-h1",
});
addIframe(detailsEl, "r08wk-58DPk");
addYouTubeThumbnail(detailsEl, "r08wk-58DPk");
new Setting(detailsEl)
.setName(t("LATEX_DEFAULT_NAME"))
.setDesc(fragWithHTML(t("LATEX_DEFAULT_DESC")))
@@ -2855,7 +2965,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
detailsEl.createDiv( { text: t("TASKBONE_DESC"), cls: "setting-item-description" });
let taskboneAPIKeyText: TextComponent;
addIframe(detailsEl, "7gu4ETx7zro");
addYouTubeThumbnail(detailsEl, "7gu4ETx7zro");
new Setting(detailsEl)
.setName(t("TASKBONE_ENABLE_NAME"))
.setDesc(fragWithHTML(t("TASKBONE_ENABLE_DESC")))
@@ -3234,7 +3344,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
cls: "excalidraw-setting-h1",
});
addIframe(detailsEl, "H8Njp7ZXYag",52);
addYouTubeThumbnail(detailsEl, "H8Njp7ZXYag",52);
Object.keys(this.plugin.settings.scriptEngineSettings)
.filter((s) => scripts.contains(s))
.forEach((scriptName: string) => {
+77 -3
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 for the selected image in a popout window",
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,15 @@ 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",
TOGGLE_COMPACT_MODE: "Toggle compact-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",
@@ -222,6 +235,8 @@ export default {
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>" +
@@ -344,7 +359,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>",
@@ -435,12 +450,18 @@ FILENAME_HEAD: "Filename",
"Note: This setting does not affect the PDF export feature within Excalidraw itself.<br>" +
"See the other related setting for <a href='#"+TAG_MDREADINGMODE+"'>Markdown Reading Mode</a> under 'Appearance and Behavior' further above.<br>" +
"⚠️ You must close and reopen the Excalidraw/markdown file for changes to take effect. ⚠️",
MODES_HEAD: "Modes",
TRAY_MODE_NAME: "Enable tray-mode",
COMPACT_MODE_NAME: "Compact-mode on Tablets",
COMPACT_MODE_DESC: "Overrides tray-mode on tablets, allowing the native Excalidraw compact-mode to be used instead.",
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 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>" +
@@ -459,6 +480,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",
@@ -904,6 +931,10 @@ 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 regularly then you may download the fonts locally to your Vault. \n\n" +
@@ -1156,4 +1187,47 @@ FILENAME_HEAD: "Filename",
//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",
};
+78 -3
View File
@@ -58,6 +58,10 @@ export default {
NEW_IN_POPOUT_WINDOW_EMBED: "Crear nuevo bosquejo - EN UNA VENTANA EMERGENTE - e incrustar en el documento activo",
TOGGLE_LOCK: "Alternar Elemento de Texto entre edición RAW y VISTA PREVIA",
DELETE_FILE: "Eliminar imagen o archivo Markdown seleccionado de la Bóveda de Obsidian",
MARKER_FRAME_SHOW: "Mostrar Marker Frames(marcos de marcador)",
MARKER_FRAME_HIDE: "Ocultar Marker Frames(marcos de marcador)",
MARKER_FRAME_TITLE_SHOW: "Mostrar títulos de Marker Frames(marcos de marcador)",
MARKER_FRAME_TITLE_HIDE: "Ocultar títulos de Marker Frames(marcos de marcador)",
COPY_ELEMENT_LINK: "Copiar [[enlace]] para el/los elemento(s) seleccionado(s)",
COPY_DRAWING_LINK: "Copiar ![[enlace incrustado]] de este bosquejo",
INSERT_LINK_TO_ELEMENT:
@@ -134,6 +138,15 @@ export default {
"2) Luego, crea un bosquejo vacío en un nuevo panel haciendo CTRL/CMD+clic en el botón de la barra de Excalidraw,\n" +
"3) y pega tu trabajo en el nuevo documento con CTRL/CMD+V.",
ARIA_LABEL_TRAY_MODE: "El modo bandeja ofrece un lienzo alternativo y más espacioso",
TRAY_TRAY_MODE: "Activar/desactivar modo bandeja",
TOGGLE_COMPACT_MODE: "Alternar modo compacto",
TRAY_SCRIPT_LIBRARY: "Biblioteca de scripts",
TRAY_SCRIPT_LIBRARY_ARIA: "Explorar la biblioteca de scripts de Excalidraw",
TRAY_EXPORT: "Exportar imagen...",
TRAY_EXPORT_ARIA: "Exportar imagen como archivo PNG, SVG o Excalidraw",
TRAY_SAVE: "Guardar",
TRAY_SWITCH_TO_MD: "Abrir como Markdown",
TRAY_SWITCH_TO_MD_ARIA: "Cambiar a vista de Markdown",
MASK_FILE_NOTICE: "Este es un archivo de máscara. Se usa para recortar y enmascarar partes de la imagen. Mantén presionado el aviso para abrir el video de ayuda.",
INSTALL_SCRIPT_BUTTON: "Instalar o actualizar scripts de Excalidraw",
OPEN_AS_MD: "Abrir como Markdown",
@@ -178,7 +191,7 @@ export default {
WELCOME_COMMAND_PALETTE: 'Escribe "Excalidraw" en la Paleta de Comandos',
WELCOME_OBSIDIAN_MENU: "Explora el Menú de Obsidian en la esquina superior derecha",
WELCOME_SCRIPT_LIBRARY: "Visita la Librería de Scripts",
WELCOME_HELP_MENU: "Encuentra ayuda en el menú_de_hamburguesa",
WELCOME_HELP_MENU: "Encuentra ayuda en el menú de la esquina superior izquierda",
WELCOME_YOUTUBE_ARIA: "Canal de YouTube de PKM Visual",
WELCOME_YOUTUBE_LINK: "Echa un vistazo al canal de YouTube de PKM Visual.",
WELCOME_DISCORD_ARIA: "Únete al servidor de Discord",
@@ -222,6 +235,8 @@ export default {
RELEASE_NOTES_DESC:
"<b><u>Activado:</u></b> Muestra las notas de la versión cada vez que actualices Excalidraw a una versión más reciente.<br>" +
"<b><u>Desactivado:</u></b> Modo silencioso. Aún puedes leer las notas de la versión en <a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/releases'>GitHub</a>.",
WARN_ON_MANIFEST_MISMATCH_NAME: "Advertir sobre actualizaciones de complementos incompletos",
WARN_ON_MANIFEST_MISMATCH_DESC: "Comprueba que el ejecutable de Excalidraw instalado coincida con la versión mostrada en la lista de complementos de Obsidian. Si no coinciden (a menudo después de una sincronización parcial), verás una advertencia y podrás actualizar. Desactívalo para dejar de comprobar.",
NEWVERSION_NOTIFICATION_NAME: "Notificación de Actualización del Complemento",
NEWVERSION_NOTIFICATION_DESC:
"<b><u>Activado:</u></b> Muestra una notificación cuando hay una nueva versión del complemento disponible.<br>" +
@@ -419,7 +434,8 @@ FILENAME_HEAD: "Nombre de archivo",
SHOW_DRAWING_OR_MD_IN_HOVER_PREVIEW_DESC:
"...incluso si el archivo tiene la clave frontmatter <b>excalidraw-open-md: true</b>.<br>" +
"Cuando esta configuración está desactivada y el archivo está configurado para abrirse en Markdown por defecto, " +
"la vista previa al pasar el mouse mostrará el lado Markdown del documento.",
"la vista previa al pasar el mouse mostrará el lado Markdown del documento.<br>" +
"Nota: <b>excalidraw-open-md</b> es diferente de <b>excalidraw-embed-md</b>. Si <b>excalidraw-embed-md</b> está establecido en true, a vista previa al pasar el mouse siempre mostrará el lado Markdown, sin importar esta configuración. Para forzar la renderización de la imagen al incrustar, usa <code>![[drawing#^as-image]]</code> en tu archivo Markdown.",
SHOW_DRAWING_OR_MD_IN_READING_MODE_NAME: "Renderizar como imagen en el modo de lectura Markdown de un archivo de Excalidraw",
SHOW_DRAWING_OR_MD_IN_READING_MODE_DESC:
"Cuando estás en modo de lectura Markdown (es decir, leyendo el reverso del bosquejo), ¿debe renderizarse el bosquejo de Excalidraw como una imagen? " +
@@ -434,12 +450,18 @@ FILENAME_HEAD: "Nombre de archivo",
"Nota: Esta configuración no afecta la función de exportación a PDF dentro del propio Excalidraw.<br>" +
"Consulta la otra configuración relacionada para el <a href='#"+TAG_MDREADINGMODE+"'>Modo de Lectura de Markdown</a> en 'Apariencia y Comportamiento' más arriba.<br>" +
"⚠️ Debes cerrar y volver a abrir el archivo de Excalidraw/Markdown para que los cambios surtan efecto. ⚠️",
MODES_HEAD: "Modos",
TRAY_MODE_NAME: "Habilitar modo de bandeja (tray-mode)",
COMPACT_MODE_NAME: "Modo compacto en tablets",
COMPACT_MODE_DESC: "Anula el modo de bandeja en tablets, permitiendo que se use en su lugar el modo compacto nativo de Excalidraw.",
HOTKEY_OVERRIDE_HEAD: "Anulaciones de atajos de teclado",
HOTKEY_OVERRIDE_DESC: `Algunos de los atajos de teclado de Excalidraw, como <code>${labelCTRL()}+Enter</code> para editar texto o <code>${labelCTRL()}+K</code> para crear un enlace de elemento ` +
"entran en conflicto con la configuración de atajos de teclado de Obsidian. Las combinaciones de atajos de teclado que agregues a continuación anularán la configuración de atajos de teclado de Obsidian mientras usas Excalidraw. Por lo tanto, " +
`puedes agregar <code>${labelCTRL()}+G</code> si quieres que el comportamiento predeterminado sea Agrupar Objeto en Excalidraw en lugar de abrir la Vista de Gráfico.`,
THEME_HEAD: "Tema y estilo",
ZOOM_HEAD: "Zoom",
ZOOM_AND_PAN_HEAD: "Zoom y panorámica",
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "Desplazar el lienzo con el botón derecho del mouse (abrir menú con 'm')",
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC: "Cuando está habilitado, puedes desplazar el lienzo haciendo clic derecho y arrastrando. El menú contextual se abrirá con la tecla 'm', a menos que estés editando texto.",
DEFAULT_PINCHZOOM_NAME: "Permitir zoom con pellizco en modo lápiz",
DEFAULT_PINCHZOOM_DESC:
"El zoom con pellizco en modo lápiz, al usar la herramienta de dibujo a mano alzada, está deshabilitado por defecto para evitar zooms accidentales no deseados con la palma de la mano.<br>" +
@@ -458,6 +480,12 @@ FILENAME_HEAD: "Nombre de archivo",
ZOOM_TO_FIT_MAX_LEVEL_NAME: "Nivel máximo de zoom para ajustar",
ZOOM_TO_FIT_MAX_LEVEL_DESC:
"Establece el nivel máximo al que el zoom para encajar agrandará el bosquejo. El mínimo es 0.5 (50%) y el máximo es 10 (1000%).",
ZOOM_STEP_NAME: "Incremento del zoom",
ZOOM_STEP_DESC: "Incremento del zoom (en puntos porcentuales) para acciones como el zoom con la rueda del ratón. Valores más pequeños dan un control más preciso, pero pueden requerir un desplazamiento excesivo. Predeterminado: 5%.",
ZOOM_MIN_NAME: "Zoom mínimo",
ZOOM_MIN_DESC: "Qué tanto puedes alejarte con el zoom (para que quepa más del bosquejo en la pantalla). Predeterminado: 10%. Históricamente, los valores por debajo del 10% eran inestables; bájalo con precaución y restablece a 10% si surgen problemas.",
ZOOM_MAX_NAME: "Zoom máximo",
ZOOM_MAX_DESC: "Límite superior del zoom. Predeterminado: 3000%. Por lo general, no es necesario cambiarlo; se incluye para ser exhaustivos.",
PEN_HEAD: "Lápiz",
GRID_HEAD: "Cuadrícula",
GRID_DYNAMIC_COLOR_NAME: "Color de cuadrícula dinámica",
@@ -903,6 +931,10 @@ FILENAME_HEAD: "Nombre de archivo",
SCRIPT_EXECUTION_ERROR:
"Error de ejecución del script. Por favor, revisa la consola del desarrollador para ver el mensaje de error.",
//ExcalidrawViewUtils.ts
MARKER_FRAME_RENDERING_DISABLED_NOTICE: "Hay marker-frames (marcos de marcador) ocultos en la escena.",
//DRAWING_HAS_BACK_OF_THE_CARD: "Hay notas en el reverso de este dibujo.",
//ExcalidrawData.ts
LOAD_FROM_BACKUP: "El archivo de Excalidraw estaba dañado. Cargando desde el archivo de backup(copia de seguridad).",
FONT_LOAD_SLOW: "Cargando fuentes...\n\n Esto está tomando más tiempo de lo esperado. Si este retraso ocurre regularmente, puedes descargar las fuentes de forma local en tu Bóveda. \n\n" +
@@ -1155,4 +1187,47 @@ FILENAME_HEAD: "Nombre de archivo",
//exportUtils.ts
PDF_EXPORT_DESKTOP_ONLY: "La exportación a PDF solo está disponible en escritorio.",
//UniversalInsertFileModal.ts
UIFM_TITLE: "Insertar archivo desde la bóveda",
UIFM_SECTION_HEAD: "Seleccionar encabezado de sección",
UIFM_ANCHOR: "Anclar al 100% del tamaño original",
UIFM_ANCHOR_DESC: "Esta es una función Pro, úsala solo si entiendes cómo funciona. Si se activa, incluso si cambias el tamaño de la imagen importada en Excalidraw, la próxima vez que abras el dibujo, la imagen volverá al 100% de su tamaño. Esto es útil para incrustar una idea atómica de Excalidraw en otra nota y preservar el tamaño relativo del texto y los íconos.",
UIFM_BTN_EMBEDDABLE: "como Incrustable",
UIFM_BTN_PDF: "como Pdf",
UIFM_BTN_IMAGE: "como Imagen",
//ReleaseNotes.ts
RN_WELCOME: "Bienvenido a Excalidraw",
//Excalidraw component
COMP_IMG: "Imágenes y archivos",
COMP_IMG_FROM_SYSTEM: "Importar desde el sistema",
COMP_IMG_ANY_FILE: "Cualquier archivo de la bóveda",
COMP_IMG_LaTeX: "Fórmula de LaTeX",
COMP_FRAME: "Acciones de Frame(marco)",
COMP_FRAME_HINT: "Activar/desactivar Marker-Frame (marco de marcador). Marcos de guía para definir diapositivas/áreas de impresión/referencias de imagen. " +
"Se ocultan en las exportaciones de imágenes y no contienen elementos. Oculta/muestra los marcos desde el menú contextual del lienzo.",
//CustomEmbeddable.tsx
NOTICE_PDF_THEME: "Sobreescritura de Tema de PDF .\n" +
"Controla esto a través de la propiedad de documento 'excalidraw-embeddable-theme' de este archivo (anula la configuración del complemento).\n\n" +
"Valores: dark, light, auto=Excalidraw, default=Obsidian.",
//EmbeddableActionsMenu.tsx
BOOKMARK_PAGE: "Guardar posición actual en el documento",
CAPTURE_PAGE: "Capturar la página actual como imagen",
//VersionMismatch.ts
//ADVERTENCIA: No cambie las cadenas {VAL_RECORDED} y {VAL_ACTUAL}, ¡son reemplazadas por los valores de versión reales en tiempo de ejecución!
VERSION_MISMATCH_NOTICE: `La versión registrada por Obsidian es <b>{VAL_RECORDED}</b>, pero el código de Excalidraw instalado es <b>{VAL_ACTUAL}</b>.`,
VERSION_MISMATCH_HEADING: "Desajuste de versión de Excalidraw",
VERSION_MISMATCH_CAUSE: "Esto suele ocurrir después de una sincronización parcial (ej. Obsidian Sync Standard) donde archivos grandes (main.js > 5MB) no se sincronizaron, por lo que solo se actualizó <code>manifest.json</code> .",
VERSION_MISMATCH_OPTIONS: "Opciones:<br><b>1.</b> Vuelva a descargar el complemento (recomendado).<br><b>2.</b> Ignorar por ahora.",
VERSION_MISMATCH_NOTE: "Nota: Actualizar la información de la versión manualmente puede afectar a las herramientas que leen manifest.json directamente (ej. Plugin Update Tracker, BRAT) hasta una reinstalación completa.",
VERSION_MISMATCH_DISABLE_NAME: "Desactivar futuras advertencias de desajuste",
VERSION_MISMATCH_DISABLE_DESC: "Puede volver a habilitar esto en: Opciones → Excalidraw → Básico → Advertir sobre actualizaciones de complementos incompletos.",
VERSION_MISMATCH_REDOWNLOAD: "Volver a descargar complemento",
VERSION_MISMATCH_IGNORE: "Ignorar",
};
+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>" +
+596 -521
View File
File diff suppressed because it is too large. Load diff
+600 -525
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -6,9 +6,9 @@ import { Notice } from "obsidian";
import { getEA } from "src/core";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { cloneElement } from "src/utils/excalidrawAutomateUtils";
import { ExportSettings } from "src/view/ExcalidrawView";
import { nanoid } from "src/constants/constants";
import { svgToBase64 } from "../utils/utils";
import { ExportSettings } from "src/types/exportUtilTypes";
/**
* Creates a masked image from an Excalidraw scene.
+1 -1
View File
@@ -50,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);
+2 -1
View File
@@ -6,7 +6,8 @@ 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, exportPNG, exportPNGToClipboard } from "src/utils/exportUtils";
import { exportSVGToClipboard, exportPNG, exportPNGToClipboard } from "src/utils/exportUtils";
import { PageOrientation, PageSize, PDFPageAlignment, PDFPageMarginString } from "src/types/exportUtilTypes";
import { t } from "src/lang/helpers";
import { PDFExportSettings, PDFExportSettingsComponent } from "./PDFExportSettingsComponent";
import { captureScreenshot } from "src/utils/screenshot";
+130 -27
View File
@@ -4,10 +4,15 @@ export class FloatingModal extends Modal {
private dragging = false;
private offsetX = 0;
private offsetY = 0;
private pointerDownHandler: (e: PointerEvent) => void;
private pointerMoveHandler: (e: PointerEvent) => void;
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);
@@ -15,40 +20,82 @@ export class FloatingModal extends Modal {
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): void {
private handlePointerDown(e: PointerEvent | TouchEvent): void {
// Get the target element
const target = e.target as HTMLElement;
// Ignore if clicking on interactive elements
if (
e.target instanceof HTMLInputElement ||
e.target instanceof HTMLTextAreaElement ||
e.target instanceof HTMLSelectElement ||
e.target instanceof HTMLButtonElement ||
(e.target as HTMLElement).closest(".clickable-icon")
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement ||
target instanceof HTMLSelectElement ||
target instanceof HTMLButtonElement ||
target.closest(".clickable-icon")
) {
return;
}
this.dragging = true;
const { modalEl } = this;
this.offsetX = e.clientX - modalEl.getBoundingClientRect().left;
this.offsetY = e.clientY - modalEl.getBoundingClientRect().top;
// For touch events, prevent default behavior to avoid Obsidian's handling
if (e.type === "touchstart") {
e.preventDefault();
e.stopPropagation();
// Add global event listeners for move and up events
document.addEventListener("pointermove", this.pointerMoveHandler);
document.addEventListener("pointerup", this.pointerUpHandler);
// Capture the pointer to ensure we get events even when outside the target
(e.target as HTMLElement).setPointerCapture(e.pointerId);
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): void {
private handlePointerMove(e: PointerEvent | TouchEvent): void {
if (!this.dragging) return;
const { modalEl } = this;
// Prevent default behavior
e.preventDefault();
if (e.type === "touchmove") e.stopPropagation();
const x = e.clientX - this.offsetX;
const y = e.clientY - this.offsetY;
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`;
@@ -58,17 +105,42 @@ export class FloatingModal extends Modal {
private handlePointerUp(): void {
this.dragging = false;
document.removeEventListener("pointermove", this.pointerMoveHandler);
// 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 } = this;
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) {
@@ -84,22 +156,53 @@ export class FloatingModal extends Modal {
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 pointer down listener to start dragging
modalEl.addEventListener("pointerdown", this.pointerDownHandler);
// 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);
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 });
}
document.removeEventListener("pointermove", this.pointerMoveHandler);
document.removeEventListener("pointerup", this.pointerUpHandler);
// 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> {
+4 -1
View File
@@ -439,7 +439,10 @@ export class InsertPDFModal extends Modal {
if(this.frame) {
const frameID = ea.addFrame(topX, topY,imgWidth,imgHeight,`${page}`);
ea.addElementsToFrame(frameID, [boxID,imageID]);
const frameEl = ea.getElement(frameID) as any;
frameEl.frameRole = "marker";
ea.addToGroup([frameID,boxID,imageID]);
//ea.addElementsToFrame(frameID, [boxID,imageID]);
ea.getElement(frameID).link = this.pdfFile.path + `#page=${page}`;
}
+173 -309
View File
@@ -5,331 +5,195 @@ If you'd like to learn more, please subscribe to my YouTube channel: [Visual PKM
Thank you & Enjoy!
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/P_Q6avJGoWI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
<div class="excalidraw-videoWrapper">
<a href="https://www.youtube.com/watch?v=P_Q6avJGoWI" target="_blank"><img src ="https://i.ytimg.com/vi/P_Q6avJGoWI/maxresdefault.jpg" style="width:100%;"></a>
</div>
`;
export const RELEASE_NOTES: { [k: string]: string } = {
Intro: `After each update, you’ll see these release notes (you can turn this off in the plugin settings).
Intro: `After each update, you'll see these release notes (you can turn this off in the plugin settings).
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.14.1":`
"2.17.0":`
## New
- New frontmatter option \`excalidraw-embed-md\`. When set to \`true\`, embedding this Excalidraw file into another markdown file will display its markdown content (the "back of the note") instead of rendering it as an image.
- Phone UI from Excalidraw.com [#9996](https://github.com/excalidraw/excalidraw/pull/9996)
## Fixed
- side panel does not attach correctly when library is pinned [#2510](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2510)
- Fixed print area when using marker frames and printing Slideshow to PDF
- The Invert Colors script and ExcalidrawAutomate bugs that resulted in broken colors and Excalidarw crash in some cases after color inversion.
- Fixed duplicated PDF elements after copy-pasting from scene to scene.
`,
"2.16.1":`
## Fixed
- Based on a request from [Kevin](https://github.com/Kovah) referencing GDPR, I removed YouTube iframes from settings, scripts, etc., and replaced them with thumbnail images + links to YouTube. [#2234](https://github.com/zsviczian/obsidian-excalidraw-plugin/discussions/2234)`,
"2.16.0":`
<div class="excalidraw-videoWrapper">
<a href="https://www.youtube.com/watch?v=51EgDgtiZgQ" target="_blank"><img src ="https://i.ytimg.com/vi/51EgDgtiZgQ/maxresdefault.jpg" style="width:100%;"></a>
</div>
## New from Excalidraw.com
- New library search feature [#9903](https://github.com/excalidraw/excalidraw/pull/9903)
- You can rename library items by selecting them, then choosing "Rename or publish" from the ... menu.
- New compact mode for tablets [#9910](https://github.com/excalidraw/excalidraw/pull/9910)
- New setting in plugin setting \`Compact-mode on Tablets\` to override tray-mode on tablets in favor of the new compact mode.
## New
- Embedding PDF as images, frames are now marker frames instead of regular frames. You can reference pages, including their markup in markdown notes, using this syntax: \`![[drawing#^frame=12]]\` (page 12)
- Pinned scripts toolbar is now on the right side in all modes: tray-, normal-, and compact. The toolbar moves into view when the side panel is opened for the stencil library or for search.
- Better RTL support, pinned scripts are rendered on the left side in RTL mode.
## Fixed
- Critical fix: When clicking to follow a link in a markdown embeddable in preview mode to open an Excalidraw drawing in the same tab, the back of the newly opened drawing was overwritten with the content of the source drawing.
- PDF++ Links from document to Excalidraw select everything in the scene instead of the linked element. [#2503](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2503)
`,
"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">
<a href="https://www.youtube.com/watch?v=DqDnzCOoYMc" target="_blank"><img src ="https://i.ytimg.com/vi/DqDnzCOoYMc/maxresdefault.jpg" style="width:100%;"></a>
</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">
<a href="https://www.youtube.com/watch?v=29EWeglRm7s" target="_blank"><img src ="https://i.ytimg.com/vi/29EWeglRm7s/maxresdefault.jpg" style="width:100%;"></a>
</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">
<a href="https://www.youtube.com/watch?v=A_udjVjgWN0" target="_blank"><img src ="https://i.ytimg.com/vi/A_udjVjgWN0/maxresdefault.jpg" style="width:100%;"></a>
</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).
## Fixed
- 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.
`,
"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)
- Add container to multiple text elements [#9348](https://github.com/excalidraw/excalidraw/pull/9348)
## Fixed from Excalidraw.com
- Rounded diamond edge elbow arrow U route [#9349](https://github.com/excalidraw/excalidraw/pull/9349)
- Improved eraser performance [#9352](https://github.com/excalidraw/excalidraw/pull/9352)
- Keep arrow label horizontal [#9364](https://github.com/excalidraw/excalidraw/pull/9364)
## Fixed in ExcalidrawAutomate
- ${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)
`,
"2.9.1":`
- Minor emergency fix. Reverting: [#9203](https://github.com/excalidraw/excalidraw/pull/9203)
`,
"2.9.0":`
## New
- QoL improvement: The context menu requires a longer press and hold for it to be displayed on mobile devices. When you want to precision adjust an element it happens that you linger on the point for just a little longer and the context menu appears unwantedly.
- Elbow arrow improvements [#9236](https://github.com/excalidraw/excalidraw/pull/9236), [#8593](https://github.com/excalidraw/excalidraw/pull/8593), [#9197](https://github.com/excalidraw/excalidraw/pull/9197), [#9191](https://github.com/excalidraw/excalidraw/pull/9191), [#9236](https://github.com/excalidraw/excalidraw/pull/9236)
## Fixed Obsidian 1.8.9 regressions
- Custom references (like #^group) broken in Live Preview in Obsidian 1.8.9 due to translation update [#2279](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2279)
- Excalidraw tabs only show on a second click on Obsidian Mobile
## Refactoring
- The Excalidraw component moved to React 19. Obsidian for now remains on React 18. This refactoring ensures that Excalidraw continues to work in Obsidian and Obsidian will receive future Excalidraw updates. [#9182](https://github.com/excalidraw/excalidraw/pull/9182)
`,
"2.8.3":`
## Fixed
- Chinese translation not available since 2.8.0. [#2247](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2247)
- Since the most recent Samsung Android update, adding images from the gallery returns an Unsupported Image Type error. [#2245](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2245)
- Duplicating/removing frame while children selected [#9079](https://github.com/excalidraw/excalidraw/pull/9079)
`,
"2.8.2":`
## New
- Moved "Create new drawing" option up in the context menu [#2243](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2243)
## Fixed
- In rare cases drawing content gets overwritten with another drawing [#2152](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2152)
- "Wrap selection in frame" sets dark mode to light mode [#2240](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2240)
- Multiple bug fixes from Excalidraw.com
- Elbow arrows within boxes [#9077](https://github.com/excalidraw/excalidraw/issues/9077)
- Elbow arrow orthogonality [#9073](https://github.com/excalidraw/excalidraw/pull/9073)
- Improve library sidebar performance [#9060](https://github.com/excalidraw/excalidraw/pull/9060)
- Opacity slider now displays numerical value [#9009](https://github.com/excalidraw/excalidraw/pull/9009)
- Resize a frame and its children together when box selecting the frame and its children together [#9031](https://github.com/excalidraw/excalidraw/pull/9031)
- Excalidraw screen flickering in dark mode [#9057](https://github.com/excalidraw/excalidraw/pull/9057)
`,
"2.8.1":`
## Fixed
- Unable to open Excalidraw files after the 2.8.0 update. [#2235](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2235)
`,
"2.8.0":`
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/tWi5xTUTz7E" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
## New
- Updated "Export Image" dialog
- 🚀 PDF Export option including tiling of images over multiple pages. Only available on desktop :(
- SVG to clipboard
- More granular setting for padding and scale
- Slideshow script can now print slides to PDF (update script from script store)
- Set local graph to show the links in the embeddable when it is activated/deactivated [#2200](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2200)
## Fixed
- Fixed several LaTeX issues. 🙏 @Sintuz [#1631](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1631), [#2195](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2195), [#1842](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1842)
- Fixed support for *.jfif and *.avif images [#2212](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2212)
- PDF++ selection is not correctly showing after embedded into a drawing (for some specific files) [#2213](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2213)
- iOS 18 can't upload image and library [#2182](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2182)
- Image block references are broken in hover previews [#2218](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2218)
- ⚠️ Note there is a known issue in Obsidian 1.8.2 ⚠️ affecting preview windows in Excalidraw. I received confirmation that this will be fixed in 1.8.3. For now, if hover previews are important to you, you can downgrade to Obsidian 1.8.1 [#2228](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2225)
- Mobile elements panel and context menu are not scrollable [#2216](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2216)
- "Local Font" menu disappears when opening a drawing in an Obsidian popout-window [#2205](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2205)
## Updates from Excalidraw.com
- Pressing delete on a frame will only delete the children [#9011](https://github.com/excalidraw/excalidraw/pull/9011)
- New crowfoot arrowheads and a new arrowhead picker [#8942](https://github.com/excalidraw/excalidraw/pull/8942)
- Fixed some of the arrow binding issues [#9010](https://github.com/excalidraw/excalidraw/pull/9010), [#2209](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2209)
- New context menu action: "Wrap selection in frame" [#9005](https://github.com/excalidraw/excalidraw/pull/9005)
- Elbow arrow segment fixing and positioning [#8952](https://github.com/excalidraw/excalidraw/pull/8952)
- When drag creating a new frame, do not add a partial group to it. When wrapping a selected partial group in a frame however, do add it to the wrapping frame. But such that it should be separated from the previous containing group. [#9014](https://github.com/excalidraw/excalidraw/pull/9014)
## New in ExcalidrawAutomate
- New hook: ${String.fromCharCode(96)}onImageFileNameHook${String.fromCharCode(96)}. When set, this callback is triggered when a image is being saved in Excalidraw.
- PDF export functions, paving the way for slideshow to export slides to PDF
${String.fromCharCode(96,96,96)}ts
/**
* Returns the dimensions of a standard page size in pixels.
*/
function getPagePDFDimensions(
pageSize: PageSize,
orientation: PageOrientation
): PageDimensions;
/**
* Creates a PDF from the provided SVG elements with specified scaling and page properties.
*/
function createPDF(props: {
SVG: SVGSVGElement[];
scale?: PDFExportScale;
pageProps?: PDFPageProperties;
filename: string;
}): Promise<void>;
/**
* Creates an SVG representation of the current view.
*/
function createViewSVG(props : {
withBackground?: boolean;
theme?: "light" | "dark";
frameRendering?: FrameRenderingOptions;
padding?: number;
selectedOnly?: boolean;
skipInliningFonts?: boolean;
embedScene?: boolean;
}): Promise<SVGSVGElement>;
/**
* If set, this callback is triggered when a image is being saved in Excalidraw.
* You can use this callback to customize the naming and path of pasted images to avoid
* default names like "Pasted image 123147170.png" being saved in the attachments folder,
* and instead use more meaningful names based on the Excalidraw file or other criteria,
* plus save the image in a different folder.
*
* If the function returns null or undefined, the normal Excalidraw operation will continue
* with the excalidraw generated name and default path.
* If a filepath is returned, that will be used. Include the full Vault filepath and filename
* with the file extension.
* The currentImageName is the name of the image generated by excalidraw or provided during paste.
*/
function onImageFilePathHook: (data: {
currentImageName: string;
drawingFilePath: string;
}) => string = null;
${String.fromCharCode(96,96,96)}
`,
};
@@ -1,5 +1,5 @@
import { Setting } from "obsidian";
import { PageOrientation, PageSize, PDFPageAlignment, PDFPageMarginString, STANDARD_PAGE_SIZES } from "src/utils/exportUtils";
import { PageOrientation, PageSize, PDFPageAlignment, PDFPageMarginString, STANDARD_PAGE_SIZES } from "src/types/exportUtilTypes";
import { t } from "src/lang/helpers";
export interface PDFExportSettings {
+2 -2
View File
@@ -369,7 +369,7 @@ export class PenSettingsModal extends Modal {
.setName(fragWithHTML(`Stroke Width <b>${ps.strokeWidth === 0 ? "Not Set" : ps.strokeWidth}</b>`))
.addSlider(slider =>
slider
.setLimits(0,5,0.5)
.setLimits(0,5,0.1)
.setValue(ps.strokeWidth)
.onChange(value => {
this.dirty = true;
@@ -421,7 +421,7 @@ export class PenSettingsModal extends Modal {
.setDesc("If the stroke has an outline, this will mean the stroke color is the outline color, and the background color is the pen stroke's fill color. If the pen does not have an outline then the pen color is the stroke color. The Fill Style setting applies to the fill style of the enclosed shape, not of the line itself. The line can only have solid fill.")
.addSlider(slider =>
slider
.setLimits(0,8,0.5)
.setLimits(0,8,0.1)
.setValue(ps.penOptions.outlineWidth)
.onChange(value => {
this.dirty = true;
+1
View File
@@ -1011,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,
+2 -2
View File
@@ -1,7 +1,7 @@
import { Modal, Setting, TFile } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
import { getIMGFilename } from "src/utils/fileUtils";
import { addIframe } from "src/utils/utils";
import { addYouTubeThumbnail } from "src/utils/utils";
const haveLinkedFilesChanged = (depth: number, mtime: number, path: string, sourceList: Set<string>, plugin: ExcalidrawPlugin):boolean => {
if(depth++ > 5) return false;
@@ -67,7 +67,7 @@ export class PublishOutOfDateFilesDialog extends Modal {
text: "Video about Obsidian Publish support",
});
detailsEl.createEl("br");
addIframe(detailsEl, "JC1E-jeiWhI");
addYouTubeThumbnail(detailsEl, "JC1E-jeiWhI");
const p = this.contentEl.createEl("p",{text: "Collecting data..."});
const statusEl = this.contentEl.createEl("p", {text: "Status: "});
const files = await listOfOutOfSyncImgExports(this.plugin, recursive, statusEl);
+7 -2
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,10 +17,14 @@ 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() {
+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();
+15 -3
View File
@@ -611,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,};",
@@ -813,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: "",
},
{
@@ -826,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;",
@@ -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);
}
}
}
+39 -59
View File
@@ -2,7 +2,7 @@
//https://img.youtube.com/vi/uZz5MgzWXiM/maxresdefault.jpg
import { ExcalidrawElement, FileId } from "@zsviczian/excalidraw/types/element/src/types";
import { BinaryFileData, DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import { App, MarkdownRenderer, Notice, TFile } from "obsidian";
import {
DEFAULT_MD_EMBED_CSS,
@@ -15,7 +15,6 @@ import {
} from "../constants/constants";
import { createSVG } from "src/utils/excalidrawAutomateUtils";
import { ExcalidrawData, getTransclusion } from "./ExcalidrawData";
import { ExportSettings } from "../view/ExcalidrawView";
import { t } from "../lang/helpers";
import { tex2dataURL } from "./LaTeX";
import ExcalidrawPlugin from "../core/main";
@@ -39,11 +38,12 @@ import {
promiseTry,
PromisePool,
} from "../utils/utils";
import { ValueOf } from "../types/types";
import { getMermaidImageElements, getMermaidText, shouldRenderMermaid } from "../utils/mermaidUtils";
import { mermaidToExcalidraw } from "src/constants/constants";
import { ImageKey, imageCache } from "./ImageCache";
import { FILENAMEPARTS, PreviewImageType } from "../types/utilTypes";
import { ColorMap, ImgData, PDFPageViewProps, Size, MimeType, FileData } from "src/types/embeddedFileLoaderTypes";
import { ExportSettings } from "src/types/exportUtilTypes";
//An ugly workaround for the following situation.
//File A is a markdown file that has an embedded Excalidraw file B
@@ -54,54 +54,7 @@ import { FILENAMEPARTS, PreviewImageType } from "../types/utilTypes";
//and getObsidianImage is aborted if the file is already in the Watchdog stack
const markdownRendererRecursionWatcthdog = new Set<TFile>();
export const IMAGE_MIME_TYPES = {
svg: "image/svg+xml",
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
gif: "image/gif",
webp: "image/webp",
bmp: "image/bmp",
ico: "image/x-icon",
avif: "image/avif",
jfif: "image/jfif",
} as const;
type ImgData = {
mimeType: MimeType;
fileId: FileId;
dataURL: DataURL;
created: number;
hasSVGwithBitmap: boolean;
size: Size;
pdfPageViewProps?: PDFPageViewProps;
};
export declare type MimeType = ValueOf<typeof IMAGE_MIME_TYPES> | "application/octet-stream";
export type FileData = BinaryFileData & {
size: Size;
hasSVGwithBitmap: boolean;
shouldScale: boolean; //true if image should maintain its area, false if image should display at 100% its size
pdfPageViewProps?: PDFPageViewProps;
};
export type PDFPageViewProps = {
left: number;
bottom: number;
right: number;
top: number;
rotate?: number; //may be undefined in legacy files
}
export type Size = {
height: number;
width: number;
};
export interface ColorMap {
[color: string]: string;
};
/**
* Function takes an SVG and replaces all fill and stroke colors with the ones in the colorMap
@@ -201,6 +154,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 +235,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 +248,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 +266,7 @@ export class EmbeddedFile {
return false;
}
}
if (this.isSVGwithBitmap && isDark) {
if (this.hasSeparateDarkAndLightVersion && isDark) {
return this.imgInverted !== "";
}
return this.img !== "";
@@ -319,7 +276,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 +565,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 +632,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 +884,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 +1192,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) {
+132 -36
View File
@@ -13,10 +13,10 @@ import {
ExcalidrawFrameElement,
ExcalidrawTextContainer,
} from "@zsviczian/excalidraw/types/element/src/types";
import { ColorMap, MimeType } from "./EmbeddedFileLoader";
import { ColorMap, MimeType } from "../types/embeddedFileLoaderTypes";
import { Editor, Notice, OpenViewState, RequestUrlResponse, TFile, TFolder, WorkspaceLeaf } from "obsidian";
import * as obsidian_module from "obsidian";
import ExcalidrawView, { ExportSettings, TextMode } from "src/view/ExcalidrawView";
import ExcalidrawView, { TextMode } from "src/view/ExcalidrawView";
import { ExcalidrawData, getMarkdownDrawingSection } from "./ExcalidrawData";
import {
FRONTMATTER,
@@ -73,7 +73,6 @@ import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import PolyBool from "polybooljs";
import { EmbeddableMDCustomProps } from "./Dialogs/EmbeddableSettings";
import {
AIRequest,
postOpenAI as _postOpenAI,
extractCodeBlocks as _extractCodeBlocks,
} from "../utils/AIUtils";
@@ -84,11 +83,15 @@ import { ExcalidrawLib } from "../types/excalidrawLib";
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 { exportToPDF, getMarginValue, getPageDimensions } from "src/utils/exportUtils";
import { PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFPageProperties, ExportSettings} from "src/types/exportUtilTypes";
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";
import { AIRequest } from "src/types/AIUtilTypes";
extendPlugins([
HarmonyPlugin,
@@ -475,7 +478,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;
}
@@ -485,6 +488,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};
}
@@ -555,6 +561,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.
@@ -832,59 +857,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 ?? {},
};
@@ -1041,6 +1067,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({
@@ -1051,6 +1078,7 @@ export class ExcalidrawAutomate {
selectedOnly = false,
skipInliningFonts = false,
embedScene = false,
elementsOverride,
} : {
withBackground?: boolean,
theme?: "light" | "dark",
@@ -1059,6 +1087,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");
@@ -1067,6 +1096,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,
@@ -1240,6 +1272,36 @@ export class ExcalidrawAutomate {
return wrapTextAtCharLength(text, lineLen, this.plugin.settings.forceWrap);
};
/** ROUNDNESS as defined in the Excalidraw packages/common/src/constants.ts
* Radius represented as 25% of element's largest side (width/height).
* Used for LEGACY and PROPORTIONAL_RADIUS algorithms, or when the element is
* below the cutoff size.
* export const DEFAULT_PROPORTIONAL_RADIUS = 0.25;
*
* Fixed radius for the ADAPTIVE_RADIUS algorithm. In pixels.
* export const DEFAULT_ADAPTIVE_RADIUS = 32;
*
* roundness type (algorithm)
* export const ROUNDNESS = {
* Used for legacy rounding (rectangles), which currently works the same
* as PROPORTIONAL_RADIUS, but we need to differentiate for UI purposes and
* forwards-compat.
* LEGACY: 1,
*
* Used for linear elements & diamonds
* PROPORTIONAL_RADIUS: 2,
*
* Current default algorithm for rectangles, using fixed pixel radius.
* It's working similarly to a regular border-radius, but attemps to make
* radius visually similar across differnt element sizes, especially
* very large and very small elements.
*
* NOTE right now we don't allow configuration and use a constant radius
* (see DEFAULT_ADAPTIVE_RADIUS constant)
* ADAPTIVE_RADIUS: 3,
* } as const;
*/
/**
* Utility function. Returns an element object using style settings and provided parameters.
* @param {string} id - The element ID.
@@ -1291,6 +1353,7 @@ export class ExcalidrawAutomate {
boundElements: [] as any,
link,
locked: false,
frameId: null as string,
...scale ? {scale} : {},
};
}
@@ -1680,6 +1743,7 @@ export class ExcalidrawAutomate {
);
if(dimensions && !formatting?.width) {
textElement.width = dimensions.width;
textElement.height = dimensions.height;
textElement.x = dimensions.x;
@@ -1926,10 +1990,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;
};
@@ -2726,8 +2792,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,
@@ -2735,6 +2804,7 @@ export class ExcalidrawAutomate {
newElementsOnTop,
shouldRestoreElements,
});
return result;
};
/**
@@ -3030,6 +3100,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.
+44 -27
View File
@@ -46,7 +46,8 @@ import {
FileId,
} from "@zsviczian/excalidraw/types/element/src/types";
import { BinaryFiles, DataURL, SceneData } from "@zsviczian/excalidraw/types/excalidraw/types";
import { EmbeddedFile, MimeType } from "./EmbeddedFileLoader";
import { EmbeddedFile } from "./EmbeddedFileLoader";
import { MimeType } from "src/types/embeddedFileLoaderTypes";
import { MultiOptionConfirmationPrompt } from "./Dialogs/Prompt";
import { getMermaidImageElements, getMermaidText, shouldRenderMermaid } from "../utils/mermaidUtils";
import { DEBUGGING, debug } from "../utils/debugHelper";
@@ -304,7 +305,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
@@ -439,10 +444,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)) {
@@ -450,8 +463,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");
}
@@ -569,6 +582,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;
@@ -748,6 +765,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);
@@ -790,27 +828,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 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();
data = data.substring(0, sceneJSONandPOS.pos);
//The Markdown # Text Elements take priority over the JSON text elements. Assuming the scenario in which the
+1 -1
View File
@@ -1,7 +1,7 @@
// LaTeX.ts
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import ExcalidrawView from "../view/ExcalidrawView";
import { FileData, MimeType } from "./EmbeddedFileLoader";
import { FileData, MimeType } from "src/types/embeddedFileLoaderTypes";
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
import ExcalidrawPlugin from "src/core/main";
+2 -1
View File
@@ -1,13 +1,14 @@
import { ExcalidrawAutomate } from "../ExcalidrawAutomate";
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/element/src/types";
import { EmbeddedFilesLoader } from "../EmbeddedFileLoader";
import { blobToBase64 } from "src/utils/fileUtils";
import { getEA } from "src/core";
import { log } from "src/utils/debugHelper";
import { ExportSettings } from "src/types/exportUtilTypes";
import ExcalidrawView from "src/view/ExcalidrawView";
const TASKBONE_URL = "https://api.taskbone.com/"; //"https://excalidraw-preview.onrender.com/";
const TASKBONE_OCR_FN = "execute?id=60f394af-85f6-40bc-9613-5d26dc283cbb";
+46
View File
@@ -0,0 +1,46 @@
type MessageContent =
| string
| (string | { type: "image_url"; image_url: string })[];
export type GPTCompletionRequest = {
model: string;
messages?: {
role?: "system" | "user" | "assistant" | "function";
content?: MessageContent;
name?: string | undefined;
}[];
functions?: any[] | undefined;
function_call?: any | undefined;
stream?: boolean | undefined;
temperature?: number | undefined;
top_p?: number | undefined;
max_tokens?: number | undefined;
n?: number | undefined;
best_of?: number | undefined;
frequency_penalty?: number | undefined;
presence_penalty?: number | undefined;
logit_bias?:
| {
[x: string]: number;
}
| undefined;
stop?: (string[] | string) | undefined;
size?: string;
quality?: "standard" | "hd";
prompt?: string;
image?: string;
mask?: string;
};
export type AIRequest = {
image?: string;
text?: string;
instruction?: string;
systemPrompt?: string;
imageGenerationProperties?: {
size?: string; //depends on model
quality?: "standard" | "hd"; //depends on model
n?: number; //dall-e-3 only accepts 1
mask?: string; //dall-e-2 only (image editing)
};
};
+52
View File
@@ -0,0 +1,52 @@
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
import { BinaryFileData, DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import { ValueOf } from "../types/types";
export const IMAGE_MIME_TYPES = {
svg: "image/svg+xml",
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
gif: "image/gif",
webp: "image/webp",
bmp: "image/bmp",
ico: "image/x-icon",
avif: "image/avif",
jfif: "image/jfif",
} as const;
export type ImgData = {
mimeType: MimeType;
fileId: FileId;
dataURL: DataURL;
created: number;
hasSVGwithBitmap: boolean;
size: Size;
pdfPageViewProps?: PDFPageViewProps;
};
export declare type MimeType = ValueOf<typeof IMAGE_MIME_TYPES> | "application/octet-stream";
export type FileData = BinaryFileData & {
size: Size;
hasSVGwithBitmap: boolean;
shouldScale: boolean; //true if image should maintain its area, false if image should display at 100% its size
pdfPageViewProps?: PDFPageViewProps;
};
export type PDFPageViewProps = {
left: number;
bottom: number;
right: number;
top: number;
rotate?: number; //may be undefined in legacy files
}
export type Size = {
height: number;
width: number;
};
export interface ColorMap {
[color: string]: string;
};
+1 -1
View File
@@ -1,7 +1,7 @@
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import { TFile } from "obsidian";
import { FileId } from "src/core";
import { ColorMap, MimeType, PDFPageViewProps, Size } from "src/shared/EmbeddedFileLoader";
import { ColorMap, PDFPageViewProps, Size, MimeType } from "./embeddedFileLoaderTypes";
export type SVGColorInfo = Map<string, {
mappedTo: string;
+66
View File
@@ -0,0 +1,66 @@
import { FrameRenderingOptions } from "./utilTypes";
export type PDFPageAlignment =
| "center"
| "top-left"
| "top-center"
| "top-right"
| "bottom-left"
| "bottom-center"
| "bottom-right"
| "center-left"
| "center-right";
export type PDFPageMarginString = "none" | "tiny" | "normal";
export interface PDFExportScale {
fitToPage: number; // 0 means use zoom, >1 means fit to that many pages exactly
zoom?: number;
}
export interface PDFMargin {
left: number;
right: number;
top: number;
bottom: number;
}
export interface PDFPageProperties {
dimensions?: {width: number; height: number};
backgroundColor?: string;
margin: PDFMargin;
alignment: PDFPageAlignment;
}
export interface PageDimensions {
width: number;
height: number;
}
export type PageOrientation = "portrait" | "landscape";
// All dimensions in pixels (pt)
export const STANDARD_PAGE_SIZES = {
A0: { width: 3179.52, height: 4494.96 }, // 33.11 × 46.81 inches
A1: { width: 2245.76, height: 3179.52 }, // 23.39 × 33.11 inches
A2: { width: 1587.76, height: 2245.76 }, // 16.54 × 23.39 inches
A3: { width: 1122.56, height: 1587.76 }, // 11.69 × 16.54 inches
A4: { width: 794.56, height: 1122.56 }, // 8.27 × 11.69 inches
A5: { width: 559.37, height: 794.56 }, // 5.83 × 8.27 inches
A6: { width: 397.28, height: 559.37 }, // 4.13 × 5.83 inches
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
"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;
export interface ExportSettings {
withBackground: boolean;
withTheme: boolean;
isMask: boolean;
frameRendering?: FrameRenderingOptions; //optional, overrides relevant appState settings for rendering the frame
skipInliningFonts?: boolean;
}
+1
View File
@@ -58,6 +58,7 @@ declare global {
declare module "obsidian" {
interface App {
internalPlugins: any;
setting: any;
isMobile(): boolean;
getObsidianUrl(file:TFile): string;
metadataTypeManager: {
+1 -47
View File
@@ -1,52 +1,6 @@
import { Notice, RequestUrlResponse } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
type MessageContent =
| string
| (string | { type: "image_url"; image_url: string })[];
export type GPTCompletionRequest = {
model: string;
messages?: {
role?: "system" | "user" | "assistant" | "function";
content?: MessageContent;
name?: string | undefined;
}[];
functions?: any[] | undefined;
function_call?: any | undefined;
stream?: boolean | undefined;
temperature?: number | undefined;
top_p?: number | undefined;
max_tokens?: number | undefined;
n?: number | undefined;
best_of?: number | undefined;
frequency_penalty?: number | undefined;
presence_penalty?: number | undefined;
logit_bias?:
| {
[x: string]: number;
}
| undefined;
stop?: (string[] | string) | undefined;
size?: string;
quality?: "standard" | "hd";
prompt?: string;
image?: string;
mask?: string;
};
export type AIRequest = {
image?: string;
text?: string;
instruction?: string;
systemPrompt?: string;
imageGenerationProperties?: {
size?: string; //depends on model
quality?: "standard" | "hd"; //depends on model
n?: number; //dall-e-3 only accepts 1
mask?: string; //dall-e-2 only (image editing)
};
};
import { GPTCompletionRequest, AIRequest } from "src/types/AIUtilTypes";
const handleImageEditPrompt = async (request: AIRequest) : Promise<RequestUrlResponse> => {
const plugin: ExcalidrawPlugin = window.ExcalidrawAutomate.plugin;
+1 -1
View File
@@ -1,7 +1,7 @@
//for future use, not used currently
import { ImageCrop } from "@zsviczian/excalidraw/types/element/src/types";
import { PDFPageViewProps } from "src/shared/EmbeddedFileLoader";
import { PDFPageViewProps } from "src/types/embeddedFileLoaderTypes";
export function getPDFCropRect (props: {
scale: number,
+95 -13
View File
@@ -1,9 +1,25 @@
import { NonDeletedExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import { DEVICE, REG_LINKINDEX_INVALIDCHARS } from "src/constants/constants";
import { getParentOfClass } from "./obsidianUtils";
import { App, Notice, TFile, WorkspaceLeaf } from "obsidian";
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,17 +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 {
//@ts-ignore
const loadFile = lgv?.loadFile;
if (loadFile) {
loadFile(file);
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";
}
+40 -16
View File
@@ -8,7 +8,7 @@ import {
} from "@zsviczian/excalidraw/types/element/src/types";
import { normalizePath, TFile } from "obsidian";
import ExcalidrawView, { ExportSettings, getTextMode } from "src/view/ExcalidrawView";
import ExcalidrawView, { getTextMode } from "src/view/ExcalidrawView";
import {
GITHUB_RELEASES,
getCommonBoundingBox,
@@ -37,11 +37,14 @@ import {
postOpenAI as _postOpenAI,
extractCodeBlocks as _extractCodeBlocks,
} from "../utils/AIUtils";
import { ColorMap, EmbeddedFilesLoader, FileData } from "src/shared/EmbeddedFileLoader";
import { EmbeddedFilesLoader } from "src/shared/EmbeddedFileLoader";
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";
import { ColorMap, FileData } from "src/types/embeddedFileLoaderTypes";
import { ExportSettings } from "src/types/exportUtilTypes";
declare const PLUGIN_VERSION:string;
@@ -149,7 +152,7 @@ export function errorMessage(message: string, source: string):void {
export function isColorStringTransparent(color: string): boolean {
const rgbaHslaTransparentRegex = /^(rgba|hsla)\(.*?,.*?,.*?,\s*0(\.0+)?\)$/i;
const hexTransparentRegex = /^#[a-fA-F0-9]{8}00$/i;
const hexTransparentRegex = /^#[a-fA-F0-9]{6}00$/i;
return rgbaHslaTransparentRegex.test(color) || hexTransparentRegex.test(color);
}
@@ -280,10 +283,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);
}
}
@@ -551,13 +561,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));
@@ -628,9 +646,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,
@@ -641,13 +659,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();
});
};
+58 -11
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/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/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"));
}*/
});
}
+245 -108
View File
@@ -3,66 +3,10 @@ import { DEVICE } from 'src/constants/constants';
import { t } from 'src/lang/helpers';
import { download } from './fileUtils';
import { svgToBase64 } from './utils';
import { PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFMargin, PDFPageAlignment, PDFPageMarginString, PDFPageProperties, STANDARD_PAGE_SIZES } from 'src/types/exportUtilTypes';
const DPI = 96;
export type PDFPageAlignment =
| "center"
| "top-left"
| "top-center"
| "top-right"
| "bottom-left"
| "bottom-center"
| "bottom-right"
| "center-left"
| "center-right";
export type PDFPageMarginString = "none" | "tiny" | "normal";
export interface PDFExportScale {
fitToPage: number; // 0 means use zoom, >1 means fit to that many pages exactly
zoom?: number;
}
export interface PDFMargin {
left: number;
right: number;
top: number;
bottom: number;
}
export interface PDFPageProperties {
dimensions?: {width: number; height: number};
backgroundColor?: string;
margin: PDFMargin;
alignment: PDFPageAlignment;
}
export interface PageDimensions {
width: number;
height: number;
}
export type PageOrientation = "portrait" | "landscape";
// All dimensions in pixels (pt)
export const STANDARD_PAGE_SIZES = {
A0: { width: 3179.52, height: 4494.96 }, // 33.11 × 46.81 inches
A1: { width: 2245.76, height: 3179.52 }, // 23.39 × 33.11 inches
A2: { width: 1587.76, height: 2245.76 }, // 16.54 × 23.39 inches
A3: { width: 1122.56, height: 1587.76 }, // 11.69 × 16.54 inches
A4: { width: 794.56, height: 1122.56 }, // 8.27 × 11.69 inches
A5: { width: 559.37, height: 794.56 }, // 5.83 × 8.27 inches
A6: { width: 397.28, height: 559.37 }, // 4.13 × 5.83 inches
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
"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;
//margins are in pixels
export function getMarginValue(margin:PDFPageMarginString): PDFMargin {
switch(margin) {
@@ -96,6 +40,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 {
@@ -172,23 +120,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);
@@ -206,8 +185,10 @@ async function printPdf(
margins,
scaleFactor: 100,
scale: 1,
open: true,
open: shouldOpen,
filepath: pdfPath,
preferCSSPageSize: true,
...(pageRanges ? { pageRanges } : {}), // NEW
};
try {
@@ -256,8 +237,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;
@@ -445,60 +426,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);
+1 -1
View File
@@ -1,12 +1,12 @@
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
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 { getAttachmentsFolderAndFilePath } from "./obsidianUtils";
import ExcalidrawView from "src/view/ExcalidrawView";
import { IMAGE_MIME_TYPES, MimeType } from "src/types/embeddedFileLoaderTypes";
/**
* Splits a full path including a folderpath and a filename into separate folderpath and filename components
+135 -35
View File
@@ -3,7 +3,7 @@ import {
Editor,
FrontMatterCache,
MarkdownView,
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 { splitFolderAndFilename } from "./fileUtils";
@@ -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,
@@ -296,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();
@@ -412,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);
}
+53 -14
View File
@@ -20,21 +20,22 @@ import {
} from "../constants/constants";
import ExcalidrawPlugin from "../core/main";
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/common/src/utility-types";
import { cleanBlockRef, cleanSectionHeading, getFileCSSClasses } from "./obsidianUtils";
import { cleanBlockRef, cleanSectionHeading, getExcalidrawViews, getFileCSSClasses } from "./obsidianUtils";
import { updateElementLinksToObsidianLinks } from "./excalidrawAutomateUtils";
import { CropImage } from "../shared/CropImage";
import opentype from 'opentype.js';
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";
import { ExcalidrawSettings } from "src/core/settings";
import { FileData } from "src/types/embeddedFileLoaderTypes";
import { ExportSettings } from "src/types/exportUtilTypes";
declare const PLUGIN_VERSION:string;
declare var LZString: any;
@@ -51,6 +52,21 @@ declare module "obsidian" {
}
}
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() {
@@ -610,6 +626,19 @@ export function setLeftHandedMode (isLeftHanded: boolean) {
})
};
export function calculateTrayModeValue(settings: ExcalidrawSettings): boolean {
const { defaultTrayMode, compactModeOnTablets } = settings;
const isTrayMode = DEVICE.isTablet
? (compactModeOnTablets ? false : defaultTrayMode)
: defaultTrayMode;
return isTrayMode;
}
export function setTrayMode(app: App, settings: ExcalidrawSettings) {
const isTrayMode = calculateTrayModeValue(settings);
getExcalidrawViews(app).forEach((view) => view.setTrayMode(isTrayMode));
}
export type LinkParts = {
original: string;
path: string;
@@ -625,6 +654,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],
@@ -634,7 +665,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,
};
};
@@ -1055,16 +1086,24 @@ export function escapeRegExp (str:string) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
export function addIframe (containerEl: HTMLElement, link:string, startAt?: number, style:string = "settings") {
const wrapper = containerEl.createDiv({cls: `excalidraw-videoWrapper ${style}`})
wrapper.createEl("iframe", {
export function addYouTubeThumbnail (containerEl: HTMLElement, link:string, startAt?: number, style:string = "settings") {
const wrapper = containerEl.createDiv({cls: `excalidraw-videoWrapper ${style}`});
const thumbnailUrl = `https://i.ytimg.com/vi/${link}/maxresdefault.jpg`;
const anchor = wrapper.createEl("a", {
attr: {
allowfullscreen: true,
allow: "encrypted-media;picture-in-picture",
frameborder: "0",
title: "YouTube video player",
src: "https://www.youtube.com/embed/" + link + (startAt ? "?start=" + startAt : ""),
sandbox: "allow-forms allow-presentation allow-same-origin allow-scripts allow-modals",
href: "https://www.youtube.com/watch?v=" + link + (startAt ? "&t=" + startAt : ""),
target: "_blank",
rel: "noopener noreferrer",
},
});
anchor.createEl("img", {
attr: {
src: thumbnailUrl || `https://i.ytimg.com/vi/${link}/default.jpg`,
alt: "YouTube video thumbnail",
style: "width: 100%; height: auto; cursor: pointer;",
},
});
}
+178 -57
View File
@@ -38,7 +38,6 @@ import {
DISK_ICON_NAME,
SCRIPTENGINE_ICON_NAME,
TEXT_DISPLAY_RAW_ICON_NAME,
TEXT_DISPLAY_PARSED_ICON_NAME,
IMAGE_TYPES,
KEYCODE,
FRONTMATTER_KEYS,
@@ -109,8 +108,12 @@ import {
arrayToMap,
addAppendUpdateCustomData,
getFilePathFromObsidianURL,
getLinkParts,
checkVersionMismatch,
calculateTrayModeValue,
setTrayMode,
} from "../utils/utils";
import { cleanBlockRef, cleanSectionHeading, closeLeafView, getActivePDFPageNumberFromPDFView, getAttachmentsFolderAndFilePath, getLeaf, getParentOfClass, obsidianPDFQuoteWithRef, openLeaf, setExcalidrawView } from "../utils/obsidianUtils";
import { cleanBlockRef, cleanSectionHeading, closeLeafView, getAttachmentsFolderAndFilePath, getExcalidraAndMarkdowViewsForFile, getLeaf, getParentOfClass, obsidianPDFQuoteWithRef, openLeaf, setExcalidrawView } from "../utils/obsidianUtils";
import { splitFolderAndFilename } from "../utils/fileUtils";
import { GenericInputPrompt, MultiOptionConfirmationPrompt, NewFileActions, Prompt, linkPrompt } from "../shared/Dialogs/Prompt";
import { ClipboardData } from "@zsviczian/excalidraw/types/excalidraw/clipboard";
@@ -118,7 +121,6 @@ import { updateEquation } from "../shared/LaTeX";
import {
EmbeddedFile,
EmbeddedFilesLoader,
FileData,
generateIdFromFile,
} from "../shared/EmbeddedFileLoader";
import { ScriptInstallPrompt } from "../shared/Dialogs/ScriptInstallPrompt";
@@ -129,10 +131,10 @@ import { getTextElementAtPointer, getImageElementAtPointer, getElementWithLinkAt
import { excalidrawSword, ICONS, LogoWrapper, Rank, saveIcon, SwordColors } from "../constants/actionIcons";
import { ExportDialog } from "../shared/Dialogs/ExportDialog";
import { getEA } from "src/core"
import { anyModifierKeysPressed, emulateKeysForLinkClick, isWinALTorMacOPT, isWinCTRLorMacCMD, isWinMETAorMacCTRL, isSHIFT, linkClickModifierType, localFileDragModifierType, ModifierKeys, modifierKeyTooltipMessages } from "../utils/modifierkeyHelper";
import { anyModifierKeysPressed, emulateKeysForLinkClick, isWinALTorMacOPT, isWinCTRLorMacCMD, isWinMETAorMacCTRL, isSHIFT, linkClickModifierType, ModifierKeys } from "../utils/modifierkeyHelper";
import { setDynamicStyle } from "../utils/dynamicStyling";
import { CustomEmbeddable, renderWebView } from "./components/CustomEmbeddable";
import { addBackOfTheNoteCard, getExcalidrawFileForwardLinks, getFrameBasedOnFrameNameOrId, getLinkTextFromLink, insertEmbeddableToView, insertImageToView, isTextImageTransclusion, openExternalLink, parseObsidianLink, renderContextMenuAction, tmpBruteForceCleanup, toggleImageAnchoring } from "../utils/excalidrawViewUtils";
import { addBackOfTheNoteCard, deleteAppStateKeys, getExcalidrawFileForwardLinks, getFrameBasedOnFrameNameOrId, getLinkTextFromLink, insertEmbeddableToView, insertImageToView, isTextImageTransclusion, onLoadMessages, openExternalLink, parseObsidianLink, renderContextMenuAction, tmpBruteForceCleanup, toggleImageAnchoring } from "../utils/excalidrawViewUtils";
import { imageCache } from "../shared/ImageCache";
import { CanvasNodeFactory, ObsidianCanvasNode } from "./managers/CanvasNodeFactory";
import { EmbeddableMenu } from "./components/menu/EmbeddableActionsMenu";
@@ -152,10 +154,11 @@ import { getPDFCropRect } from "../utils/PDFUtils";
import { AutoexportConfig, Position, ViewSemaphores } from "../types/excalidrawViewTypes";
import { DropManager } from "./managers/DropManager";
import { ImageInfo } from "src/types/excalidrawAutomateTypes";
import { exportPNG, exportPNGToClipboard, exportSVG, exportToPDF, getMarginValue, getPageDimensions, PageOrientation, PageSize } from "src/utils/exportUtils";
import { FrameRenderingOptions } from "src/types/utilTypes";
import { exportPNG, exportPNGToClipboard, exportSVG, exportToPDF, getMarginValue, getPageDimensions } from "src/utils/exportUtils";
import { PageOrientation, PageSize, ExportSettings } from "src/types/exportUtilTypes";
import { CaptureUpdateAction } from "src/constants/constants";
import { Backpack } from "lucide-react";
import { updateElementIdsInScene } from "src/utils/excalidrawSceneUtils";
import { FileData } from "src/types/embeddedFileLoaderTypes";
const EMBEDDABLE_SEMAPHORE_TIMEOUT = 2000;
const PREVENT_RELOAD_TIMEOUT = 2000;
@@ -185,14 +188,6 @@ interface WorkspaceItemExt extends WorkspaceItem {
containerEl: HTMLElement;
}
export interface ExportSettings {
withBackground: boolean;
withTheme: boolean;
isMask: boolean;
frameRendering?: FrameRenderingOptions; //optional, overrides relevant appState settings for rendering the frame
skipInliningFonts?: boolean;
}
const HIDE = "excalidraw-hidden";
const SHOW = "excalidraw-visible";
@@ -1650,11 +1645,11 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
t("RAW"),
() => this.changeTextMode(TextMode.parsed),
);
this.actionButtons['isParsed'] = this.addAction(
/*this.actionButtons['isParsed'] = this.addAction(
TEXT_DISPLAY_PARSED_ICON_NAME,
t("PARSED"),
() => this.changeTextMode(TextMode.raw),
);
);*/
this.actionButtons['link'] = this.addAction("link", t("OPEN_LINK"), (ev) =>
this.handleLinkClick(ev),
@@ -1846,10 +1841,10 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
this.textMode = textMode;
if (textMode === TextMode.parsed) {
this.actionButtons['isRaw'].hide();
this.actionButtons['isParsed'].show();
//this.actionButtons['isParsed'].hide();
} else {
this.actionButtons['isRaw'].show();
this.actionButtons['isParsed'].hide();
//this.actionButtons['isParsed'].hide();
}
if (this.toolsPanelRef && this.toolsPanelRef.current) {
this.toolsPanelRef.current.setPreviewMode(textMode === TextMode.parsed);
@@ -2165,7 +2160,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
await this.excalidrawData.setTextMode(this.textMode);
}
this.excalidrawData.scene.appState.theme = api.getAppState().theme;
await this.loadDrawing(loadOnModifyTrigger);
await this.loadDrawing(loadOnModifyTrigger, undefined, true);
this.clearDirty();
}
@@ -2265,10 +2260,10 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
if(filenameParts.hasSectionref) {
query = [`# ${filenameParts.sectionref}`]
} else if (state.line && state.line > 0) {
query = [this.data.split("\n")[state.line - 1]];
query = [this.data.split("\n")[state.line]]; //was -1 https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2503
}
if (query) {
if (query && query.length > 0 && !(query.length === 1 && query[0].length === 0)) {
window.setTimeout(async () => {
await waitForExcalidraw();
@@ -2277,6 +2272,15 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
if (api.getAppState().isLoading) return;
const elements = api.getSceneElements() as ExcalidrawElement[];
if(query.length === 1) {
const elementId = query[0].match(/ \^([^ ]+)$/)?.[1] ?? query[0].match(/^([^ :]+): \[\[[^\]]+]]$/)?.[1];
if(elementId && elements.find((el)=>el.id === elementId)) {
this.preventAutozoom();
window.setTimeout(()=>this.zoomToElements(!api.getAppState().viewModeEnabled, [elements.find((el)=>el.id === elementId)]));
return;
}
}
if(query.length === 1 && query[0].startsWith("[")) {
const partsArray = REGEX_LINK.getResList(query[0]);
@@ -2356,6 +2360,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
if(this.lastLoadedFile === this.file) return;
this.isLoaded = false;
if(!this.file) return;
if(this.plugin.settings.compareManifestToPluginVersion) checkVersionMismatch(this.plugin);
if(this.plugin.settings.showNewVersionNotification) checkExcalidrawVersion();
if(isMaskFile(this.plugin,this.file)) {
const notice = new Notice(t("MASK_FILE_NOTICE"), 5000);
@@ -2501,6 +2506,8 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
}
await this.loadDrawing(true);
onLoadMessages(this.plugin, this.excalidrawData.scene,this.data);
if(this.plugin.ea.onFileOpenHook) {
const tempEA = getEA(this);
try {
@@ -2776,9 +2783,10 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
*
* @param justloaded - a flag to trigger zoom to fit after the drawing has been loaded
*/
public async loadDrawing(justloaded: boolean, deletedElements?: ExcalidrawElement[]) {
public async loadDrawing(justloaded: boolean, deletedElements?: ExcalidrawElement[], isReloading: boolean = false) {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.loadDrawing, "ExcalidrawView.loadDrawing", justloaded, deletedElements);
const excalidrawData = this.excalidrawData.scene;
const isOpenInMultipleLeaves = getExcalidraAndMarkdowViewsForFile(this.app,this.file).length > 1;
this.semaphores.justLoaded = justloaded;
this.clearDirty();
const om = this.excalidrawData.getOpenMode();
@@ -2808,14 +2816,19 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
{
//elements: excalidrawData.elements.concat(deletedElements??[]), //need to preserve deleted elements during autosave if images, links, etc. are updated
appState: {
...excalidrawData.appState,
...isReloading && isOpenInMultipleLeaves
? deleteAppStateKeys(excalidrawData.appState, ["scrollX","scrollY","zoom"])
: excalidrawData.appState,
...this.excalidrawData.selectedElementIds //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/609
? this.excalidrawData.selectedElementIds
: {},
...excalidrawData.appState.frameRendering && excalidrawData.appState.frameRendering.markerName === undefined
? { frameRendering: {...excalidrawData.appState.frameRendering, markerName: true, markerEnabled: true } }
: {},
zenModeEnabled,
viewModeEnabled,
linkOpacity: this.excalidrawData.getLinkOpacity(),
trayModeEnabled: this.plugin.settings.defaultTrayMode,
trayModeEnabled: calculateTrayModeValue(this.plugin.settings),
penMode: penEnabled,
penDetected: penEnabled,
allowPinchZoom: this.plugin.settings.allowPinchZoom,
@@ -2840,11 +2853,16 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
this.instantiateExcalidraw({
elements: excalidrawData.elements,
appState: {
...excalidrawData.appState,
...isReloading && isOpenInMultipleLeaves
? deleteAppStateKeys(excalidrawData.appState, ["scrollX","scrollY","zoom"])
: excalidrawData.appState,
...excalidrawData.appState.frameRendering && excalidrawData.appState.frameRendering.markerName === undefined
? { frameRendering: {...excalidrawData.appState.frameRendering, markerName: true, markerEnabled: true } }
: {},
zenModeEnabled: om.zenModeEnabled,
viewModeEnabled: excalidrawData.elements.length > 0 ? om.viewModeEnabled : false,
linkOpacity: this.excalidrawData.getLinkOpacity(),
trayModeEnabled: this.plugin.settings.defaultTrayMode,
trayModeEnabled: calculateTrayModeValue(this.plugin.settings),
penMode: penEnabled,
penDetected: penEnabled,
allowPinchZoom: this.plugin.settings.allowPinchZoom,
@@ -3658,6 +3676,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
currentItemStartArrowhead: st.currentItemStartArrowhead,
currentItemEndArrowhead: st.currentItemEndArrowhead,
currentItemArrowType: st.currentItemArrowType,
currentItemFrameRole: st.currentItemFrameRole,
scrollX: st.scrollX,
scrollY: st.scrollY,
zoom: st.zoom,
@@ -4037,7 +4056,23 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
}
}
private shouldSaveImportedImage: boolean = false;
private onChange (et: ExcalidrawElement[], st: AppState) {
if(st.activeTool?.type) {
if(st.activeTool.type === "image") {
if(st.selectedElementIds && Object.keys(st.selectedElementIds).length === 1) {
const selectedElement = et.filter(el=>el.id === Object.keys(st.selectedElementIds)[0])[0];
if(selectedElement && selectedElement.type === "image") {
this.shouldSaveImportedImage = true;
}
}
}
if(st.activeTool.type === "selection" && this.shouldSaveImportedImage) {
this.shouldSaveImportedImage = false;
setTimeout(()=>this.save(true, true),100); //image is being added to the scene
}
}
if(st.newElement?.type === "freedraw") {
this.freedrawLastActiveTimestamp = Date.now();
}
@@ -4054,7 +4089,9 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
if( elcount>0 && et.length===0 ) return;
this.semaphores.justLoaded = false;
if (!this.semaphores.preventAutozoom && this.plugin.settings.zoomToFitOnOpen) {
this.zoomToFit(false,true);
if(getExcalidraAndMarkdowViewsForFile(this.app, this.file).length === 1) {
this.zoomToFit(false,true);
}
}
this.previousSceneVersion = this.getSceneVersion(et);
this.previousBackgroundColor = st.viewBackgroundColor;
@@ -4227,7 +4264,12 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
}
}
if (data.elements) {
window.setTimeout(() => this.save(), 30); //removed prevent reload = false, as reload was triggered when pasted containers were processed and there was a conflict with the new elements
//const onlyImages = data.elements.length > 0 && data.elements.every((el) => el.type === "image");
//const preventReload = !onlyImages;
data.elements.filter(el=>el.type==="text" || el.link).forEach(el=>
updateElementIdsInScene({elements: data.elements as Mutable<ExcalidrawElement>[]},el, nanoid())
);
window.setTimeout(() => this.save(false), 30); //removed prevent reload = false, as reload was triggered when pasted containers were processed and there was a conflict with the new elements
}
//process pasted text after it was processed into elements by Excalidraw
@@ -4423,8 +4465,14 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
ea.selectElementsInView([await insertEmbeddableToView (ea, center, file, link)]);
ea.destroy();
} else {
const modal = new UniversalInsertFileModal(this.plugin, this);
modal.open(file, center);
const linkParts = getLinkParts(link);
if(linkParts.page) {
const path = file.path + "#" + link.split("#")[1];
ea.selectElementsInView([await insertImageToView (ea, center, path)]);
} else {
const modal = new UniversalInsertFileModal(this.plugin, this);
modal.open(file, center);
}
}
this.setDirty(9);
}
@@ -4627,12 +4675,12 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
return {imageEl: el, embeddedFile: imageFile};
}
public async insertBackOfTheNoteCard() {
public async insertBackOfTheNoteCard(center: boolean = false) {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.insertBackOfTheNoteCard, "ExcalidrawView.insertBackOfTheNoteCard");
await this.forceSave(true);
const sections = await this.getBackOfTheNoteSections();
const selectCardDialog = new SelectCard(this.app,this,sections);
selectCardDialog.start();
selectCardDialog.start(center);
}
public async moveBackOfTheNoteCardToFile(id?: string) {
@@ -4978,6 +5026,44 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
onClose
),
])
if(
!areElementsSelected &&
elements.some(el=>el.type === "frame" && el.frameRole === "marker")
) {
const {frameRendering} = appState;
contextMenuActions.push([
renderContextMenuAction(
React,
frameRendering.markerEnabled && frameRendering.enabled && frameRendering.outline
? t("MARKER_FRAME_HIDE")
: t("MARKER_FRAME_SHOW"),
() => {
const markerEnabled = !(frameRendering.markerEnabled && frameRendering.enabled && frameRendering.outline);
if(markerEnabled) {
setTimeout(() => this.updateScene({appState: {frameRendering: {...frameRendering, enabled: true, outline: true, markerEnabled}}, captureUpdate: CaptureUpdateAction.NEVER}));
} else {
setTimeout(() => this.updateScene({appState: {frameRendering: {...frameRendering, markerEnabled}}, captureUpdate: CaptureUpdateAction.NEVER}));
}
},
onClose
),
]);
if(frameRendering.markerEnabled && frameRendering.enabled && frameRendering.outline) {
contextMenuActions.push([
renderContextMenuAction(
React,
frameRendering.markerName
? t("MARKER_FRAME_TITLE_HIDE")
: t("MARKER_FRAME_TITLE_SHOW"),
() => {
setTimeout(() => this.updateScene({appState: {frameRendering: {...frameRendering, markerName: !frameRendering.markerName}}, captureUpdate: CaptureUpdateAction.NEVER}));
},
onClose
),
]);
}
}
}
if(contextMenuActions.length === 0) return;
@@ -5260,9 +5346,19 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
{
icon: ICONS.trayMode,
"aria-label": t("ARIA_LABEL_TRAY_MODE"),
onSelect: ()=> this.toggleTrayMode(),
onSelect: ()=> {
if(!DEVICE.isTablet) {
this.toggleTrayMode();
return;
}
if(this.plugin.settings.defaultTrayMode) {
this.toggleCompactMode();
return;
}
this.toggleTrayMode(false);
},
},
"Toggle tray-mode"
t("TRAY_TRAY_MODE")
) : null,
React.createElement(
MainMenu.Item,
@@ -5271,34 +5367,34 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
"aria-label": t("FORCE_SAVE"),
onSelect: ()=> this.forceSave(),
},
"Save"
t("TRAY_SAVE")
),
React.createElement(
MainMenu.Item,
{
icon: ICONS.scriptEngine,
"aria-label": "Explore the Excalidraw Script Library",
"aria-label": t("TRAY_SCRIPT_LIBRARY_ARIA"),
onSelect: ()=> this.actionOpenScriptInstallPrompt(),
},
"Script Library"
t("TRAY_SCRIPT_LIBRARY")
),
React.createElement(
MainMenu.Item,
{
icon: ICONS.ExportImage,
"aria-label": "Export image as PNG, SVG, or Excalidraw file",
"aria-label": t("TRAY_EXPORT_ARIA"),
onSelect: ()=> this.actionOpenExportImageDialog(),
},
"Export Image..."
t("TRAY_EXPORT")
),
React.createElement(
MainMenu.Item,
{
icon: ICONS.switchToMarkdown,
"aria-label": "Switch to markdown view",
"aria-label": t("TRAY_SWITCH_TO_MD_ARIA"),
onSelect: ()=> this.openAsMarkdown(),
},
"Open as Markdown"
t("TRAY_SWITCH_TO_MD")
),
React.createElement(MainMenu.Separator),
React.createElement(MainMenu.DefaultItems.Help),
@@ -5726,22 +5822,41 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
});
}
public async toggleTrayMode() {
public async toggleCompactMode() {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.toggleCompactMode, "ExcalidrawView.toggleCompactMode");
//just in case settings were updated via Obsidian sync
const newCompactMode = !this.plugin.settings.compactModeOnTablets;
await this.plugin.loadSettings();
this.plugin.settings.compactModeOnTablets = newCompactMode;
setTrayMode(this.app, this.plugin.settings);
await this.plugin.saveSettings();
}
public async toggleTrayMode(compactMode?: boolean) {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.toggleTrayMode, "ExcalidrawView.toggleTrayMode");
//just in case settings were updated via Obsidian sync
const newTrayMode = !this.plugin.settings.defaultTrayMode;
await this.plugin.loadSettings();
this.plugin.settings.defaultTrayMode = newTrayMode;
if(compactMode!==undefined) {
this.plugin.settings.compactModeOnTablets = compactMode;
}
setTrayMode(this.app, this.plugin.settings);
await this.plugin.saveSettings();
}
public setTrayMode(on: boolean) {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.toggleTrayMode, "ExcalidrawView.setTrayMode");
const api = this.excalidrawAPI as ExcalidrawImperativeAPI;
if (!api) {
return false;
}
const st = api.getAppState();
api.updateScene({
appState: { trayModeEnabled: !st.trayModeEnabled },
appState: { trayModeEnabled: on },
captureUpdate: CaptureUpdateAction.NEVER,
});
//just in case settings were updated via Obsidian sync
await this.plugin.loadSettings();
this.plugin.settings.defaultTrayMode = !st.trayModeEnabled;
this.plugin.saveSettings();
setTimeout(()=>api.refreshEditorBreakpoints());
}
/**
@@ -5894,7 +6009,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
if(elements.length === 2) {
const textEl = elements.filter(el=>el.type==="text");
if(textEl.length===1 && (textEl[0] as ExcalidrawTextElement).containerId) {
const container = elements.filter(el=>el.boundElements.some(be=>be.type==="text"))
const container = elements.filter(el=>el.boundElements && el.boundElements.some(be=>be.type==="text"))
if(container.length===1) {
elementId = textEl[0].id;
}
@@ -5909,6 +6024,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
const frames = elements.filter(el=>el.type==="frame");
const hasFrame = frames.length === 1;
const hasMarkerFrame = hasFrame && frames[0].frameRole === "marker";
const hasGroup = elements.some(el=>el.groupIds && el.groupIds.length>0);
let button = {
@@ -5926,7 +6042,8 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
button.area,
button.link,
...hasGroup ? [button.group] : [],
...hasFrame ? [button.frame, button.clippedframe] : [],
...hasFrame && !hasMarkerFrame ? [button.clippedframe] : [],
...hasFrame ? [button.frame] : [],
];
break;
case "group=":
@@ -5934,12 +6051,14 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
...hasGroup ? [button.group] : [],
button.link,
button.area,
...hasFrame ? [button.frame, button.clippedframe] : [],
...hasFrame && !hasMarkerFrame ? [button.clippedframe] : [],
...hasFrame ? [button.frame] : [],
];
break;
case "frame=":
buttons = [
...hasFrame ? [button.frame, button.clippedframe] : [],
...hasFrame && !hasMarkerFrame ? [button.clippedframe] : [],
...hasFrame ? [button.frame] : [],
...hasGroup ? [button.group] : [],
button.link,
button.area,
@@ -5947,7 +6066,8 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
break;
case "clippedframe=":
buttons = [
...hasFrame ? [button.clippedframe, button.frame] : [],
...hasFrame && !hasMarkerFrame ? [button.clippedframe] : [],
...hasFrame ? [button.frame] : [],
...hasGroup ? [button.group] : [],
button.link,
button.area,
@@ -5958,7 +6078,8 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
{caption: "Link", action:()=>{prefix="";return}},
{caption: "Area", action:()=>{prefix="area="; return;}},
{caption: "Group", action:()=>{prefix="group="; return;}},
...hasFrame ? [button.frame, button.clippedframe] : [],
...hasFrame && !hasMarkerFrame ? [button.clippedframe] : [],
...hasFrame ? [button.frame] : [],
]
}
+509 -133
View File
@@ -1,15 +1,16 @@
import { NonDeletedExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import { ExcalidrawEmbeddableElement, } from "@zsviczian/excalidraw/types/element/src/types";
import ExcalidrawView from "src/view/ExcalidrawView";
import { Notice, WorkspaceLeaf, WorkspaceSplit } from "obsidian";
import { Notice, requireApiVersion, WorkspaceLeaf, } from "obsidian";
import * as React from "react";
import { ConstructableWorkspaceSplit, getContainerForDocument, isObsidianThemeDark } from "src/utils/obsidianUtils";
import { DEVICE, EXTENDED_EVENT_TYPES, KEYBOARD_EVENT_TYPES } from "src/constants/constants";
import { isObsidianThemeDark } from "src/utils/obsidianUtils";
import { DEVICE, EXTENDED_EVENT_TYPES, KEYBOARD_EVENT_TYPES, } from "src/constants/constants";
import { ExcalidrawImperativeAPI, UIAppState } from "@zsviczian/excalidraw/types/excalidraw/types";
import { ObsidianCanvasNode } from "src/view/managers/CanvasNodeFactory";
import { processLinkText, patchMobileView, setFileToLocalGraph } from "src/utils/customEmbeddableUtils";
import { processLinkText, patchMobileView, setFileToLocalGraph, createLeaf, predictViewType } from "src/utils/customEmbeddableUtils";
import { EmbeddableMDCustomProps } from "src/shared/Dialogs/EmbeddableSettings";
import { t } from "src/lang/helpers";
const CANVAS_VIEWTYPES = new Set(["markdown", "bases"]);
const CANVAS_VIEWTYPES = new Set(["markdown", "bases", "audio", "video", "pdf"]);
declare module "obsidian" {
interface Workspace {
@@ -21,6 +22,17 @@ declare module "obsidian" {
}
}
let noticeTimer: number;
function showNoticeOnce(message: string) {
if (noticeTimer) {
return
}
noticeTimer = window.setTimeout(() => {
noticeTimer = undefined;
}, 1000);
new Notice(message,6000);
}
function getTheme (view: ExcalidrawView, theme:string): string {
return view.excalidrawData.embeddableTheme === "dark"
? "theme-dark"
@@ -31,6 +43,258 @@ function getTheme (view: ExcalidrawView, theme:string): string {
: isObsidianThemeDark() ? "theme-dark" : "theme-light";
}
function setPDFViewTheme(view: ExcalidrawView, pdfView: any) {
if(!pdfView) return;
if(view.excalidrawData.embeddableTheme === "auto") {
pdfView.viewer?.child?.pdfViewer?.setBackground?.(null, false);
const pdfContainerEl = pdfView.containerEl?.querySelector(".pdf-container");
if(pdfContainerEl) {
pdfContainerEl.classList.remove("mod-themed");
}
const thumbnailViewEl = pdfView.containerEl?.querySelector(".pdf-thumbnail-view");
if(thumbnailViewEl) {
thumbnailViewEl.style.filter = "var(--theme-filter)";
}
} else {
const pdfViewerEl = pdfView.containerEl?.querySelector("div.pdfViewer");
if(pdfViewerEl) {
pdfViewerEl.addClass("mod-nofilter");
}
}
if(["dark", "light"].includes(view.excalidrawData.embeddableTheme)) {
const pdfContainerEl = pdfView.containerEl?.querySelector(".pdf-container");
if(pdfContainerEl && !pdfContainerEl.classList.contains("mod-themed")) {
pdfContainerEl.classList.add("mod-themed");
}
}
if(view.excalidrawData.embeddableTheme === "light") {
pdfView.viewer?.child?.pdfViewer?.setBackground?.(null, false);
}
if(view.excalidrawData.embeddableTheme === "dark") {
pdfView.viewer?.child?.pdfViewer?.setBackground?.(
document.body.getCssPropertyValue("--color-base-00"), true
);
}
}
function setupPdfViewEnhancements(
view: ExcalidrawView,
leafRef: React.MutableRefObject<{ leaf: WorkspaceLeaf; node?: ObsidianCanvasNode; editNode?: Function } | null>,
pdfObserverRef: React.MutableRefObject<MutationObserver | null> & { currentCleanup?: () => void },
pdfObserverDisabledRef: React.MutableRefObject<boolean>
) {
const pdfView = leafRef.current?.node?.child;
if (!pdfView) return;
const patchPDF = () => {
// Disable observer while applying the theme to avoid loops
pdfObserverDisabledRef.current = true;
setPDFViewTheme(view, pdfView);
requestAnimationFrame(() => { pdfObserverDisabledRef.current = false; });
// Observe inline height changes on the PDF root container and reset them
// this could be an obsidian bug, should be revisted later 2025-08-23
const containerEl = pdfView.containerEl as HTMLElement | null;
let prevHeight = containerEl?.style?.height || "";
let heightObserver: MutationObserver | null = null;
if (containerEl) {
heightObserver = new MutationObserver(() => {
const h = containerEl.style.height || "";
if (h !== prevHeight) {
prevHeight = h;
if (h) {
containerEl.style.height = "";
prevHeight = "";
}
}
});
heightObserver.observe(containerEl, { attributes: true, attributeFilter: ["style"] });
}
// Transform-aware MMB drag-to-scroll (bypasses Chromium autoscroll)
const scroller = pdfView.containerEl?.querySelector(".pdf-viewer-container") || null;
let active = false;
let lastX = 0, lastY = 0;
let scaleX = 1, scaleY = 1;
const getScaleFromAncestor = (target: Element | null) => {
// Read scale from the outer excalidraw embeddable container transform
const container = target?.closest(".excalidraw__embeddable-container") as HTMLElement | null;
if (!container) return { sx: 1, sy: 1 };
const t = getComputedStyle(container).transform;
// t can be "none", "matrix(a,b,c,d,tx,ty)" or "matrix3d(...)"
if (!t || t === "none") return { sx: 1, sy: 1 };
if (t.startsWith("matrix3d(")) {
// matrix3d: m11=a1, m12=b1, m21=a2, m22=b2 in the first 6 entries
const m = t.slice(9, -1).split(",").map(Number);
const a = m[0], b = m[1], c = m[4], d = m[5];
// scaleX = length of first column, scaleY = length of second column
return { sx: Math.hypot(a, b) || 1, sy: Math.hypot(c, d) || 1 };
}
if (t.startsWith("matrix(")) {
const m = t.slice(7, -1).split(",").map(Number); // [a,b,c,d,tx,ty]
const a = m[0], b = m[1], c = m[2], d = m[3];
return { sx: Math.hypot(a, b) || 1, sy: Math.hypot(c, d) || 1 };
}
return { sx: 1, sy: 1 };
};
const onPointerDownCapture = (e: PointerEvent) => {
if ((
(DEVICE.isDesktop && e.button !== 1) ||
(DEVICE.isMobile && e.button !== 0)) ||
!scroller) return;
// Start custom pan, cancel browser autoscroll and prevent Excalidraw from handling it.
e.preventDefault();
e.stopPropagation();
active = true;
lastX = e.clientX;
lastY = e.clientY;
const { sx, sy } = getScaleFromAncestor(scroller);
scaleX = sx;
scaleY = sy;
// Listen on window so we keep panning even if we leave the element.
window.addEventListener("pointermove", onPointerMove, { capture: true });
window.addEventListener("pointerup", onPointerUp, { capture: true, once: true });
window.addEventListener("pointercancel", onPointerUp, { capture: true, once: true });
try { (view.contentEl as HTMLElement).style.cursor = "grabbing"; } catch {}
};
const onPointerMove = (e: PointerEvent) => {
if (!active || !scroller) return;
// Continue only while the pointer button is held:
// - Desktop: middle mouse button (bit 3 = 4)
// - Mobile: primary/left button (bit 0 = 1)
if (
(DEVICE.isDesktop && (e.buttons & 4) === 0) ||
(DEVICE.isMobile && (e.buttons & 1) === 0)
) return;
const dx = e.clientX - lastX;
const dy = e.clientY - lastY;
lastX = e.clientX;
lastY = e.clientY;
// Convert viewport dx/dy to local CSS px by dividing on scale.
scroller.scrollLeft -= dx / (scaleX || 1);
scroller.scrollTop -= dy / (scaleY || 1);
e.preventDefault();
e.stopPropagation();
};
const onPointerUp = (_e: PointerEvent) => {
active = false;
try { (view.contentEl as HTMLElement).style.cursor = ""; } catch {}
window.removeEventListener("pointermove", onPointerMove, { capture: true } as any);
window.removeEventListener("pointerup", onPointerUp, { capture: true } as any);
window.removeEventListener("pointercancel", onPointerUp,{ capture: true } as any);
};
const root = pdfView.containerEl as HTMLElement;
root?.addEventListener("pointerdown", onPointerDownCapture, { capture: true });
const cleanupPan = () => {
root?.removeEventListener("pointerdown", onPointerDownCapture, { capture: true } as any);
window.removeEventListener("pointermove", onPointerMove, { capture: true } as any);
window.removeEventListener("pointerup", onPointerUp, { capture: true } as any);
window.removeEventListener("pointercancel", onPointerUp,{ capture: true } as any);
heightObserver?.disconnect();
heightObserver = null;
};
(pdfObserverRef as any).currentCleanup = () => { cleanupPan(); };
if (view.excalidrawData.embeddableTheme !== "default") {
const pdfContainerEl = pdfView.containerEl?.querySelector(".pdf-container") as HTMLElement | null;
if (pdfContainerEl) {
pdfObserverRef.current?.disconnect();
pdfObserverRef.current = new MutationObserver(() => {
if (pdfObserverDisabledRef.current) return;
pdfObserverDisabledRef.current = true;
try {
setPDFViewTheme(view, pdfView);
if(view.excalidrawData.embeddableTheme !== "default") {
showNoticeOnce(t("NOTICE_PDF_THEME"));
}
} finally {
requestAnimationFrame(() => { pdfObserverDisabledRef.current = false; });
}
});
pdfObserverRef.current.observe(pdfContainerEl, {
attributes: true,
attributeFilter: ["class"],
});
// https://github.com/RyotaUshio/obsidian-pdf-plus/issues/477
// Watch for the PDF container being removed from DOM (e.g. by PDF+)
const rootEl = pdfView.containerEl as HTMLElement | null;
if (rootEl) {
let detachObserver: MutationObserver | null = new MutationObserver((_muts, obs) => {
// If the tracked pdfContainerEl is gone/replaced, clean up and reattach
if (!pdfContainerEl.isConnected || !rootEl.contains(pdfContainerEl)) {
obs.disconnect();
detachObserver = null;
// Cleanup existing handlers/observers
try { (pdfObserverRef as any).currentCleanup?.(); } catch {}
try { pdfObserverRef.current?.disconnect(); } catch {}
// Re-setup on next tick to allow DOM to settle
setTimeout(() => {
if (leafRef.current?.node?.child?.containerEl?.isConnected) {
setupPdfViewEnhancements(
view,
leafRef as React.MutableRefObject<{ leaf: WorkspaceLeaf; node?: ObsidianCanvasNode; editNode?: Function } | null>,
pdfObserverRef as any,
pdfObserverDisabledRef
);
}
}, 0);
}
});
detachObserver.observe(rootEl, { childList: true, subtree: true });
// Extend cleanup to also stop the detachObserver and the class observer
const prevCleanup = (pdfObserverRef as any).currentCleanup;
(pdfObserverRef as any).currentCleanup = () => {
try { prevCleanup?.(); } catch {}
try { pdfObserverRef.current?.disconnect(); } catch {}
try { detachObserver?.disconnect(); } catch {}
detachObserver = null;
};
}
}
}
};
const root = leafRef?.current?.node?.child?.containerEl;
if (root) {
const selector = ".pdf-viewer-container";
const existing = root.querySelector(selector);
if (existing) {
patchPDF();
} else {
let timeoutId:number = null as any;
const mo = new MutationObserver((_, obs) => {
const el = root.querySelector(selector);
if (el) {
patchPDF();
obs.disconnect();
if (timeoutId) clearTimeout(timeoutId);
}
});
mo.observe(root as HTMLElement, { childList: true, subtree: true });
timeoutId = window.setTimeout(() => {
mo.disconnect();
}, 10000);
}
}
}
//--------------------------------------------------------------------------------
//Render webview for anything other than Vimeo and Youtube
//Vimeo and Youtube are rendered by Excalidraw because of the window messaging
@@ -46,6 +310,7 @@ export function renderWebView (src: string, view: ExcalidrawView, id: string, _:
title="Excalidraw Embedded Content"
allowFullScreen={true}
src={src}
webpreferences="autoplayPolicy=document-user-activation-required"
style={{
overflow: "hidden",
borderRadius: "var(--embeddable-radius)",
@@ -59,7 +324,7 @@ export function renderWebView (src: string, view: ExcalidrawView, id: string, _:
className="excalidraw__embeddable"
title="Excalidraw Embedded Content"
allowFullScreen={true}
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
src={isDataURL ? null : src}
style={{
overflow: "hidden",
@@ -74,15 +339,16 @@ export function renderWebView (src: string, view: ExcalidrawView, id: string, _:
//Render WorkspaceLeaf or CanvasNode
//--------------------------------------------------------------------------------
function RenderObsidianView(
{ mdProps, element, linkText, view, containerRef, activeEmbeddable, theme, canvasColor }:{
{ mdProps, element, linkText, view, containerRef, activeEmbeddable, theme, canvasColor, selectedElementId }:{
mdProps: EmbeddableMDCustomProps;
element: NonDeletedExcalidrawElement;
element: ExcalidrawEmbeddableElement;
linkText: string;
view: ExcalidrawView;
containerRef: React.RefObject<HTMLDivElement>;
activeEmbeddable: {element: NonDeletedExcalidrawElement; state: string};
activeEmbeddable: {element: ExcalidrawEmbeddableElement; state: string};
theme: string;
canvasColor: string;
selectedElementId: string;
}): JSX.Element {
const { subpath, file } = processLinkText(linkText, view);
@@ -96,8 +362,13 @@ function RenderObsidianView(
const leafRef = React.useRef<{leaf: WorkspaceLeaf; node?: ObsidianCanvasNode, editNode?: Function} | null>(null);
const isEditingRef = React.useRef(false);
const isActiveRef = React.useRef(false);
const viewTypeRef = React.useRef("empty");
const themeRef = React.useRef(theme);
const elementRef = React.useRef(element);
const pdfObserverRef = React.useRef(null);
const pdfObserverDisabledRef = React.useRef(false);
const mobilePatchCleanupRef = React.useRef(null);
const initialViewFileRef = React.useRef(view.file);
// Update themeRef when theme changes
React.useEffect(() => {
@@ -110,7 +381,7 @@ function RenderObsidianView(
}, [element]);
//--------------------------------------------------------------------------------
//block propagation of events to the parent if the iframe element is active
//block propagation of events to the parent if the embeddable element is active
//--------------------------------------------------------------------------------
const stopPropagation = React.useCallback((event:React.PointerEvent<HTMLElement>) => {
if(isActiveRef.current) {
@@ -137,7 +408,7 @@ function RenderObsidianView(
}; //cleanup on unmount
}, []);
//blocking or not the propagation of events to the parent if the iframe is active
//blocking or not the propagation of events to the parent if the embeddable element is active
React.useEffect(() => {
EXTENDED_EVENT_TYPES.forEach((type) => containerRef.current.removeEventListener(type, stopPropagation));
if(!containerRef?.current) {
@@ -166,6 +437,21 @@ function RenderObsidianView(
}
}, [isActiveRef.current]);
const setKeepOnTop = () => {
const keepontop = (view.app.workspace.activeLeaf === view.leaf) && DEVICE.isDesktop;
if (keepontop) {
//@ts-ignore
if(!view.ownerWindow.electronWindow.isAlwaysOnTop()) {
//@ts-ignore
view.ownerWindow.electronWindow.setAlwaysOnTop(true);
setTimeout(() => {
//@ts-ignore
view.ownerWindow.electronWindow.setAlwaysOnTop(false);
}, 500);
}
}
}
//--------------------------------------------------------------------------------
//Mount the workspace leaf or the canvas node depending on subpath
//--------------------------------------------------------------------------------
@@ -180,71 +466,82 @@ function RenderObsidianView(
containerRef.current.parentElement.style.padding = "";
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();
leafRef.current = {
leaf: view.app.workspace.createLeafInParent(rootSplit, 0),
leaf: null,
node: null,
editNode: null,
};
const setKeepOnTop = () => {
const keepontop = (view.app.workspace.activeLeaf === view.leaf) && DEVICE.isDesktop;
if (keepontop) {
//@ts-ignore
if(!view.ownerWindow.electronWindow.isAlwaysOnTop()) {
//@ts-ignore
view.ownerWindow.electronWindow.setAlwaysOnTop(true);
setTimeout(() => {
//@ts-ignore
view.ownerWindow.electronWindow.setAlwaysOnTop(false);
}, 500);
const createNode = (viewType: string) => {
if(!requireApiVersion("1.9.10")) {
setKeepOnTop();
}
leafRef.current.node = view.canvasNodeFactory.createFileNote(file, subpath, containerRef.current, element.id);
setColors(containerRef.current, element, mdProps, canvasColor, viewType);
view.updateEmbeddableLeafRef(element.id, leafRef.current);
viewTypeRef.current = "markdown";
}
patchMobileView(view);
//if subpath is defined, create a canvas node else create a workspace leaf
if(subpath && view.canvasNodeFactory.isInitialized() && file.extension.toLowerCase() === "md") {
createNode("markdown");
} else {
let viewType = predictViewType(view.app,file);
// markdown could still be a kanban board or other custom view on top of markdown, those need to be displayed in leaves
if(viewType !== "markdown" && CANVAS_VIEWTYPES.has(viewType) && view.canvasNodeFactory.isInitialized()) {
createNode(viewType);
if(viewType === "pdf") {
// Moved PDF setup logic into a helper for readability
setupPdfViewEnhancements(
view,
leafRef as React.MutableRefObject<{ leaf: WorkspaceLeaf; node?: ObsidianCanvasNode; editNode?: Function } | null>,
pdfObserverRef as unknown as React.MutableRefObject<MutationObserver | null> & { currentCleanup?: () => void },
pdfObserverDisabledRef
);
}
} else {
(async () => {
const {rootSplit, leaf } = createLeaf(view);
leafRef.current.leaf = leaf;
await leafRef.current.leaf.openFile(file, {
active: false,
state: {mode:"preview"},
...subpath ? { eState: { subpath }}:{},
});
const viewType = leafRef.current.leaf.view?.getViewType();
viewTypeRef.current = viewType;
if(viewType === "canvas") {
leafRef.current.leaf.view.canvas?.setReadonly(true);
}
if (viewType === "markdown" && view.canvasNodeFactory.isInitialized()) {
createNode("markdown");
//I haven't found a better way of deciding if an .md file has its own view (e.g., kanban) or not
//This runs only when the file is added, thus should not be a major performance issue
await leafRef.current.leaf.setViewState({state: {file:null}})
leafRef.current.leaf?.detach();
} else {
const workspaceLeaf:HTMLDivElement = rootSplit.containerEl.querySelector("div.workspace-leaf");
if(workspaceLeaf) workspaceLeaf.style.borderRadius = "var(--embeddable-radius)";
rootSplit.containerEl.addClass("mod-visible");
containerRef.current.appendChild(rootSplit.containerEl);
setColors(containerRef.current, element, mdProps, canvasColor, viewType);
view.updateEmbeddableLeafRef(element.id, leafRef.current);
}
})();
}
}
//if subpath is defined, create a canvas node else create a workspace leaf
if(subpath && view.canvasNodeFactory.isInitialized()) {
setKeepOnTop();
leafRef.current.node = view.canvasNodeFactory.createFileNote(file, subpath, containerRef.current, element.id);
view.updateEmbeddableLeafRef(element.id, leafRef.current);
} else {
(async () => {
await leafRef.current.leaf.openFile(file, {
active: false,
state: {mode:"preview"},
...subpath ? { eState: { subpath }}:{},
});
const viewType = leafRef.current.leaf.view?.getViewType();
if(viewType === "canvas") {
leafRef.current.leaf.view.canvas?.setReadonly(true);
}
if (CANVAS_VIEWTYPES.has(viewType) && view.canvasNodeFactory.isInitialized()) {
setKeepOnTop();
//I haven't found a better way of deciding if an .md file has its own view (e.g., kanban) or not
//This runs only when the file is added, thus should not be a major performance issue
await leafRef.current.leaf.setViewState({state: {file:null}})
leafRef.current.node = view.canvasNodeFactory.createFileNote(file, subpath, containerRef.current, element.id);
setColors(containerRef.current, element, mdProps, canvasColor);
} else {
const workspaceLeaf:HTMLDivElement = rootSplit.containerEl.querySelector("div.workspace-leaf");
if(workspaceLeaf) workspaceLeaf.style.borderRadius = "var(--embeddable-radius)";
rootSplit.containerEl.addClass("mod-visible");
containerRef.current.appendChild(rootSplit.containerEl);
setColors(containerRef.current, element, mdProps, canvasColor);
}
patchMobileView(view);
view.updateEmbeddableLeafRef(element.id, leafRef.current);
})();
}
return () => {
// disconnect observer if any
(pdfObserverRef as any).currentCleanup?.();
pdfObserverRef.current?.disconnect();
pdfObserverRef.current = null;
// cleanup persistent mobile patch if active
try { mobilePatchCleanupRef.current?.(); } catch {}
mobilePatchCleanupRef.current = null;
if(!leafRef.current) {
return;
}
@@ -257,7 +554,7 @@ function RenderObsidianView(
//--------------------------------------------------------------------------------
//Set colors of the canvas node
//--------------------------------------------------------------------------------
function setColors (canvasNode: HTMLDivElement, element: NonDeletedExcalidrawElement, mdProps: EmbeddableMDCustomProps, canvasColor: string) {
function setColors (canvasNode: HTMLDivElement, element: ExcalidrawEmbeddableElement, mdProps: EmbeddableMDCustomProps, canvasColor: string, viewType: string) {
if(!mdProps) return;
if (!leafRef.current?.hasOwnProperty("node")) return;
@@ -297,22 +594,31 @@ function RenderObsidianView(
canvasNode?.style.setProperty("--background-primary", color);
canvasNodeContainer?.style.setProperty("background-color", color);
}
canvasNode?.style.setProperty("--bases-cards-container-background","var(--background-primary)");
canvasNode?.style.setProperty("--bases-embed-border-color","var(--background-modifier-border)");
canvasNode?.style.setProperty("--bases-table-header-color","var(--text-muted)");
canvasNode?.style.setProperty("--bases-table-header-background","var(--background-primary)");
canvasNode?.style.setProperty("--bases-table-header-background-hover","var(--background-modifier-hover)");
canvasNode?.style.setProperty("--bases-table-header-sort-mask","linear-gradient(to left, transparent var(--size-4-6), black var(--size-4-6))");
canvasNode?.style.setProperty("--bases-table-border-color","var(--table-border-color)");
canvasNode?.style.setProperty("--bases-table-row-background-hover","var(--table-row-background-hover)");
canvasNode?.style.setProperty("--bases-table-cell-shadow-active","0 0 0 2px var(--interactive-accent)");
canvasNode?.style.setProperty("--bases-table-cell-background-active","var(--background-primary)");
canvasNode?.style.setProperty("--bases-table-cell-background-disabled","var(--background-primary-alt)");
canvasNode?.style.setProperty("--bases-cards-container-background","var(--background-primary)");
canvasNode?.style.setProperty("--bases-cards-background","var(--background-primary)");
canvasNode?.style.setProperty("--bases-cards-cover-background","var(--background-primary-alt)");
canvasNode?.style.setProperty("--bases-cards-shadow","0 0 0 1px var(--background-modifier-border)");
canvasNode?.style.setProperty("--bases-cards-shadow-hover","0 0 0 1px var(--background-modifier-border-hover)");
switch (viewType) {
case "bases":
canvasNode?.style.setProperty("--bases-cards-container-background","var(--background-primary)");
canvasNode?.style.setProperty("--bases-embed-border-color","var(--background-modifier-border)");
canvasNode?.style.setProperty("--bases-table-header-color","var(--text-muted)");
canvasNode?.style.setProperty("--bases-table-header-background","var(--background-primary)");
canvasNode?.style.setProperty("--bases-table-header-background-hover","var(--background-modifier-hover)");
canvasNode?.style.setProperty("--bases-table-header-sort-mask","linear-gradient(to left, transparent var(--size-4-6), black var(--size-4-6))");
canvasNode?.style.setProperty("--bases-table-border-color","var(--table-border-color)");
canvasNode?.style.setProperty("--bases-table-row-background-hover","var(--table-row-background-hover)");
canvasNode?.style.setProperty("--bases-table-cell-shadow-active","0 0 0 2px var(--interactive-accent)");
canvasNode?.style.setProperty("--bases-table-cell-background-active","var(--background-primary)");
canvasNode?.style.setProperty("--bases-table-cell-background-disabled","var(--background-primary-alt)");
canvasNode?.style.setProperty("--bases-cards-container-background","var(--background-primary)");
canvasNode?.style.setProperty("--bases-cards-background","var(--background-primary)");
canvasNode?.style.setProperty("--bases-cards-cover-background","var(--background-primary-alt)");
canvasNode?.style.setProperty("--bases-cards-shadow","0 0 0 1px var(--background-modifier-border)");
canvasNode?.style.setProperty("--bases-cards-shadow-hover","0 0 0 1px var(--background-modifier-border-hover)");
break;
case "pdf":
canvasNode?.style.setProperty("--pdf-sidebar-background","var(--background-primary)");
canvasNode?.style.setProperty("--pdf-background","var(--background-primary)");
canvasNode?.style.setProperty("--pdf-sidebar-background","var(--background-primary)");
break;
}
if(mdProps.borderMatchElement) {
const opacity = (mdProps?.borderOpacity ?? 50)/100;
@@ -342,7 +648,7 @@ function RenderObsidianView(
const element = elementRef.current;
const canvasNode = containerRef.current;
if(!canvasNode.hasClass("canvas-node")) return;
setColors(canvasNode, element, mdProps, canvasColor);
setColors(canvasNode, element, mdProps, canvasColor, viewTypeRef.current);
}, [
mdProps?.useObsidianDefaults,
mdProps?.backgroundMatchCanvas,
@@ -355,6 +661,7 @@ function RenderObsidianView(
elementRef.current,
containerRef.current,
canvasColor,
viewTypeRef.current,
])
//--------------------------------------------------------------------------------
@@ -374,56 +681,97 @@ function RenderObsidianView(
//Switch to edit mode when markdown view is clicked
//--------------------------------------------------------------------------------
const handleClick = React.useCallback((event?: React.PointerEvent<HTMLElement>) => {
if (view.file !== initialViewFileRef.current) {
return;
}
if(isActiveRef.current) {
event?.stopPropagation();
}
if (isActiveRef.current && !isEditingRef.current && leafRef.current?.leaf) {
if(leafRef.current.leaf.view?.getViewType() === "markdown") {
const api:ExcalidrawImperativeAPI = view.excalidrawAPI;
const el = api.getSceneElements().filter(el=>el.id === element.id)[0];
if(!el || el.angle !== 0) {
new Notice("Sorry, cannot edit rotated markdown documents");
return;
}
//@ts-ignore
const modes = leafRef.current.leaf.view.modes;
if (!modes) {
return;
}
leafRef.current.leaf.view.setMode(modes['source']);
isEditingRef.current = true;
patchMobileView(view);
} else if (leafRef.current?.node) {
//Handle canvas node
const newTheme = getTheme(view, themeRef.current);
containerRef.current?.addClasses(["is-editing", "is-focused"]);
view.canvasNodeFactory.startEditing(leafRef.current.node, newTheme);
}
if(!isActiveRef.current || isEditingRef.current || !leafRef.current) {
return;
}
}, [leafRef.current?.leaf, element.id, view, themeRef.current]);
if(leafRef.current) leafRef.current.editNode = handleClick;
/*if(isActiveRef.current && leafRef.current?.leaf) {
setKeepOnTop();
view.app.workspace.setActiveLeaf(leafRef.current.leaf, { focus: true });
}*/
if (leafRef.current.node) {
//Handle canvas node
const newTheme = getTheme(view, themeRef.current);
containerRef.current?.addClasses(["is-editing", "is-focused"]);
view.canvasNodeFactory.startEditing(leafRef.current.node, newTheme);
return;
}
if(leafRef.current.leaf && viewTypeRef.current === "markdown") {
const api:ExcalidrawImperativeAPI = view.excalidrawAPI;
const el = api.getSceneElements().filter(el=>el.id === element.id)[0];
if(!el || el.angle !== 0) {
new Notice("Sorry, cannot edit rotated markdown documents");
return;
}
//@ts-ignore
const modes = leafRef.current.leaf.view.modes;
if (!modes) {
return;
}
patchMobileView(view);
leafRef.current.leaf.view.setMode(modes['source']);
isEditingRef.current = true;
}
}, [leafRef.current?.leaf, element.id, view, themeRef.current, isActiveRef.current, isEditingRef.current, viewTypeRef.current]);
const startEditing = React.useCallback(() => {
if (view.file !== initialViewFileRef.current) {
return;
}
if(isActiveRef.current && isEditingRef.current) {
return;
}
isActiveRef.current = true;
handleClick();
}, [isActiveRef.current, isEditingRef.current, handleClick, view]);
if(leafRef.current) leafRef.current.editNode = startEditing;
// Event listener for key press
React.useEffect(() => {
const handleKeyPress = (event: KeyboardEvent) => {
if (event.key === "Enter") {
handleClick(event); // Call handleClick function when Enter key is pressed
// Deactivate active embeddable on Escape
if (event.key === "Escape" && isActiveRef.current) {
event.preventDefault();
event.stopPropagation();
view.updateScene({ appState: { activeEmbeddable: null } });
return;
}
// Existing Enter behavior
if (
event.key === "Enter" && !isEditingRef.current &&
(selectedElementId === element.id || activeEmbeddable?.element?.id === element.id)
) {
startEditing(); // Call handleClick function when Enter key is pressed
}
};
document.addEventListener("keydown", handleKeyPress); // Add event listener for key press
// Use capture so this runs even if container stops bubbling
document.addEventListener("keydown", handleKeyPress, true);
return () => {
document.removeEventListener("keydown", handleKeyPress); // Remove event listener when component unmounts
document.removeEventListener("keydown", handleKeyPress, true);
};
}, [handleClick]);
}, [handleClick, isActiveRef.current, view, activeEmbeddable, element, selectedElementId]);
//--------------------------------------------------------------------------------
// Set isActiveRef and switch to preview mode when the iframe is not active
// Set isActiveRef and switch to preview mode when the embeddable is not active
//--------------------------------------------------------------------------------
React.useEffect(() => {
if (view.file !== initialViewFileRef.current) {
return;
}
if(!containerRef?.current || !leafRef?.current) {
return;
}
@@ -431,7 +779,6 @@ function RenderObsidianView(
const previousIsActive = isActiveRef.current;
isActiveRef.current = (activeEmbeddable?.element.id === element.id) && (activeEmbeddable?.state === "active");
const node = leafRef.current?.node as ObsidianCanvasNode;
if (previousIsActive === isActiveRef.current) {
return;
}
@@ -440,21 +787,8 @@ function RenderObsidianView(
setFileToLocalGraph(view.app, file);
}
if(leafRef.current.leaf?.view?.getViewType() === "markdown") {
//Handle markdown leaf
//@ts-ignore
const modes = leafRef.current.leaf.view.modes;
if(!modes) {
return;
}
if(!isActiveRef.current) {
//@ts-ignore
leafRef.current.leaf.view.setMode(modes["preview"]);
isEditingRef.current = false;
return;
}
} else if (node) {
const node = leafRef.current?.node as ObsidianCanvasNode;
if (node) {
//Handle canvas node
if(isActiveRef.current && view.plugin.settings.markdownNodeOneClickEditing && !containerRef.current?.hasClass("is-editing")) { //!node.isEditing
const newTheme = getTheme(view, themeRef.current);
@@ -464,10 +798,49 @@ function RenderObsidianView(
containerRef.current?.removeClasses(["is-editing", "is-focused"]);
view.canvasNodeFactory.stopEditing(node);
}
return;
}
if(leafRef.current.leaf) {
// Manage persistent mobile patch lifecycle for LEAF on phones
if (DEVICE.isPhone) {
if (isActiveRef.current) {
// start persistent observer if not running
if (!mobilePatchCleanupRef.current) {
const cleanup = patchMobileView(view, {
keepAlive: true,
isActive: () => isActiveRef.current,
});
mobilePatchCleanupRef.current = (typeof cleanup === "function") ? cleanup : null;
}
} else {
// stop persistent observer when deactivated
try { mobilePatchCleanupRef.current?.(); } catch {}
mobilePatchCleanupRef.current = null;
}
}
//I think this no longer happens since markdown is always a canvas node if canvasNodeFactory is initialized
if(viewTypeRef.current === "markdown") {
//Handle markdown leaf
//@ts-ignore
const modes = leafRef.current.leaf?.view.modes;
if(!modes) {
return;
}
if(!isActiveRef.current) {
//@ts-ignore
leafRef.current.leaf.view.setMode(modes["preview"]);
isEditingRef.current = false;
return;
}
}
}
}, [
containerRef,
leafRef,
activeEmbeddable?.state,
isActiveRef,
activeEmbeddable?.element,
activeEmbeddable?.state,
@@ -482,11 +855,12 @@ function RenderObsidianView(
};
export const CustomEmbeddable: React.FC<{element: NonDeletedExcalidrawElement; view: ExcalidrawView; appState: UIAppState; linkText: string}> = ({ element, view, appState, linkText }) => {
export const CustomEmbeddable: React.FC<{element: ExcalidrawEmbeddableElement; view: ExcalidrawView; appState: UIAppState; linkText: string}> = ({ element, view, appState, linkText }) => {
const React = view.packages.react;
const containerRef: React.RefObject<HTMLDivElement> = React.useRef(null);
const theme = getTheme(view, appState.theme);
const mdProps: EmbeddableMDCustomProps = element.customData?.mdProps || null;
const selectedElementIds = Object.keys(appState.selectedElementIds);
return (
<div
ref={containerRef}
@@ -495,6 +869,7 @@ export const CustomEmbeddable: React.FC<{element: NonDeletedExcalidrawElement; v
height: `100%`,
borderRadius: "var(--embeddable-radius)",
color: `var(--text-normal)`,
touchAction: "auto",
}}
className={`${theme} canvas-node ${
mdProps?.filenameVisible && !mdProps.useObsidianDefaults ? "" : "excalidraw-mdEmbed-hideFilename"}`}
@@ -508,6 +883,7 @@ export const CustomEmbeddable: React.FC<{element: NonDeletedExcalidrawElement; v
activeEmbeddable={appState.activeEmbeddable}
theme={appState.theme}
canvasColor={appState.viewBackgroundColor}
selectedElementId={selectedElementIds.length === 1 ? selectedElementIds[0] : null}
/>
</div>
)
@@ -10,9 +10,9 @@ import { ScriptEngine } from "../../../shared/Scripts";
import { MD_EX_SECTIONS, ROOTELEMENTSIZE, nanoid, sceneCoordsToViewportCoords } from "src/constants/constants";
import { REGEX_LINK, REG_LINKINDEX_HYPERLINK } from "../../../shared/ExcalidrawData";
import { processLinkText, useDefaultExcalidrawFrame } from "src/utils/customEmbeddableUtils";
import { cleanSectionHeading } from "src/utils/obsidianUtils";
import { cleanSectionHeading, getActivePDFPageNumberFromPDFView } from "src/utils/obsidianUtils";
import { EmbeddableSettings } from "src/shared/Dialogs/EmbeddableSettings";
import { openExternalLink } from "src/utils/excalidrawViewUtils";
import { insertImageToView, openExternalLink } from "src/utils/excalidrawViewUtils";
import { getEA } from "src/core";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { CaptureUpdateAction } from "src/constants/constants";
@@ -40,7 +40,7 @@ export class EmbeddableMenu {
this.renderButtons = null;
}
private updateElement = (subpath: string, element: ExcalidrawEmbeddableElement, file: TFile) => {
private updateElement = async (subpath: string, element: ExcalidrawEmbeddableElement, file: TFile, save: boolean = true) => {
if(!element) return;
const view = this.view;
const app = view.app;
@@ -56,7 +56,8 @@ export class EmbeddableMenu {
ea.copyViewElementsToEAforEditing([element]);
ea.getElement(element.id).link = link;
view.excalidrawData.elementLinks.set(element.id, link);
ea.addElementsToView(false, true, true).then(() => ea.destroy());
await ea.addElementsToView(false, save, true);
ea.destroy();
}
private handleMouseEnter () {
@@ -119,6 +120,46 @@ export class EmbeddableMenu {
}
}
private actionBookmarkPage (element: ExcalidrawEmbeddableElement) {
if(!element) return;
const pdfView = this.view.getEmbeddableLeafElementById(element.id)?.node?.child;
if(!pdfView) return;
const page = getActivePDFPageNumberFromPDFView(pdfView);
if(!page) return;
const pdfFile: TFile = pdfView?.file;
if(!pdfFile) return;
this.updateElement(`#page=${page}`, element, pdfFile, false);
}
private async actionInsertPageAsImage (element: ExcalidrawEmbeddableElement) {
if(!element) return;
const pdfView = this.view.getEmbeddableLeafElementById(element.id)?.node?.child;
if(!pdfView) return;
const page = getActivePDFPageNumberFromPDFView(pdfView);
if(!page) return;
const pdfFile: TFile = pdfView?.file;
if(!pdfFile) return;
const ea = getEA(this.view) as ExcalidrawAutomate;
ea.selectElementsInView([]);
const x = element.x + element.width + 20;
const y = element.y;
const path = this.view.app.metadataCache.fileToLinktext(
pdfFile,
this.view.file.path,
false,
)
const id = await insertImageToView(
ea,
{x,y},
`${path}#page=${page}`,
undefined,
undefined,
false,
);
ea.selectElementsInView([id]);
ea.destroy();
}
private async actionMarkdownBlock (file: TFile, subpath: string, element: ExcalidrawEmbeddableElement) {
if(!file) return;
this.view.updateScene({appState: {activeEmbeddable: null}, captureUpdate: CaptureUpdateAction.NEVER});
@@ -298,12 +339,26 @@ export class EmbeddableMenu {
icon={ICONS.Properties}
/>
{isPDF && (
<ActionButton
key={"Crop"}
title={t("CROP_PAGE")}
action={() => this.actionCrop(element)}
icon={ICONS.Crop}
/>
<>
<ActionButton
key={"Crop"}
title={t("CROP_PAGE")}
action={() => this.actionCrop(element)}
icon={ICONS.Crop}
/>
<ActionButton
key={"Bookmark"}
title={t("BOOKMARK_PAGE")}
action={() => this.actionBookmarkPage(element)}
icon={ICONS.Bookmark}
/>
<ActionButton
key={"Camera"}
title={t("CAPTURE_PAGE")}
action={() => this.actionInsertPageAsImage(element)}
icon={ICONS.Camera}
/>
</>
)}
</div>
</div>
+7 -2
View File
@@ -257,7 +257,12 @@ export class ObsidianMenu {
public renderButton (isMobile: boolean, appState: AppState) {
return (
<>
<div className={clsx(
{
"ExcalidrawObsidianMenu--mobile": isMobile,
"ExcalidrawObsidianMenu": !isMobile,
},
)}>
<label
className={clsx(
"ToolIcon",
@@ -288,7 +293,7 @@ export class ObsidianMenu {
</label>
{this.renderCustomPens(isMobile,appState)}
{this.renderPinnedScriptButtons(isMobile,appState)}
</>
</div>
);
};
+4 -2
View File
@@ -498,7 +498,7 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
<fieldset>
<legend>Utility actions</legend>
<div className="buttonList buttonListIcon">
<ActionButton
<ActionButton
key={"scriptEngine"}
title={t("INSTALL_SCRIPT_BUTTON")}
action={this.actionOpenScriptInstallDialog.bind(this)}
@@ -517,7 +517,7 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
action={(this.actionConvertExcalidrawToMD.bind(this))}
icon={ICONS.convertFile}
/>
) : (
) : !this.state.isPreviewMode && (
<ActionButton
key={"viewmode"}
title={this.state.isPreviewMode ? t("PARSED") : t("RAW")}
@@ -549,6 +549,8 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
: ICONS.gotoFullScreen
}
/>
</div>
<div className="buttonList buttonListIcon">
<ActionButton
key={"search"}
title={t("SEARCH")}
+8 -10
View File
@@ -34,6 +34,7 @@ export interface ObsidianCanvasNode {
isEditing: boolean;
file: TFile;
detach: Function;
isEditable: Function;
}
export class CanvasNodeFactory {
@@ -84,8 +85,8 @@ export class CanvasNodeFactory {
private async waitForEditor(node: ObsidianCanvasNode): Promise<HTMLElement | null> {
let counter = 0;
while (!node.child.editor?.containerEl?.parentElement?.parentElement && counter++ < 100) {
await new Promise(resolve => setTimeout(resolve, 25));
while (!node.child.editor?.containerEl?.parentElement?.parentElement && counter++ < 40) {
await sleep(25);
}
return node.child.editor?.containerEl?.parentElement?.parentElement;
}
@@ -112,12 +113,11 @@ export class CanvasNodeFactory {
}
public async startEditing(node: ObsidianCanvasNode, theme: string) {
if (!this.initialized || !node) return;
if (!this.initialized || !node || !node.isEditable()) return;
try {
//if (node.file === this.view.file) {
await this.view.setEmbeddableNodeIsEditing();
//}
await this.view.setEmbeddableNodeIsEditing();
node.startEditing();
node.isEditing = true;
@@ -138,12 +138,10 @@ export class CanvasNodeFactory {
}
public stopEditing(node: ObsidianCanvasNode) {
if (!this.initialized || !node || !node.isEditing) return;
if (!this.initialized || !node || !node.isEditing || !node.isEditable()) return;
try {
//if (node.file === this.view.file) {
this.view.clearEmbeddableNodeIsEditing();
//}
this.view.clearEmbeddableNodeIsEditing();
node.child.showPreview();
node.isEditing = false;
this.observer?.disconnect();
+1
View File
@@ -105,6 +105,7 @@ export class DropManager {
files: TFile[],
text: string,
): boolean => {
this.app.workspace.setActiveLeaf(this.view.leaf); //ensure the view is active, so ModalContainerObserver is active
if (this.view.getHookServer().onDropHook) {
try {
return this.view.getHookServer().onDropHook({
+49 -1
View File
@@ -290,6 +290,7 @@ textarea.excalidraw-wysiwyg {
}
.excalidraw .tray-zoom {
height: var(--default-button-size);
pointer-events: initial;
padding-bottom: 0.05rem;
padding-top: 0.05rem;
@@ -318,9 +319,11 @@ textarea.excalidraw-wysiwyg {
font-size: 0.45rem !important;
}
/*
.Island > .Stack > .Stack {
padding:0.2rem;
}
*/
label.color-input-container > input {
max-width: 5rem;
@@ -329,7 +332,7 @@ label.color-input-container > input {
.excalidraw .FixedSideContainer_side_top {
left: 10px !important;
top: 10px !important;
right: 10px !important;
right: 10px;
bottom: 10px !important;
}
@@ -857,3 +860,48 @@ textarea.excalidraw-wysiwyg, .excalidraw input {
fill: none;
pointer-events: none;
}
/*remove blur from PDF embed*/
.excalidraw__embeddable-container canvas {
image-rendering: auto;
}
.excalidraw__embeddable-container .mod-nofilter canvas {
filter: none !important;
}
.excalidraw__embeddable-container .canvas-node.is-selected .canvas-node-container,
.excalidraw__embeddable-container .canvas-node.is-focused .canvas-node-container {
border-color: inherit;
box-shadow: inherit;
}
.excalidraw__embeddable-container .pdf-toolbar-right {
display: none;
}
.excalidraw-scriptengine-install .modal-close-button {
z-index: 9999;
}
.excalidraw .undo-redo-buttons button {
width: 3em;
}
.ExcalidrawObsidianMenu--mobile label.ToolIcon {
margin-left: 4px;
}
.ExcalidrawObsidianMenu--mobile {
display: flex;
flex-direction: row;
flex-wrap: wrap;
row-gap: 4px;
justify-content: center;
align-items: center;
}
.ExcalidrawObsidianMenu {
display: flex;
flex-direction: column;
}