Compare commits

...

117 Commits

Author SHA1 Message Date
zsviczian
9fca82bb6f 1.9.0 2023-05-12 16:51:10 +02:00
zsviczian
00c801e338 updated slideshow script - do not select arrow at end if hidden 2023-05-01 07:03:08 +02:00
zsviczian
dd0c0cd021 updated slideshow script 2023-04-29 18:12:29 +02:00
zsviczian
12594baac6 1.8.26 2023-04-23 08:42:03 +02:00
zsviczian
b03bd7e4f9 updated scribble helper 2023-04-23 07:39:42 +02:00
zsviczian
02b21aeea9 lint 2023-04-23 07:27:07 +02:00
zsviczian
a67bdfa5e8 updates scribble helper 2023-04-23 07:25:06 +02:00
zsviczian
52407e89fb updated image 2023-04-22 21:41:07 +02:00
zsviczian
7e930c2339 1.8.25 2023-04-22 21:24:33 +02:00
zsviczian
7ab8f07d1f updated scribble helper 2023-04-21 05:57:19 +02:00
zsviczian
d34086a395 1.8.24 2023-04-17 23:44:46 +02:00
zsviczian
334f122cca Upgraded Script util.inputPrompt 2023-04-16 21:49:56 +02:00
zsviczian
f80202e5e7 1.8.23 2023-04-15 13:41:00 +02:00
zsviczian
29736f10fc bump excalidraw package and minor styling change 2023-04-13 18:16:40 +02:00
zsviczian
0654663dff Merge branch 'master' of https://github.com/zsviczian/obsidian-excalidraw-plugin 2023-04-08 19:42:57 +02:00
zsviczian
4e12f7cc4c gitignore 2023-04-08 19:41:58 +02:00
zsviczian
a42dbc0cdc updates messages 2023-04-02 11:04:05 +02:00
zsviczian
5c40cdb3d3 1.8.22 2023-04-02 10:20:09 +02:00
zsviczian
d47a206206 script update 2023-04-02 09:33:21 +02:00
zsviczian
ba0eaf067b Merge pull request #1016 from threethan/master
Add Hardware Eraser and Auto Draw scripts
2023-04-02 09:23:59 +02:00
zsviczian
f80edce3dc renam invert-colors image 2023-03-26 22:52:09 +02:00
zsviczian
21968214af 1.8.21 2023-03-26 22:40:46 +02:00
zsviczian
7770eb51dc Merge branch 'master' of https://github.com/zsviczian/obsidian-excalidraw-plugin 2023-03-19 20:12:29 +01:00
zsviczian
d0229259a6 1.8.20 2023-03-19 20:12:26 +01:00
zsviczian
00cbea3705 folder note core script 2023-03-16 14:41:59 +01:00
zsviczian
e85857c29f Update directory-info.json 2023-03-16 14:36:33 +01:00
zsviczian
1704a016b1 Add files via upload 2023-03-16 14:34:40 +01:00
zsviczian
f5af19557a publish Text to Sticky Notes 2023-03-11 13:29:11 +01:00
zsviczian
17b8b154c2 publish image 2023-03-11 13:19:41 +01:00
zsviczian
5c1030880a 1.8.19 2023-03-07 20:10:47 +01:00
zsviczian
1b62983016 1.8.18 2023-03-04 19:14:15 +01:00
zsviczian
52fb7ab546 updated excalidraw package 2023-02-26 17:35:13 +01:00
zsviczian
604bfbf23f 1.8.17 2023-02-26 17:28:59 +01:00
zsviczian
3c1a3c18c2 Merge pull request #1038 from tswwe/patch-2
Update zh-cn.ts
2023-02-26 17:16:20 +01:00
thxnder
f531c361de Update zh-cn.ts
keep up with en.ts
2023-02-26 18:20:37 +08:00
zsviczian
4609ea33bb 1.8.16 2023-02-21 21:11:23 +01:00
zsviczian
41b1a170f7 1.8.15-beta 2023-02-19 20:58:04 +01:00
zsviczian
e6d39eca75 upload modifiers table 2023-02-19 16:56:12 +01:00
threethan
2a1e3731ba Improved pen plugins (better compatibility) 2023-02-14 23:12:03 -05:00
zsviczian
8ca6a9fe96 1.8.14 2023-02-13 17:16:32 +01:00
threethan
6f2248ffa0 Add Hardware Eraser and Auto Draw scripts 2023-02-13 00:58:04 -05:00
zsviczian
48e47f333e 1.8.13 2023-02-12 15:41:18 +01:00
zsviczian
3091ed629a 1.8.12 2023-01-29 13:29:41 +01:00
zsviczian
a9193dd695 updated mindmap format description 2023-01-28 23:47:06 +01:00
zsviczian
3122e86e22 mindmap format script 2023-01-28 23:37:48 +01:00
zsviczian
a6efe27146 Merge pull request #968 from pandoralink/feature/mindmap-format
feat: add Mindmap format ea-script
2023-01-28 23:24:21 +01:00
zsviczian
adbec35e30 Merge pull request #989 from SamRidgeway/typo-fix
Fixes a typo in the fullscreen action
2023-01-28 23:23:35 +01:00
zsviczian
205a94d3a3 custom pen debug 2023-01-28 23:23:04 +01:00
zsviczian
6e88c8f0eb Pens and pinned scripts 2023-01-27 22:35:27 +01:00
Sam Ridgeway
32a05322d0 Fixes a typo in the fullscreen action 2023-01-27 09:39:14 -05:00
zsviczian
8738b74236 1.8.11 2023-01-22 14:19:41 +01:00
zsviczian
aa0ddd85fd handle link click cleanup duplicat function 2023-01-20 20:32:50 +01:00
zsviczian
bcd47ddb8e wheel, pinch, image url, grid 2023-01-19 22:24:15 +01:00
zsviczian
50f24b42cb 1.8.10 2023-01-15 16:49:28 +01:00
poplink
0a5d511c96 feat: add Mindmap format ea-script 2023-01-11 17:50:04 +08:00
zsviczian
70d93602f7 added new customized menu 2023-01-09 23:05:48 +01:00
zsviczian
68c7c9f55e 1.8.9 2023-01-08 14:29:56 +01:00
zsviczian
42f1fa88b9 added funding URL 2023-01-06 18:00:27 +01:00
zsviczian
3a2d064024 1.8.8 2023-01-06 17:57:05 +01:00
zsviczian
38cfdd4e0e corrected spelling of filename 2023-01-06 12:15:26 +01:00
zsviczian
fb93c0c352 publish updated scripts 2023-01-06 12:11:07 +01:00
zsviczian
f4fb1e3cc8 Alternative pen assets 2023-01-06 11:49:00 +01:00
zsviczian
5c11e5733e updated slideshow and deconstruct scripts 2023-01-02 16:09:21 +01:00
zsviczian
8d8f7a7866 1.8.7 2022-12-23 21:48:04 +01:00
zsviczian
da89e32213 1.8.6 2022-12-17 14:04:46 +01:00
zsviczian
b6d36e5076 Update manifest.json 2022-12-17 13:41:36 +01:00
zsviczian
90c377f125 1.8.5 2022-12-17 12:41:31 +01:00
zsviczian
df85138890 updated elbow connectors 2022-12-15 18:55:43 +01:00
zsviczian
654b656a2f Merge pull request #935 from 1-2-3/master
feat:add "Center connect points" option to "Elbow connectors" script
2022-12-15 18:54:26 +01:00
zsviczian
1d22dcb488 roundness 2022-12-12 23:17:50 +01:00
zahuifan
a42e907d0c feat:add "Center connect points" option. 2022-12-11 12:19:18 +08:00
zsviczian
353cad21d6 Update directory-info.json 2022-12-07 10:14:46 +01:00
zsviczian
2b02f186a6 Update Text Arch.svg 2022-12-07 10:13:47 +01:00
zsviczian
3e12d1e815 Update directory-info.json 2022-12-07 10:03:54 +01:00
zsviczian
539bbdf07f Merge pull request #929 from 1-2-3/master
fix: scripts not work with arrows that contain text.
2022-12-07 10:02:07 +01:00
zsviczian
b993b358fe 1.8.4 2022-12-06 22:51:54 +01:00
zahuifan
0639ea5969 fix: not work with arrows that contain text. 2022-12-06 12:15:46 +08:00
zsviczian
05b7bc6029 1.8.3-beta 2022-12-05 23:27:21 +01:00
zsviczian
c9755be0e9 organic line update 2022-12-04 22:16:27 +01:00
zsviczian
9526fb5726 cleanup script library 2022-12-04 21:36:36 +01:00
zsviczian
c04587ab5c added Uniform size script 2022-12-04 19:53:46 +01:00
zsviczian
ab94fe304b add auto layout.md 2022-12-04 18:47:04 +01:00
zsviczian
b080fec85e Merge pull request #922 from 1-2-3/master
add auto layout ea-script
2022-12-04 18:44:16 +01:00
zsviczian
c9972116b3 fixed #905 2022-12-04 17:00:30 +01:00
zahuifan
c254c8cc5d add direction suggester 2022-12-04 18:01:06 +08:00
zahuifan
14c2ce3766 add auto layout ea-script 2022-12-04 15:50:34 +08:00
zsviczian
437a01c194 1.8.2 2022-12-03 00:19:32 +01:00
zsviczian
da98aca107 add to file info 2022-12-02 22:44:12 +01:00
zsviczian
e81f4d3688 update photo 2022-12-02 22:23:42 +01:00
zsviczian
f280704744 update icon 2022-12-02 22:18:45 +01:00
zsviczian
9547ced85c publish slideshow 2022-12-02 22:12:58 +01:00
zsviczian
356a0b7a63 slideshow images 2022-12-02 22:06:18 +01:00
zsviczian
171e37b4e5 Merge pull request #916 from yentlprojects/fix-settings-typo
English settings page - Language/typo fixes
2022-12-01 07:33:41 +01:00
Yentl Projects
cfb070cfe5 English settings page - Language/typo fixes 2022-12-01 01:51:20 +01:00
zsviczian
76e2a32998 1.8.1 2022-11-29 20:19:12 +01:00
zsviczian
23a4f42c27 fix Black screen of death 2022-11-28 22:53:06 +01:00
zsviczian
8202cf0dde 1.8.1 beta 2022-11-27 23:10:36 +01:00
zsviczian
40f88bb900 Update README.md 2022-11-20 18:31:57 +01:00
zsviczian
e6f5f9469a 1.8.0 2022-11-20 17:59:42 +01:00
zsviczian
0502ac3bb0 Fix tools panel icon sizes, added save and open link actions, taskbone image size normalization 2022-11-19 21:31:11 +01:00
zsviczian
36125c9b83 fullscreen finish 2022-11-19 19:06:13 +01:00
zsviczian
cced2ca2e4 new-fullscreen mode 2022-11-19 18:51:37 +01:00
zsviczian
0de2c78cac added taskbone, fixed transclusion deconstruct 2022-11-19 18:23:59 +01:00
zsviczian
7848c8f705 1.7.30 2022-11-18 18:23:32 +01:00
zsviczian
f6c135227b rename to deconstruct 2022-11-15 23:42:50 +01:00
zsviczian
95ca41fcaa fix release notes 2022-11-15 21:21:09 +01:00
zsviczian
d7648d702a fixed release notes 2022-11-15 21:09:42 +01:00
zsviczian
5033a7cccf publish decompose script 2022-11-15 20:44:25 +01:00
zsviczian
1a83abb256 added decompose script image 2022-11-15 20:32:34 +01:00
zsviczian
08f616b5d9 1.7.29 2022-11-15 19:16:16 +01:00
zsviczian
ca44699e8d manifest-beta.json 2022-11-13 20:58:16 +01:00
zsviczian
e0111e264c Merge branch 'master' of https://github.com/zsviczian/obsidian-excalidraw-plugin 2022-11-13 20:32:00 +01:00
zsviczian
c6196a86a9 1.7.28 beta 2022-11-13 20:31:57 +01:00
zsviczian
3926e5c30b Update issue templates 2022-11-02 13:59:55 +01:00
zsviczian
a1256422fa Update issue templates 2022-11-02 13:58:09 +01:00
zsviczian
eeb47d4912 Update issue templates 2022-11-02 13:56:50 +01:00
zsviczian
8ceac4ab31 1.7.27 2022-11-01 11:42:39 +01:00
116 changed files with 12527 additions and 5210 deletions

View File

@@ -1,32 +1,30 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Environment (please complete the following information):**
- OS including version: [e.g. iOS 15.1, Android 9, Windows 11, etc]
- Plugin version:
- Obsidian version:
**Additional context**
Add any other context about the problem here.
---
name: Bug report
about: Create a report to help me improve Excalidraw
title: 'BUG: '
labels: ''
assignees: ''
---
**Your environment**
Please run `Command Palette/Show Debug info` in Obsidian and paste the result here.
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Additional context**
Add any other context about the problem here.

View File

@@ -1,20 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
---
name: Feature request
about: Suggest an idea for this project
title: 'FR: '
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

7
.gitignore vendored
View File

@@ -15,5 +15,8 @@ data.json
lib
#VSCode
.vscode
yarn.lock
.vscode
yarn.lock
.DS_Store
.lock
.lock

32
README-BUILD.md Normal file
View File

@@ -0,0 +1,32 @@
The project runs with `node 16.10.0`. Some packages will throw dependency errors if you try to compile with a higher node version.
After running `npm -i` you'll need to make two manual changes:
## postprocess
postprocess is used in rollup.config.js.
However, the version available on npmjs does not work, after installing packages you need this update:
`npm install brettz9/rollup-plugin-postprocess#update --save-dev``
More info here: https://github.com/developit/rollup-plugin-postprocess/issues/10
## colormaster
1.2.1 misses 3 plugin references after installing the package you need to update
`node_modules/colormaster/package.json` adding the following to the `exports:` section:
```typescript
,
"./plugins/luv": {
"import": "./plugins/luv.mjs",
"require": "./plugins/luv.js",
"default": "./plugins/luv.mjs"
},
"./plugins/uvw": {
"import": "./plugins/uvw.mjs",
"require": "./plugins/uvw.js",
"default": "./plugins/uvw.mjs"
},
"./plugins/ryb": {
"import": "./plugins/ryb.mjs",
"require": "./plugins/ryb.js",
"default": "./plugins/ryb.mjs"
}
```

349
README.md
View File

@@ -1,120 +1,287 @@
# Excalidraw
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.
Please upgrade to Obsidian v0.12.19 or higher to get the latest release.
## Video Walkthrough
![image](https://user-images.githubusercontent.com/14358394/125159831-336d6880-e17a-11eb-8a3d-ceabc2555a08.png)
<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>
# Video walkthrough
| | | |
|----|----|----|
|[![thumbnail](https://user-images.githubusercontent.com/14358394/156931370-aa4d88de-c4a8-46cc-aeb2-dc09aa0bea39.jpg)](https://youtu.be/o0exK-xFP3k)| | |
|[![Obsidian-Excalidraw 1.2.0 update - Major IMPROVEMENTS](https://user-images.githubusercontent.com/14358394/124356817-7b3f3d80-dc18-11eb-932d-363bb373c5ab.jpg)](https://youtu.be/UxJLLYtgDKE)|[![1 Getting Started](https://user-images.githubusercontent.com/14358394/125160304-7f211180-e17c-11eb-8363-c52723de1ffd.jpg)](https://youtu.be/sY4FoflGaiM)|[![2 Basic shapes and features](https://user-images.githubusercontent.com/14358394/125160312-8a743d00-e17c-11eb-9fa2-490ef4cbd59e.jpg)](https://youtu.be/Iy_oVTq12Gw)|
|[![3 Groups](https://user-images.githubusercontent.com/14358394/125160323-96f89580-e17c-11eb-9bce-8eb1067a51bb.jpg)](https://youtu.be/QOL1KF7-kdc)|[![4 Stencil](https://user-images.githubusercontent.com/14358394/125160332-9f50d080-e17c-11eb-98e9-fec60fe147d9.jpg)](https://youtu.be/aSgcbfspvfo)|[![5 embedding](https://user-images.githubusercontent.com/14358394/125160341-a546b180-e17c-11eb-9de8-d87fdc844c9c.jpg)](https://youtu.be/MaJ5jJwBRWs)|
|[![6 Links](https://user-images.githubusercontent.com/14358394/125160346-aa0b6580-e17c-11eb-930b-4024807040d1.jpg)](https://youtu.be/MXzeCOEExNo)|[![7 Markdown](https://user-images.githubusercontent.com/14358394/125160354-b2fc3700-e17c-11eb-81af-9e71e461f6dd.jpg)](https://youtu.be/R0IAg0s-wQE)|[![8 Templates](https://user-images.githubusercontent.com/14358394/125160360-b8f21800-e17c-11eb-8bd8-79d4e3f6e92d.jpg)](https://youtu.be/ibdS7ykwpW4)|
|[![9 Excalidraw Automate](https://user-images.githubusercontent.com/14358394/125160367-bdb6cc00-e17c-11eb-92f1-6f59faea85fd.jpg)](https://youtu.be/VRZVujfVab0)|[![10 Miscellaneous](https://user-images.githubusercontent.com/14358394/125160374-c3141680-e17c-11eb-8cc2-dfaffd903d15.jpg)](https://youtu.be/D1iBYo1_jjc)|[![Image Elements](https://user-images.githubusercontent.com/14358394/138607067-ccb62f92-48a4-4880-ac6e-68c1bf86ac2c.png)](https://www.youtube.com/watch?v=_c_0zpBJ4Xc&)|
|[![LaTex Demo](https://user-images.githubusercontent.com/14358394/143732412-1c65227e-4381-406d-847a-b001ab3506ca.jpg)](https://youtu.be/r08wk-58DPk)|[![markdown embeds](https://user-images.githubusercontent.com/14358394/143732440-90bfa029-8615-462e-ada3-c903d71a82c9.jpg)](https://youtu.be/tsecSfnTMow)|[![markdownAdvanced](https://user-images.githubusercontent.com/14358394/143783906-15cee494-c6d5-4495-a2ca-74634e4e7355.jpg)](https://youtu.be/K6qZkTz8GHs)|
|[![Script Engine](https://user-images.githubusercontent.com/14358394/145684531-8d9c2992-59ac-4ebc-804a-4cce1777ded2.jpg)](https://youtu.be/hePJcObHIso)|[![sticky notes thumbnail](https://user-images.githubusercontent.com/14358394/147283367-e5689385-ea51-4983-81a3-04d810d39f62.jpg)](https://youtu.be/NOuddK6xrr8)|[![plugin store](https://user-images.githubusercontent.com/14358394/147889174-6c306d0d-2d29-46cc-a53f-3f0013cf14de.jpg)](https://youtu.be/lzYdOQ6z8F0)|
|[![fourtfont](https://user-images.githubusercontent.com/14358394/149659524-2a4e0a24-40c9-4e66-a6b1-c92f3b88ecd5.jpg)](https://youtu.be/eKFmrSQhFA4)|[![thumbnail](https://user-images.githubusercontent.com/14358394/151705333-54e9ffd2-0bd7-4d02-b99e-0bd4e4708d4d.jpg)](https://youtu.be/qbPIAZguJeo)|[![Thumbnail](https://user-images.githubusercontent.com/14358394/152585752-7eb0371f-0bab-40f6-a194-3b48e5811735.jpg)](https://youtu.be/2Y8OhkGiTHg)|
|[![Thumbnail](https://user-images.githubusercontent.com/14358394/153676009-6f86b2d7-c248-49a2-b802-be21c6999e4f.jpg)](https://youtu.be/2v9TZmQNO8c)|[![Thumbnail](https://user-images.githubusercontent.com/14358394/154821232-a404b6cf-72fb-4ce4-9d53-619132dce491.jpg)](https://youtu.be/xHPGWR3m0c8)|[![Thumbnail](https://user-images.githubusercontent.com/14358394/156931428-b2269fd9-87bd-43ab-8558-5572f40dff93.jpg)](https://youtu.be/gMIKXyhS-dM)|
|[![thumbnail](https://user-images.githubusercontent.com/14358394/156931461-0979b821-315a-41dd-86f1-31d169b7c127.jpg)](https://youtu.be/Etskjw7a5zo)|[![Thumbnail](https://user-images.githubusercontent.com/14358394/158008902-12c6a851-237e-4edd-a631-d48e81c904b2.jpg)](https://youtu.be/4N6efq1DtH0)|[![thumbnail](https://user-images.githubusercontent.com/14358394/159369910-6371f08d-b5fa-454d-9c6c-948f7e7a7d26.jpg)](https://youtu.be/U2LkBRBk4LY)|
| [![6 strategies for linking your visual thoughts v4](https://user-images.githubusercontent.com/14358394/171635214-30533c45-94fa-436e-83a9-b2ec99f190e2.jpg)](https://youtu.be/qiKuqMcNWgU)|[![Video thumbnail small](https://user-images.githubusercontent.com/14358394/185791706-3d9983ab-7cb1-4b27-a016-30c039d84e34.jpg)](https://youtu.be/yZQoJg2RCKI)|[![Thumbnail - Colors - Excalidraw Basics (Custom)](https://user-images.githubusercontent.com/14358394/194773147-5418a0ab-6be5-4eb0-a8e4-d6af21b1b483.png)](https://youtu.be/6PLGHBH9VZ4) |
|[![Thumbnail - Excalidraw color palettes (Custom)](https://user-images.githubusercontent.com/14358394/194773211-9e871be7-0795-4dc7-947e-c6c275e690d0.png)](https://youtu.be/epYNx2FSf2w) | [![Thumbnail (Custom)](https://user-images.githubusercontent.com/14358394/194773268-400cfb1b-6bde-45e0-9e4b-91bbaa461cf0.png)](https://youtu.be/Amhlv6r9WvM) | [![Thumbnail - Simple rules for beautiful sketches (Custom) (1)](https://user-images.githubusercontent.com/14358394/194773527-ef35c8b9-1a6d-4415-9c7e-b667fb17535d.png)](https://youtu.be/r9oB1SlK1GU) |
|[![Thumbnail - ColorMaster Scripting (Custom)](https://user-images.githubusercontent.com/14358394/195988535-a133a9b9-d094-45ba-ba64-c994b9a1e0ef.png)](https://youtu.be/7gJDwNgQ6NU) | | |
<details><summary>10 Part (slightly outdated) Video Walkthrough</summary>
<a href="https://youtu.be/sY4FoflGaiM" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/125160304-7f211180-e17c-11eb-8363-c52723de1ffd.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;1 Getting Started</a><br>
<a href="https://youtu.be/Iy_oVTq12Gw" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/125160312-8a743d00-e17c-11eb-9fa2-490ef4cbd59e.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;2 Basic shapes and features</a><br>
<a href="https://youtu.be/QOL1KF7-kdc" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/125160323-96f89580-e17c-11eb-9bce-8eb1067a51bb.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;3 Grouping elements</a><br>
<a href="https://youtu.be/aSgcbfspvfo" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/125160332-9f50d080-e17c-11eb-98e9-fec60fe147d9.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;4 The stencil-library</a><br>
<a href="https://youtu.be/MaJ5jJwBRWs" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/125160341-a546b180-e17c-11eb-9de8-d87fdc844c9c.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;5 Embedding</a><br>
<a href="https://youtu.be/MXzeCOEExNo" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/125160346-aa0b6580-e17c-11eb-930b-4024807040d1.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;6 Links</a><br>
<a href="https://youtu.be/R0IAg0s-wQE" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/125160354-b2fc3700-e17c-11eb-81af-9e71e461f6dd.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;7 Markdown</a><br>
<a href="https://youtu.be/ibdS7ykwpW4" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/125160360-b8f21800-e17c-11eb-8bd8-79d4e3f6e92d.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;8 Templates</a><br>
<a href="https://youtu.be/VRZVujfVab0" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/125160367-bdb6cc00-e17c-11eb-92f1-6f59faea85fd.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;9 Excalidraw Automate</a><br>
<a href="https://youtu.be/D1iBYo1_jjc" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/125160374-c3141680-e17c-11eb-8cc2-dfaffd903d15.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;10 Miscellaneous</a><br>
</details>
<details><summary>Embedding stuff into Excalidraw</summary>
<a href="https://www.youtube.com/watch?v=_c_0zpBJ4Xc&" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/138607067-ccb62f92-48a4-4880-ac6e-68c1bf86ac2c.png" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Image Elements</a><br>
<a href="https://youtu.be/r08wk-58DPk" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/143732412-1c65227e-4381-406d-847a-b001ab3506ca.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;LaTex Demo</a><br>
<a href="https://youtu.be/tsecSfnTMow" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/143732440-90bfa029-8615-462e-ada3-c903d71a82c9.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Markdown embeds</a><br>
<a href="https://youtu.be/K6qZkTz8GHs" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/143783906-15cee494-c6d5-4495-a2ca-74634e4e7355.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Markdown embeds advanced features</a><br>
<a href="https://youtu.be/Etskjw7a5zo" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/156931461-0979b821-315a-41dd-86f1-31d169b7c127.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Link to Elements, Vertical text alignment, Markdown Styling</a><br>
</details>
<details><summary>The Script Engine Store - Excalidraw Automation</summary>
<a href="https://youtu.be/hePJcObHIso" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/145684531-8d9c2992-59ac-4ebc-804a-4cce1777ded2.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Introducing the Script Engine</a><br>
<a href="https://youtu.be/lzYdOQ6z8F0" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/147889174-6c306d0d-2d29-46cc-a53f-3f0013cf14de.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Script Enginge Store</a><br>
</details>
<details><summary>Working with colors</summary>
<a href="https://youtu.be/6PLGHBH9VZ4" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/194773147-5418a0ab-6be5-4eb0-a8e4-d6af21b1b483.png" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Colors - Excalidraw Basics (Custom)</a><br>
<a href="https://youtu.be/epYNx2FSf2w" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/194773211-9e871be7-0795-4dc7-947e-c6c275e690d0.png" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Excalidraw color palettes (Custom)</a><br>
<a href="https://youtu.be/Amhlv6r9WvM" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/194773268-400cfb1b-6bde-45e0-9e4b-91bbaa461cf0.png" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;"Artistic" Color Gradients</a><br>
<a href="https://youtu.be/r9oB1SlK1GU" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/194773527-ef35c8b9-1a6d-4415-9c7e-b667fb17535d.png" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Simple rules for beautiful sketches</a><br>
<a href="https://youtu.be/7gJDwNgQ6NU" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/195988535-a133a9b9-d094-45ba-ba64-c994b9a1e0ef.png" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;ColorMaster Scripting</a><br>
</details>
<details><summary>Links and block references</summary>
<a href="https://youtu.be/qiKuqMcNWgU" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/171635214-30533c45-94fa-436e-83a9-b2ec99f190e2.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;6 strategies for linking your visual thoughts v4</a><br>
<a href="https://youtu.be/yZQoJg2RCKI" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/185791706-3d9983ab-7cb1-4b27-a016-30c039d84e34.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Block reference parts of images</a><br>
<a href="https://youtu.be/Etskjw7a5zo" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/156931461-0979b821-315a-41dd-86f1-31d169b7c127.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Link to Elements, Vertical text alignment, Markdown Styling</a><br>
<a href="https://youtu.be/2Y8OhkGiTHg" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/152585752-7eb0371f-0bab-40f6-a194-3b48e5811735.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;How to guide for the Excalidraw-native hyperlinks</a><br>
</details>
<details><summary>Powertools</summary>
<a href="https://youtu.be/NOuddK6xrr8" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/147283367-e5689385-ea51-4983-81a3-04d810d39f62.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Sticky Notes (word wrapping)</a><br>
<a href="https://youtu.be/eKFmrSQhFA4" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/149659524-2a4e0a24-40c9-4e66-a6b1-c92f3b88ecd5.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Fourt Font</a><br>
<a href="https://youtu.be/vlC1-iBvIfo" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/199207784-8bbe14e0-7d10-47d7-971d-20dce8dbd659.png" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;SVG import</a><br>
<a href="https://youtu.be/7gu4ETx7zro" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/202916770-28f2fa64-1ba2-4b40-a7fe-d721b42634f7.png" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;OCR</a><br>
<a href="https://youtu.be/U2LkBRBk4LY" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/159369910-6371f08d-b5fa-454d-9c6c-948f7e7a7d26.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Bind/unbind text from container, Frontmatter tags to customize export</a><br>
<a href="https://youtu.be/uZz5MgzWXiM" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/211054371-8872e01a-77d6-4afc-a0c2-86a55410a8d3.png" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Custom pen support</a><br>
</details>
<details><summary>Quality of life improvements</summary>
<a href="https://youtu.be/qbPIAZguJeo" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/151705333-54e9ffd2-0bd7-4d02-b99e-0bd4e4708d4d.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Mobile Support</a><br>
<a href="https://youtu.be/2v9TZmQNO8c" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/153676009-6f86b2d7-c248-49a2-b802-be21c6999e4f.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Tray-mode and Customizable Color Palette</a><br>
<a href="https://youtu.be/xHPGWR3m0c8" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/154821232-a404b6cf-72fb-4ce4-9d53-619132dce491.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Compressed JSON and improved save/sync support</a><br>
<a href="https://youtu.be/gMIKXyhS-dM" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/156931428-b2269fd9-87bd-43ab-8558-5572f40dff93.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;The Obsidian Tools Panel</a><br>
<a href="https://youtu.be/4N6efq1DtH0" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/158008902-12c6a851-237e-4edd-a631-d48e81c904b2.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Eraser, left-handed mode, improved filename configuration</a><br>
</details>
---
## Features
# Key features
- The plugin integrates Excalidraw seamlessly into Obsidian including Command Palette actions, File Explorer features, Option Menu commands, and the Ribbon Button.
- <kbd>CTRL/CMD+Click</kbd> on the ribbon button, or in the file explorer to create / open drawings in a new pane.
- Settings will allow you to customize Excalidraw to your needs:
- Default folder for new drawings and define custom filename pattern for new drawings.
- Template for new drawings. The template will restore stroke properties. This means you can set up defaults in your template for stroke color, stroke width, opacity, font family, font size, fill style, stroke style, etc. This also applies to ExcalidrawAutomate.
- Via the template you can customize the color palette used by Excalidraw. Switch to Markdown view. Scroll down to the bottom of the file and find `"AppState": {`. Find `"customColorPalette": {` at the end of the AppState section. You may specify the 3 palettes used in Excalidraw by adding any or all of the following 3 variables: `"canvasBackground":[], "elementBackground":[], "elementStroke": []`. Add a comma separated list of valid HTML colors (e.g. `#FF0000` for red) in the array for each of the variables. See my videos above for further help.
- If portability is important to you: Auto-export SVG and/or PNG files including keep-in-sync feature so you can embed SVG/PNG into your documents instead of embedding excalidraw files. You can override export settings for an individual file by adding the `excalidraw-autoexport` frontmatter key. Valid values for this key are `none`, `both`, `png` and `svg`.
- Specify the default width of embedded drawings.
- Compatibility features to auto-export and keep in sync markdown excalidraw files and legacy .excalidraw files.
- Experimental feature to add custom TAG to file explorer to mark drawing files.
- Enable / disable autosave.
- You can customize the size and position of the embedded images using the `![[image.excalidraw|100]]`, `![[image.excalidraw|100x100]]`, `![[image.excalidraw|100|left]]`, `![[image.excalidraw|right-wrap]]`, formatting options. `![[<filename.excalidraw>|<width>x<height>|<alignment>]]`. You can add your custom [alignment via CSS](https://www.scaler.com/topics/align-image-in-html/). Any text that appears in `<alignment>` will be added to the rendered SVG element style and to the wrapper DIV element. See [styles.css](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/styles.css) for more insight.
- Supports hyperlinks e.g. `https://zsolt.blog`, `[Obsidian](https://obsidian.md)`, and internal links e.g. `[[My file in vault|Alias]]` in drawing text.
- Links will update when files are moved or renamed, if you have the Obsidian setting Files & Links/Automatically Update Internal Links enabled.
- Links in drawings will show up in backlinks of documents
- Transclusions are supported
- The plugin integrates Excalidraw seamlessly into Obsidian including Command Palette actions, File
Explorer features, Option Menu commands, and the Ribbon Button.
- <kbd>CTRL/CMD+Click</kbd> on the ribbon button, or in the file explorer to create / open drawings
in a new pane.
### Settings
Settings will allow you to customize Excalidraw to your needs. The plugin comes with tons of settings. I tried adding meaningful explanations to these settings, so please be patient and look for the setting, for most requests a setting already exists.
Plugin settings are grouped into the following sections:
- **Basic settings**: such as default folders to use
- **Saving**: compression and autosave timer
- **Filename**: configure the automatically created Excalidraw filename
- **Display**: settings that effect the handling of Excalidraw (e.g.: left-handed mode, theme settings, mouse wheel and pinch zoom settings, zoom to fit settings)
- **Links and transclusions**: Settings that effect how links and embedded items behave on the Excalidraw canvas
- **Markdown-embed settings**: These settings control how markdown documents from your Vault embedded into Excalidraw drawings will behave
- **Embed & Export**: Settings that control how Excalidraw images are displayed when embedding them into markdown documents
- **Auto-export Settings**: You can configure Excalidraw to create a PNG or SVG copy of your drawing each time it gets saved
- **Compatibility features**: Check these settings if you edit the Excalidraw drawings outside Obsidian (e.g. in LogSeq, Visual Studio, on the web, etc.)
- **Experimental features**: There are advanced features that are implemented as "clever" hacks. Features include defining a fourth font, adding a custom icon to distinguish Exalidraw files in the Obsidian file explorer, OCR settings, and more.
- **Settings for installed Scripts**: Some of the scripts you install from the Script Library come with settings. Script settings are installed the first time you run the script. So to access settings for a script, install the script, run it for the first time, then look for the settings in plugin settings.
#### Templates
- Template for new drawings. The template will restore stroke properties.
This means you can set up defaults in your template for stroke color, stroke width,
opacity, font family, font size, fill style, stroke style, etc.
This also applies to ExcalidrawAutomate.
- Via the template you can customize the color palette used by Excalidraw.
- Switch to Markdown view.
- Scroll down to the bottom of the file and find `"AppState": {`.
- Find `"customColorPalette": {` at the end of the AppState section.
- You may specify the 3 palettes used in Excalidraw by adding any or all of the following 3 variables:
- `"canvasBackground":[], "elementBackground":[], "elementStroke": []`.
- Add a comma separated list of valid HTML colors (e.g. `#FF0000` for red)
in the array for each of the variables.
- See my videos above for further help.
#### Export
- If portability is important to you:
- Auto-export SVG and/or PNG files including keep-in-sync feature so you can
embed SVG/PNG into your documents instead of embedding excalidraw files.
- You can override export settings for an individual file by adding the `excalidraw-autoexport`
frontmatter key. Valid values for this key are `none`, `both`, `png` and `svg`.
- Specify the default width of embedded drawings.
- Compatibility features to auto-export and keep in sync markdown excalidraw files and legacy `.excalidraw` files.
- Experimental feature to add custom TAG to file explorer to mark drawing files.
- Enable / disable autosave.
### Embedding your drawings into markdown documents
- You can customize the size and position of the embedded images using the
- `![[image.excalidraw|100]]`,
- `![[image.excalidraw|100x100]]`,
- `![[image.excalidraw|100|left]]`,
- `![[image.excalidraw|right-wrap]]`, formatting options.
- `![[<filename.excalidraw>|<width>x<height>|<alignment>]]`.
- You can add your custom [alignment via CSS](https://www.scaler.com/topics/align-image-in-html/).
- Any text that appears in `<alignment>` will be added to the rendered SVG element style and to the wrapper DIV element.
- See [styles.css](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/styles.css) for more insight.
- Excalidraw drawings do not display in Obsidian Publish. If you want to use Excalidraw in your published documents, you can configure in plugin settings, under `Embed & Export`, to automatically insert a PNG or SVG version of the drawing in your document when creating a new file. See `type of file to insert into document`
- Under `Export settings` you can also configure to automatically export a dark and light version of the image, in case your published site supports dark and light mode.
### Hyperlinks and Drag & Drop support
![](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/images/excalidraw-modifiers.png)
#### Hyperlinks
- Supports hyperlinks e.g.
- `https://zsolt.blog`,
- `[Obsidian](https://obsidian.md)`, and
- internal links e.g. `[[My file in vault|Alias]]` in drawing text.
- Links will update when files are moved or renamed, if you have the Obsidian
setting Files & Links/Automatically Update Internal Links enabled.
- Links in drawings will show up in backlinks of documents
- Transclusions are supported
- `![[myfile#^blockref]]` will convert in the drawing into the transcluded text of the block
- `![[myfile#section]]` also works, this will transclude the section
- you can also specify word wrapping for transcluded text by adding the max character count in curly brackets right after the transclusion e.g. `![[myfile#^blockref]]{40}` will wrap text at 40 characters.
- For convenience you can also use the command palette to insert links into drawings
- <kbd>CTRL/CMD + hover</kbd> to bring up the Obsidian quick preview for the link. (On Mac it is <kbd>CTRL+CMD+hover</kbd>).
- <kbd>CTRL/CMD + CLICK</kbd> a text element to open it as a link.
- <kbd>CTRL/CMD + ALT + CLICK</kbd> to create the file (if it does not yet exist) and open it
- <kbd>CTRL/CMD + SHIFT + CLICK</kbd> to open the file in a new pane
- <kbd>CTRL/CMD + ALT + SHIFT + CLICK</kbd> to create the file (if it does not yet exist) and open it in a new pane
- you can also specify word wrapping for transcluded text by adding the max character count
in curly brackets right after the transclusion e.g. `![[myfile#^blockref]]{40}` will wrap text at 40 characters.
- For convenience you can also use the command palette to insert links into drawings
- <kbd>CTRL/CMD + hover</kbd> to bring up the Obsidian quick preview for the link. (On Mac it is <kbd>CTRL+CMD+hover</kbd>).
- Using the block reference you can also reference & transclude text that appears on drawings, in other documents
- Insert LaTeX formulas using the Command Palette action "Insert LaTeX formula". You can edit formulas either in Markdown view, or by <kbd>CTRL/CMD + Click</kbd> on the formula.
- Drag & Drop support
- You can drag files from the Obsidian file explorer and they will become links to those files in Excalidraw.
- Dragging image files (PNG, SVG, JPG, ICO, GIF, WEBP, Excalidraw) from Obsidian's file explorer while pressing the <kbd>CTRL</kbd> (<kbd>SHIFT</kbd> on Mac) button will embed the image into your drawing.
- If in addition to <kbd>CTRL</kbd> or <kbd>SHIFT</kbd> you also hold down <kbd>ALT<kbd>, the image will be inserted at 100% of its size. ⚠ Note: this is a very niche feature with a very particular behavior that I built primarily for myself (even more so than other features in Excalidraw Obsidian - also built primarily for myself 😉)... This will reset your embedded image to 100% size every time you open the Excalidraw drawing, or in case you have embedded an Excalidraw drawing on your canvas inserted using this function, every time you update the embedded drawing, it will be scaled back to 100% size. This means that even if you resize the image on the drawing, it will reset to 100% the next time you open the file or you modify the original embedded object. This feature is useful when you decompose a drawing into separate Excalidraw files, but when combined onto a single canvas you want the individual pieces to maintain their actual sizes. I use this feature to construct Book-on-a-Page summaries from atomic drawings.
- You can drag and drop text from Markdown views onto Excalidraw.
- You can drag and drop web addresses from your browser and they will become links.
- Image support
- On iOS and Android you can add images from your camera by pressing the add image button in Excalidraw.
- You can copy/paste images into your drawing. Images will be saved in your vault.
- You can drag and drop images as explained above.
- Block referencing parts of images
- When referencing an element on the canvas in a link pointing to an Excalidraw file using the elementId or the section header (i.e. a Text Element containing the `# <Section title>`) - e.g. `[[file#^elementID]]`, you can add the `group=` prefix, e.g. `[[file#^group=elementID]]` or the `area=` prefix, e.g. `[[file#area=Section heading]]`.
- If the `group=` prefix is found Excalidraw will select the group of elements in the same group as the element referenced by the elementID (block reference) or the section heading.
#### Drag & Drop support
- You can drag files from the Obsidian file explorer and they will become links to those files in Excalidraw. See table above for the varios modifier key combinations.
- Note: anchoring an image to 100% of its size is a very niche feature with a very particular behavior that I built primarily for myself
- (even more so than other features in Excalidraw Obsidian - also built primarily for myself 😉).
- This will reset your embedded image to 100% size every time you open the Excalidraw drawing,
or in case you have embedded an Excalidraw drawing on your canvas inserted using this function,
every time you update the embedded drawing, it will be scaled back to 100% size.
- This means that even if you resize the image on the drawing, it will reset to 100% the next time you open
the file or you modify the original embedded object. This feature is useful when you
decompose a drawing into separate Excalidraw files, but when combined onto a single canvas
you want the individual pieces to maintain their actual sizes. I use this feature to
construct Book-on-a-Page summaries from atomic drawings.
- You can drag and drop text from Markdown views onto Excalidraw.
- You can drag and drop web addresses from your browser and they will become links.
- You can drag and drop YouTube links and thumbnails and they will be YouTube links with thumbnails in Excalidraw
### LaTeX
Insert LaTeX formulas using the Command Palette action "Insert LaTeX formula".
You can edit formulas either in Markdown view, or by <kbd>CTRL/CMD + Click</kbd> on the formula.
### Image support
- On iOS and Android you can add images from your camera by pressing the add image button in Excalidraw.
- You can copy/paste images into your drawing. Images will be saved in your vault.
- You can drag and drop images as explained above.
- URL link to images on the web: You can drag images from a webpage to Excalidraw. If you hold down the CTRL button while dropping the image to Excalidraw, the image will not be saved to your vault. Excalidraw will load the image from the URL. Note, that if you do not have internet access, or these images are deleted from the internet, they will also disappear from your drawing.
- If you page an image URL to excalidraw (simply click copy on the url, then click paste on the excalidraw canvas), the image will be inserted with a link to the image on the web. Again, the image won't be save to your vault, only the link.
- If you drop a YouTube video link it will be convereted into a thumbnail photo with an element link pointing to the video.
### Block referencing parts of images
For more details see this [video](https://youtu.be/yZQoJg2RCKI)
- When referencing an element on the canvas in a link pointing to an Excalidraw file using
- the elementId or the section header (i.e. a Text Element containing the `# <Section title>`)
- e.g. `[[file#^elementID]]`,
- you can add the `group=` prefix,
- e.g. `[[file#^group=elementID]]` or
- the `area=` prefix,
- e.g. `[[file#area=Section heading]]`.
- If the `group=` prefix is found Excalidraw will select the group of elements in the
same group as the element referenced by the elementID (block reference) or the section heading.
- If the `area=` prefix is found Excalidraw will insert a cutout of the image around the referenced element.
- Note that the `area=` selector is not supported when embedding Excalidraw as PNG into your markdown documents.
- Referencing the elementID of a text element without the `group=` or `area=` prefix will transclude the element as plain text. Referencing a non-Text Element (e.g. rectangle, ellipse, etc.) without the `group=` or `area=` prefix will result in an Obsidian error since these elementIds are not present in the Excalidraw markdown file as block references.
- Referencing the elementID of a text element without the `group=` or `area=` prefix will
transclude the element as plain text. Referencing a non-Text Element (e.g. rectangle,
ellipse, etc.) without the `group=` or `area=` prefix will result in an Obsidian error
since these elementIds are not present in the Excalidraw markdown file as block
references.
### Markdown
- Since 1.2.0 Drawing files are stored in Markdown files
- You can add tags to drawings
- You can add metadata to the YAML front matter of drawings
- Anything you add between the frontmatter and the `# Text Elements` heading will be ignored by Excalidraw, i.e. you can add whatever you like here, it will be preserved as part of the document.
- Excalidraw documents now show in graph view.
- The following front matter keys will customize how the drawing is displayed - overriding general settings:
- `excalidraw-link-prefix: "📍"` preview prefix for internal links
- `excalidraw-url-prefix: "🌐"` preview prefix for external links
- `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. 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-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.
- Embed complete markdown files into your drawings
- Drag from the desired file from the Obsidian file explorer and hold down <kbd>CTRL/CMD</kbd> while dropping the file onto the canvas.
- Use the command palette action: `Insert markdown file from vault`
- Use custom woff, woff2 or TTF font to display the document, you can set the default font to use under Excalidraw Settings.
- You can set a custom css for rendering the snapshot image of your markdown document. Only operating system standard fonts are supported as the font-family ([Win10](https://docs.microsoft.com/en-us/typography/fonts/windows_10_font_list), [Mac & iOS](https://developer.apple.com/fonts/system-fonts/)), plus you can set one additional custom font using the setting explained above. (for a demonstration watch this [video](https://youtu.be/K6qZkTz8GHs) and check out this [sample css](https://github.com/zsviczian/obsidian-excalidraw-plugin/discussions/281)).
- To help with styling you can observe the SVG snapshot of the markdown document created by Excalidraw. Open Obsidian Developer Console (<kbd>CTRL+Shift+i</kbd>) and execute the following command: `ExcalidrawAutomate.mostRecentMarkdownSVG`
- You can control appearance of the embedded markdown file on a file by file bases by adding the following front matter keys to your markdown document:
- You can add tags to drawings
- You can add metadata to the YAML front matter of drawings
- Anything you add between the frontmatter and the `# Text Elements` heading will be ignored by Excalidraw, i.e. you can add whatever you like here, it will be preserved as part of the document.
- Excalidraw documents now show in graph view.
- The following front matter keys will customize how the drawing is displayed - overriding general settings:
- `excalidraw-link-prefix: "📍"` preview prefix for internal links
- `excalidraw-url-prefix: "🌐"` preview prefix for external links
- `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. 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-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.
### Embed complete markdown files into your drawings
- Drag from the desired file from the Obsidian file explorer and hold down <kbd>SHIFT</kbd> while dropping the file onto the canvas.
- Use the command palette action: `Insert markdown file from vault`
- Use custom woff, woff2 or TTF font to display the document, you can set the default font to use under Excalidraw Settings.
- You can set a custom css for rendering the snapshot image of your markdown document.
Only operating system standard fonts are supported as the font-family (
[Win10](https://docs.microsoft.com/en-us/typography/fonts/windows_10_font_list),
[Mac & iOS](https://developer.apple.com/fonts/system-fonts/)
), plus you can set one additional custom font using the setting explained above.
- (for a demonstration watch this [video](https://youtu.be/K6qZkTz8GHs) and check out this
- [sample css](https://github.com/zsviczian/obsidian-excalidraw-plugin/discussions/281)).
- To help with styling you can observe the SVG snapshot of the markdown document created by Excalidraw.
- Open Obsidian Developer Console (<kbd>CTRL+Shift+i</kbd>/<kbd>CMD+OPT+i</kbd>) and
- execute the following command: `ExcalidrawAutomate.mostRecentMarkdownSVG`
- You can control appearance of the embedded markdown file on a file by file
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).
- `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).
- `excalidraw-border-color: css-color-name|#HEXcolor|any-other-html-standard-format`
- `excalidraw-css: "css-filename|css snippet"`
- Switch to markdown view or use <kbd>CTRL/CMD+ALT/OPT</kbd> click on the image to edit properties of the embed: `[[filename#^blockref|WIDTHxMAXHEIGHT]]`
- Includes full [QuickAdd](https://github.com/chhoumann/quickadd), [Templater](https://silentvoid13.github.io/Templater/) and [Dataview](https://blacksmithgu.github.io/obsidian-dataview/docs/api/intro/) support through ExcalidrawAutomate. Check out the [detailed help + examples](https://zsviczian.github.io/obsidian-excalidraw-plugin/). I also have a [YouTube ExcalidrawAutomate Playlist](https://www.youtube.com/playlist?list=PL6mqgtMZ4NP1IR4nXxSlMA4PA5E-qpyHZ) with lots of examples.
- Since 1.5.0 you can easily execute ExcalidrawAutomate macros and assign command palette shortcuts to them, using the ScriptEngine. You will find an intro video and a growing library of ready to install scripts [here](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts).
- Switch to markdown view or use <kbd>WIN+CTRL</kbd>/<kbd>CMD+CTRL</kbd> click on the image to edit properties of the embed:
- `[[filename#^blockref|WIDTHxMAXHEIGHT]]`
### Custom Font, Custom Pen, OCR support, SVG import
- In plugin settings you can add a custom 4th font. For more details see this [video](https://youtu.be/eKFmrSQhFA4)
- The plugin includes OCR support using Taskbone OCR. For more details see this [video](https://youtu.be/7gu4ETx7zro)
- You can convert SVG files into Excalidraw drawings (with some limitation). For more details see this [video](https://youtu.be/vlC1-iBvIfo)
- You can define custom freedraw pens. See documentation [here](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Alternative%20Pens.md), [video](https://youtu.be/uZz5MgzWXiM)
### Script Engine
- Since 1.5.0 you can easily execute ExcalidrawAutomate macros and assign command palette shortcuts to them, using the ScriptEngine. You will find an intro video and a growing library of ready to install scripts [here](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts).
- You can organize scripts into groups on the Obsidian Tools Panel in Excalidraw by moving scripts and accompanying SVG icon files to folders. See demo [video](https://youtu.be/wTtaXmRJ7wg?t=16).
### Other
- Left-handed mode
- Includes full
- [QuickAdd](https://github.com/chhoumann/quickadd),
- [Templater](https://silentvoid13.github.io/Templater/) and
- [Dataview](https://blacksmithgu.github.io/obsidian-dataview/docs/api/intro/) support through ExcalidrawAutomate.
- Check out the [detailed help + examples](https://zsviczian.github.io/obsidian-excalidraw-plugin/).
- I also have a [YouTube ExcalidrawAutomate Playlist](https://www.youtube.com/playlist?list=PL6mqgtMZ4NP1IR4nXxSlMA4PA5E-qpyHZ) with lots of examples.
- REQUIRES AN OBSIDIAN SYNC SUBSCRIPTION: Full drawing file history and synchronization between devices
- Multilanguage support: if you'd like to help out by translating the plugin, please get in contact with me.
# Feedback, questions, ideas, problems
Join the conversation about the Excalidraw plugin on [forum.obsidian.md](https://forum.obsidian.md/t/excalidraw-full-featured-sketching-plugin-in-obsidian)
---
Please head over to [GitHub](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues) to report a bug or request an enhancement.
## Feedback, questions, ideas, problems
# Say Thank You
If you are enjoying Excalidraw then please support my work and enthusiasm by buying me a coffee on [https://ko-fi/zsolt](https://ko-fi.com/zsolt).
Join the conversation about the Excalidraw plugin on
[forum.obsidian.md](https://forum.obsidian.md/t/excalidraw-full-featured-sketching-plugin-in-obsidian)
Please also help spread the word by sharing about the Obsidian Excalidraw Plugin on Twitter, Reddit, or any other social media platform you regularly use.
Please head over to [GitHub](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues) to
report a bug or request an enhancement.
---
## Say Thank You
If you are enjoying Excalidraw then please support my work and enthusiasm by buying me a coffee on
[https://ko-fi/zsolt](https://ko-fi.com/zsolt).
Please also help spread the word by sharing about the Obsidian Excalidraw Plugin on Twitter, Reddit,
or any other social media platform you regularly use.
You can find me on Twitter [@zsviczian](https://twitter.com/zsviczian), and on my blog [zsolt.blog](https://zsolt.blog).
[<img style="float:left" src="https://user-images.githubusercontent.com/14358394/115450238-f39e8100-a21b-11eb-89d0-fa4b82cdbce8.png" width="200">](https://ko-fi.com/zsolt)
# Friends of Excalidraw
---
## Friends of Excalidraw
If you enjoy Excalidraw, consider giving [ExcaliBrain](https://github.com/zsviczian/excalibrain) a try (also available via Obsidian Community Plugins).
[![thumbnail](https://user-images.githubusercontent.com/14358394/169708346-9e41289d-9536-43ec-8f70-2d2ad2d369d6.png)](https://youtu.be/gOkniMkDPyM)
<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>

14
TODO.md
View File

@@ -1,14 +0,0 @@
[x] do not embed font into SVG when embedding Excalidraw into other Excalidraw
[x] add ```html <SVG>...</SVG> ``` codeblock to excalidraw markdown
[x] read pre-saved `<SVG>` when generating image preview
[x] update code to adopt change files moving from AppState to App
- Add "files" to legacy excalidraw export
[x] PNG preview
[x] markdown embed SVG 190
[x] markdown embed PNG
[x] embed Excalidraw into other Excalidraw

View File

@@ -0,0 +1,208 @@
/*
IF YOU ACCIDENTLY MODIFY THIS FILE AND IT STOPS WORKING, SIMPLY DOWNLOAD IT AGAIN FROM THE SCRIPT LIBRARY.
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-alternative-pens.jpg)
# How to create a new pen template
It takes a bit of experimentation and skill to create a new pen, so be patient.
1. Create a folder in your Vault for your pen options. The default is `Excalidraw/Pens`.
2. Create a new markdown file in your in the `pen folder` (e.g. `My pen`).
3. Copy the following template to the markdown file.
```json
{
"highlighter": true,
"constantPressure": false,
"hasOutline": true,
"outlineWidth": 4,
"options": PASTE_PREFECT_FREEHAND_OPTIONS_HERE
}
```
4. If you don't want your pen to have an outline around your line, change `hasOutline` to `false`. You can also modify `outlineWidth` if you want a thinner or thicker outline around your line.
5. If you want your pen to be pressure sensitive (when drawing with a mouse the pressure is simulated based on the speed of your hand) leave `constantPressure` as `false`. If you want a constant line width regardless of speed and pen pressure, change it to `true`.
6. `highlighter` true will place the new line behind the existing strokes (i.e. like a highlighter pen). If `highlighter` is missing or it is set to `false` the new line will appear at the top of the existing strokes (the default behavior of Excalidraw pens).
7. Go to https://perfect-freehand-example.vercel.app/ and configure your pen.
8. Click `Copy Options`.
9. Go back to the pen file you created in step No.2 and replace the placeholder text with the options you just copied from perfect-freehand.
10. Look for `easing` in the file and replace the function e.g. `(t) => t*t,` with the name of the function in brackets (in this example it would be `easeInQuad`). You will find the function name on the perfect-freehand website, only change the first letter to be lower case.
11. Test your pen in Excalidraw by clicking the `Alternative Pens` script and selecting your new pen.
# Example pens
My pens: https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts/pens
**Fine tipped pen:**
```json
{
constantPressure: true,
options: {
smoothing: 0.4,
thinning: -0.5,
streamline: 0.4,
easing: "linear",
start: {
taper: 5,
cap: false,
},
end: {
taper: 5,
cap: false,
},
}
}
```
**Thick marker:**
```json
{
constantPressure: true,
hasOutline: true,
outlineWidth: 4,
options: {
thinning: 1,
smoothing: 0.5,
streamline: 0.5,
easing: "linear",
start: {
taper: 0,
cap: true
},
end: {
taper: 0,
cap: true
}
}
}
```
**Fountain pen:**
```json
{
options: {
smoothing: 0.22,
thinning: 0.8,
streamline: 0.22,
easing: "easeInQuad",
start: {
taper: true,
cap: true,
},
end: {
taper: 1,
cap: true,
},
}
}
```
# Notes about the pen options
Note, that custom pens are currently not supported by Excalidraw.com. I've submitted a [PR](https://github.com/excalidraw/excalidraw/pull/6069) but there is no guarantee that it will get pushed to production. Your Excalidraw drawing can still be loaded to Excalidraw, but the special pen effects will not be visible there.
If you set a pen in your Excalidraw template file, that pen will be loaded automatically when you create a file using that template. Similarly, when you save a document, it will save your current pen settings as well. The next time you open the document, you can continue to use the same pen.
Pen options are saved with the stroke. This means, that even if you change the ped definition later on, your existing drawings will not be effected.
`outlineWidth` is relative to `strokeWidth`. i.e. if you make the stroke thinner in Excalidraw, the outline will become proportionally thinner as well. `outlineWidth` is only used if `hasOutline` is set to true.
If you don't want your pen to be pressure/speed sensitive, set `constantPressure` to `true`. Setting `constantPressure` to `true` automatically sets `simulatePressure` to `false`.
If you want your pen to be speed sensitive (i.e. the faster you draw the line the thinner it gets), set `options.simulatePressure` to `true`. If you omit `simulatePressure` from `options` then excalidraw will detect if you are drawing with a mouse or a pen and use pen pressures if available.
You can read more about configuring perfect freehand here: https://github.com/steveruizok/perfect-freehand#documentation
Excalidraw supports all of the easing functions listed here: https://easings.net/#, plus "linear". You can also find details about these easing functions here:
https://github.com/ai/easings.net/blob/master/src/easings/easingsFunctions.ts
From a performance perspective I recommend linear easing.
# The script
```javascript */
//--------------------------
// Load settings
//--------------------------
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.8.8")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
const api = ea.getExcalidrawAPI();
let settings = ea.getScriptSettings();
//set default values on first run
if(!settings["Pen folder"]) {
settings = {
"Pen folder" : {
value: "Excalidraw/Pens",
description: "The path to the folder where you store the perfect freehand options"
}
};
ea.setScriptSettings(settings);
}
let penFolder = settings["Pen folder"].value.toLowerCase();
if(penFolder === "" || penFolder === "/") {
new Notice("The pen folder cannot be the root folder of your vault");
return;
}
if(!penFolder.endsWith("/")) penFolder += "/";
//--------------------------
// Select pen
//--------------------------
const pens = app.vault.getFiles()
.filter(f=>f.extension === "md" && f.path.toLowerCase() === penFolder + f.name.toLowerCase())
.sort((a,b)=>a.basename.toLowerCase()<b.basename.toLowerCase()?-1:1);
if(pens.length === 0) {
const notice = new Notice(`You don't seem to have any pen definition files. Click this message to open the how-to guide.`,4000);
notice.noticeEl.onclick = async () => app.workspace.openLinkText(utils.scriptFile.path,"","tab");
return;
}
const file = await utils.suggester(["Excalidraw Default"].concat(pens.map(f=>(f.name.slice(0,f.name.length-3)))),["Default"].concat(pens), "Choose a pen preset, press ESC to abort");
if(!file) return;
if(file === "Default") {
api.updateScene({
appState: {
currentStrokeOptions: undefined
}
});
return;
}
//--------------------------
// Load pen
//--------------------------
const pen = await app.vault.read(file);
const parseJSON = (data) => {
try {
return JSON.parse(data);
} catch(e) {
try {
return JSON.parse(data.replaceAll(/\s(\w*)\:\s/g,' "$1": ').replaceAll(/,([^\w]*?})/gm,"$1"));
} catch(ee) {
const notice = new Notice(`Error loading the pen file. Maybe you accidently copy/pasted the easing function from perfect freehand website? Check the error message in Developer Console.\n(click=dismiss, right-click=Info) `,5000);
notice.noticeEl.oncontextmenu = async () => app.workspace.openLinkText(utils.scriptFile.path,"","tab");
console.error(ee);
console.error(data.replaceAll(/\s(\w*)\:\s/g,' "$1": ').replaceAll(/,([^\w]*?})/gm,"$1"));
return;
}
}
}
penJSON = parseJSON(pen);
if(!penJSON || typeof penJSON !== 'object') return;
//--------------------------
// Apply pen
//--------------------------
await api.updateScene({
appState: {
currentStrokeOptions: penJSON
}
});
api.setActiveTool({type:"freedraw"});

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d="M373.5 27.1C388.5 9.9 410.2 0 433 0c43.6 0 79 35.4 79 79c0 22.8-9.9 44.6-27.1 59.6L277.7 319l-10.3-10.3-64-64L193 234.3 373.5 27.1zM170.3 256.9l10.4 10.4 64 64 10.4 10.4-19.2 83.4c-3.9 17.1-16.9 30.7-33.8 35.4L24.4 510.3l95.4-95.4c2.6 .7 5.4 1.1 8.3 1.1c17.7 0 32-14.3 32-32s-14.3-32-32-32s-32 14.3-32 32c0 2.9 .4 5.6 1.1 8.3L1.7 487.6 51.5 310c4.7-16.9 18.3-29.9 35.4-33.8l83.4-19.2z"/></svg>

After

Width:  |  Height:  |  Size: 632 B

View File

@@ -1,120 +1,120 @@
/*
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-ocr.jpg)
THIS SCRIPT REQUIRES EXCALIDRAW 1.5.15
The script will
1) send the selected image file to [taskbone.com](https://taskbone.com) to exctract the text from the image, and
2) will add the text to your drawing as a text element
I recommend also installing the [Transfer TextElements to Excalidraw markdown metadata](Transfer%20TextElements%20to%20Excalidraw%20markdown%20metadata.md) script as well.
The script is based on [@schlundd](https://github.com/schlundd)'s [Obsidian-OCR-Plugin](https://github.com/schlundd/obsidian-ocr-plugin)
See ScriptEngine documentation for more details:
https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html
```javascript
*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.5.24")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
let token = ea.getScriptSettings().token?.value??ea.getScriptSettings().token;
const BASE_URL = "https://ocr.taskbone.com";
//convert setting to 1.5.21 format
if(token && !ea.getScriptSettings().token.value) {
ea.setScriptSettings({token: {value: token, hidden: true}});
}
//get new token if token was not provided
if (!token) {
const tokenResponse = await fetch(
BASE_URL + "/get-new-token", {
method: 'post'
});
if (tokenResponse.status === 200) {
jsonResponse = await tokenResponse.json();
token = jsonResponse.token;
ea.setScriptSettings({token: {value: token, hidden: true}});
} else {
notice(`Taskbone OCR Error: ${tokenResponse.status}\nPlease try again later.`);
return;
}
}
//get image element
//if multiple image elements were selected prompt user to choose
const imageElements = ea.getViewSelectedElements().filter((el)=>el.type==="image");
//need to save the view to ensure recently pasted images are saved as files
await ea.targetView.save();
let selectedImageElement = null;
switch (imageElements.length) {
case 0:
return;
case 1:
selectedImageElement = imageElements[0];
break;
default:
const files = imageElements.map((el)=>ea.getViewFileForImageElement(el));
selectedImageElement = await utils.suggester(files.map((f)=>f.name),imageElements);
break;
}
if(!selectedImageElement) {
notice("No image element was selected");
return;
}
const imageFile = ea.getViewFileForImageElement(selectedImageElement);
if(!imageFile) {
notice("Can read image file");
return;
}
//Execute the OCR
let text = null;
const fileBuffer = await app.vault.readBinary(imageFile);
const formData = new FormData();
formData.append("image", new Blob([fileBuffer]))
try {
const response = await fetch(
BASE_URL + "/get-text", {
headers: {
Authorization: "Bearer " + token
},
method: "post",
body: formData
});
if (response.status == 200) {
jsonResponse = await response.json();
text = jsonResponse?.text;
} else {
notice(`Could not read Text from ${file.path}:\n Error: ${response.status}`);
return;
}
} catch (error) {
notice(`The OCR service seems unavailable right now. Please try again later.`);
return;
}
if(!text) {
notice("No text found");
return;
}
console.log({text});
//add text element to drawing
const id = ea.addText(selectedImageElement.x,selectedImageElement.y+selectedImageElement.height,text);
await ea.addElementsToView();
ea.selectElementsInView([ea.getElement(id)]);
ea.getExcalidrawAPI().zoomToFit(ea.getViewSelectedElements(),1);
//utility function
function notice(message) {
new Notice(message,10000);
console.log(message);
}
/*
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-ocr.jpg)
THIS SCRIPT REQUIRES EXCALIDRAW 1.5.15
The script will
1) send the selected image file to [taskbone.com](https://taskbone.com) to exctract the text from the image, and
2) will add the text to your drawing as a text element
I recommend also installing the [Transfer TextElements to Excalidraw markdown metadata](Transfer%20TextElements%20to%20Excalidraw%20markdown%20metadata.md) script as well.
The script is based on [@schlundd](https://github.com/schlundd)'s [Obsidian-OCR-Plugin](https://github.com/schlundd/obsidian-ocr-plugin)
See ScriptEngine documentation for more details:
https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html
```javascript
*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.5.24")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
let token = ea.getScriptSettings().token?.value??ea.getScriptSettings().token;
const BASE_URL = "https://ocr.taskbone.com";
//convert setting to 1.5.21 format
if(token && !ea.getScriptSettings().token.value) {
ea.setScriptSettings({token: {value: token, hidden: true}});
}
//get new token if token was not provided
if (!token) {
const tokenResponse = await fetch(
BASE_URL + "/get-new-token", {
method: 'post'
});
if (tokenResponse.status === 200) {
jsonResponse = await tokenResponse.json();
token = jsonResponse.token;
ea.setScriptSettings({token: {value: token, hidden: true}});
} else {
notice(`Taskbone OCR Error: ${tokenResponse.status}\nPlease try again later.`);
return;
}
}
//get image element
//if multiple image elements were selected prompt user to choose
const imageElements = ea.getViewSelectedElements().filter((el)=>el.type==="image");
//need to save the view to ensure recently pasted images are saved as files
await ea.targetView.save();
let selectedImageElement = null;
switch (imageElements.length) {
case 0:
return;
case 1:
selectedImageElement = imageElements[0];
break;
default:
const files = imageElements.map((el)=>ea.getViewFileForImageElement(el));
selectedImageElement = await utils.suggester(files.map((f)=>f.name),imageElements);
break;
}
if(!selectedImageElement) {
notice("No image element was selected");
return;
}
const imageFile = ea.getViewFileForImageElement(selectedImageElement);
if(!imageFile) {
notice("Can read image file");
return;
}
//Execute the OCR
let text = null;
const fileBuffer = await app.vault.readBinary(imageFile);
const formData = new FormData();
formData.append("image", new Blob([fileBuffer]))
try {
const response = await fetch(
BASE_URL + "/get-text", {
headers: {
Authorization: "Bearer " + token
},
method: "post",
body: formData
});
if (response.status == 200) {
jsonResponse = await response.json();
text = jsonResponse?.text;
} else {
notice(`Could not read Text from ${file.path}:\n Error: ${response.status}`);
return;
}
} catch (error) {
notice(`The OCR service seems unavailable right now. Please try again later.`);
return;
}
if(!text) {
notice("No text found");
return;
}
console.log({text});
//add text element to drawing
const id = ea.addText(selectedImageElement.x,selectedImageElement.y+selectedImageElement.height,text);
await ea.addElementsToView();
ea.selectElementsInView([ea.getElement(id)]);
ea.getExcalidrawAPI().zoomToFit(ea.getViewSelectedElements(),1);
//utility function
function notice(message) {
new Notice(message,10000);
console.log(message);
}

View File

Before

Width:  |  Height:  |  Size: 1.0 KiB

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

Before

Width:  |  Height:  |  Size: 605 B

After

Width:  |  Height:  |  Size: 605 B

View File

@@ -1,44 +1,44 @@
/*
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-download-raw.jpg)
Download this file and save to your Obsidian Vault including the first line, or open it in "Raw" and copy the entire contents to Obsidian.
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-to-metadata.jpg)
The script will delete the selected text elements from the canvas and will copy the text from these text elements into the Excalidraw markdown file as metadata. This means, that the text will no longer be visible in the drawing, however you will be able to search for the text in Obsidian and find the drawing containing this image.
See ScriptEngine documentation for more details:
https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html
```javascript
*/
//get text elements
const textElements = ea.getViewSelectedElements().filter((el)=>el.type==="text");
if(textElements.length===0) {
notice("No text elements were selected")
return;
}
metadata = "# Metadata\n" + textElements
.map((el)=>el.rawText.replaceAll(/%|\^/g,"_")) //cleaning these characters for safety, might not be needed
.join("/n") + "\n";
ea.deleteViewElements(textElements);
await ea.targetView.save();
data = await app.vault.read(ea.targetView.file);
splitAfterFrontmatter = data.split(/(^---[\w\W]*?---\n)/);
if(splitAfterFrontmatter.length !== 3) {
notice("Error locating frontmatter in markdown file");
console.log({file:ea.targetView.file});
return;
}
newData = splitAfterFrontmatter[1]+metadata+splitAfterFrontmatter[2]
await app.vault.modify(ea.targetView.file,newData);
//utility function
function notice(message) {
new Notice(message);
console.log(message);
}
/*
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-download-raw.jpg)
Download this file and save to your Obsidian Vault including the first line, or open it in "Raw" and copy the entire contents to Obsidian.
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-to-metadata.jpg)
The script will delete the selected text elements from the canvas and will copy the text from these text elements into the Excalidraw markdown file as metadata. This means, that the text will no longer be visible in the drawing, however you will be able to search for the text in Obsidian and find the drawing containing this image.
See ScriptEngine documentation for more details:
https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html
```javascript
*/
//get text elements
const textElements = ea.getViewSelectedElements().filter((el)=>el.type==="text");
if(textElements.length===0) {
notice("No text elements were selected")
return;
}
metadata = "# Metadata\n" + textElements
.map((el)=>el.rawText.replaceAll(/%|\^/g,"_")) //cleaning these characters for safety, might not be needed
.join("/n") + "\n";
ea.deleteViewElements(textElements);
await ea.targetView.save();
data = await app.vault.read(ea.targetView.file);
splitAfterFrontmatter = data.split(/(^---[\w\W]*?---\n)/);
if(splitAfterFrontmatter.length !== 3) {
notice("Error locating frontmatter in markdown file");
console.log({file:ea.targetView.file});
return;
}
newData = splitAfterFrontmatter[1]+metadata+splitAfterFrontmatter[2]
await app.vault.modify(ea.targetView.file,newData);
//utility function
function notice(message) {
new Notice(message);
console.log(message);
}

View File

@@ -1,348 +1,348 @@
If you are enjoying the Excalidraw plugin then please support my work and enthusiasm by buying me a coffee on [https://ko-fi/zsolt](https://ko-fi.com/zsolt).
[<img src="https://user-images.githubusercontent.com/14358394/115450238-f39e8100-a21b-11eb-89d0-fa4b82cdbce8.png" class="coffee">](https://ko-fi.com/zsolt)
---
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>
Script Engine scripts are installed in the `Downloaded` subfolder of the `Excalidraw Automate script folder` specified in plugin settings.
In the `Command Palette` installed scripts are prefixed with `Downloaded/`, thus you can always know if you are executing a local script of your own, or one that you have downloaded from GitHub.
## Attention developers and hobby hackers
<img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/hobby-programmer.svg' align='left' style='background-color:whitesmoke; width:80px; margin-right:15px; margin-bottom:10px;'/>
If you want to modify scripts, I recommend moving them to the `Excalidraw Automate script folder` or a different subfolder under the script folder. Scripts in the `Downloaded` folder will be overwritten when you click the `Update this script` button. Note also, that at this time, I do not check if the script file has been updated on GitHub, thus the `Update this script` button is always visible once you have installed a script, not only when an update is availble (hope to build this feature in the future).
I would love to include your contribution in the script library. If you have a script of your own that you would like to share with the community, please open a [PR](https://github.com/zsviczian/obsidian-excalidraw-plugin/pulls) on GitHub. Be sure to include the following in your pull request
- The [script file](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts) with a self explanetory name. The name of the file will be the name of the script in the Command Palette.
- An [image](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/images) explaining the scripts purpose. Remember a picture speaks thousand words!
- An update to this file [ea-scripts/index.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/index.md)
---
# List of available scripts
- [[#Add Connector Point]]
- [[#Add Link to Existing File and Open]]
- [[#Add Link to New Page and Open]]
- [[#Add Next Step in Process]]
- [[#Box Each Selected Groups]]
- [[#Box Selected Elements]]
- [[#Change shape of selected elements]]
- [[#Connect elements]]
- [[#Convert freedraw to line]]
- [[#Convert selected text elements to sticky notes]]
- [[#Convert text to link with folder and alias]]
- [[#Copy Selected Element Styles to Global]]
- [[#Create new markdown file and embed into active drawing]]
- [[#Darken background color]]
- [[#Elbow connectors]]
- [[#Expand rectangles horizontally keep text centered]]
- [[#Expand rectangles horizontally]]
- [[#Expand rectangles vertically keep text centered]]
- [[#Expand rectangles vertically]]
- [[#Fixed horizontal distance between centers]]
- [[#Fixed inner distance]]
- [[#Fixed spacing]]
- [[#Fixed vertical distance between centers]]
- [[#Fixed vertical distance]]
- [[#Lighten background color]]
- [[Mindmap connector]]
- [[#Modify background color opacity]]
- [[#Normalize Selected Arrows]]
- [[#OCR - Optical Character Recognition]]
- [[#Organic Line]]
- [[#Repeat Elements]]
- [[#Reverse arrows]]
- [[#Scribble Helper]]
- [[#Select Elements of Type]]
- [[#Set background color of unclosed line object by adding a shadow clone]]
- [[#Set Dimensions]]
- [[#Set Font Family]]
- [[#Set Grid]]
- [[#Set Link Alias]]
- [[#Set Stroke Width of Selected Elements]]
- [[#Set Text Alignment]]
- [[#Split text by lines]]
- [[#Toggle Fullscreen on Mobile]]
- [[#Transfer TextElements to Excalidraw markdown metadata]]
- [[#Zoom to Fit Selected Elements]]
## Add Connector Point
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Connector%20Point.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/Add%20Connector%20Point.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will add a small circle to the top left of each text element in the selection and add the text and the "connector point" to a group. You can use the connector points to link text elements with an arrow (in for example a Wardley Map).<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-bullet-point.jpg'></td></tr></table>
## Add Link to Existing File and Open
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20Existing%20File%20and%20Open.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/Add%20Link%20to%20Existing%20File%20and%20Open.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Prompts for a file from the vault. Adds a link to the selected element pointing to the selected file. You can control in settings to open the file in the current active pane or an adjacent pane.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-link-and-open.jpg'></td></tr></table>
## Add Link to New Page and Open
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20New%20Page%20and%20Open.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/Add%20Link%20to%20New%20Page%20and%20Open.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Prompts for filename. Offers option to create and open a new Markdown or Excalidraw document. Adds link pointing to the new file, to the selected objects in the drawing. You can control in settings to open the file in the current active pane or an adjacent pane.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-link-to-new-page-and-pen.jpg'></td></tr></table>
## Add Next Step in Process
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Next%20Step%20in%20Process.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/Add%20Next%20Step%20in%20Process.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will prompt you for the title of the process step, then will create a stick note with the text. If an element is selected then the script will connect this new step with an arrow to the previous step (the selected element). If no element is selected, then the script assumes this is the first step in the process and will only output the sticky note with the text that was entered.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-process-step.jpg'></td></tr></table>
## Box Each Selected Groups
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Box%20Each%20Selected%20Groups.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/Box%20Each%20Selected%20Groups.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will add encapsulating boxes around each of the currently selected groups in Excalidraw.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-box-each-selected-groups.png'></td></tr></table>
## Box Selected Elements
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Box%20Selected%20Elements.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Box%20Selected%20Elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will add an encapsulating box around the currently selected elements in Excalidraw.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-box-elements.jpg'></td></tr></table>
## Change shape of selected elements
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Change%20shape%20of%20selected%20elements.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Change%20shape%20of%20selected%20elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script allows you to change the shape of selected Rectangles, Diamonds and Ellipses.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-change-shape.jpg'></td></tr></table>
## Connect elements
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Connect%20elements.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Connect%20elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will connect two objects with an arrow. If either of the objects are a set of grouped elements (e.g. a text element grouped with an encapsulating rectangle), the script will identify these groups, and connect the arrow to the largest object in the group (assuming you want to connect the arrow to the box around the text element).<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-connect-elements.jpg'></td></tr></table>
## Convert freedraw to line
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20freedraw%20to%20line.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/Convert%20freedraw%20to%20line.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Convert selected freedraw objects into editable lines. This will allow you to adjust your drawings by dragging line points and will also allow you to select shape fill in case of enclosed lines. You can adjust conversion point density in settings.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-convert-freedraw-to-line.jpg'></td></tr></table>
## Convert selected text elements to sticky notes
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.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/Convert%20selected%20text%20elements%20to%20sticky%20notes.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Converts selected plain text elements to sticky notes with transparent background and transparent stroke color (default setting, can be changed in plugin settings). Essentially converts text element into a wrappable format.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-textelement-to-transparent-stickynote.png'></td></tr></table>
## Convert text to link with folder and alias
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.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/Convert%20text%20to%20link%20with%20folder%20and%20alias.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Converts text elements to links pointing to a file in a selected folder and with the alias set as the original text. The script will prompt the user to select an existing folder from the vault.<br><code>original text</code> - <code>[[selected folder/original text|original text]]</code></td></tr></table>
## Copy Selected Element Styles to Global
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Copy%20Selected%20Element%20Styles%20to%20Global.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/Copy%20Selected%20Element%20Styles%20to%20Global.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will copy styles of any selected element into Excalidraw's global styles.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-copy-selected-element-styles-to-global.png'></td></tr></table>
## Create new markdown file and embed into active drawing
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md
```
<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%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.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 markdown document with the file name provided, open the new markdown document in an adjacent pane, and embed the markdown document into the active Excalidraw drawing.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-create-and-embed-new-markdown-file.jpg'></td></tr></table>
## Darken background color
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Darken%20background%20color.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/Darken%20background%20color.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script darkens the background color of the selected element by 2% at a time. You can use this script several times until you are satisfied. It is recommended to set a shortcut key for this script so that you can quickly try to DARKEN and LIGHTEN the color effect. In contrast to the `Modify background color opacity` script, the advantage is that the background color of the element is not affected by the canvas color, and the color value does not appear in a strange rgba() form.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/darken-lighten-background-color.png'></td></tr></table>
## Elbow connectors
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Elbow%20connectors.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/Elbow%20connectors.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script converts the selected connectors to elbows.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/elbow-connectors.png'></td></tr></table>
## Expand rectangles horizontally keep text centered
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.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/Expand%20rectangles%20horizontally%20keep%20text%20centered.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script expands the width of the selected rectangles until they are all the same width and keep the text centered.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif'></td></tr></table>
## Expand rectangles horizontally
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Expand%20rectangles%20horizontally.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/Expand%20rectangles%20horizontally.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script expands the width of the selected rectangles until they are all the same width.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif'></td></tr></table>
## Expand rectangles vertically keep text centered
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.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/Expand%20rectangles%20vertically%20keep%20text%20centered.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script expands the height of the selected rectangles until they are all the same height and keep the text centered.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif'></td></tr></table>
## Expand rectangles vertically
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Expand%20rectangles%20vertically.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/Expand%20rectangles%20vertically.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script expands the height of the selected rectangles until they are all the same height.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif'></td></tr></table>
## Fixed horizontal distance between centers
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Fixed%20horizontal%20distance%20between%20centers.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/Fixed%20horizontal%20distance%20between%20centers.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script arranges the selected elements horizontally with a fixed center spacing.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-horizontal-distance-between-centers.png'></td></tr></table>
## Fixed inner distance
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Fixed%20inner%20distance.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/Fixed%20inner%20distance.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script arranges selected elements and groups with a fixed inner distance.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-inner-distance.png'></td></tr></table>
## Fixed spacing
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Fixed%20spacing.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/Fixed%20spacing.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script arranges the selected elements horizontally with a fixed spacing. When we create an architecture diagram or mind map, we often need to arrange a large number of elements in a fixed spacing. `Fixed spacing` and `Fixed vertical Distance` scripts can save us a lot of time.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fix-space-demo.png'></td></tr></table>
## Fixed vertical distance between centers
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Fixed%20vertical%20distance%20between%20centers.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/Fixed%20vertical%20distance%20between%20centers.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script arranges the selected elements vertically with a fixed center spacing.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-vertical-distance-between-centers.png'></td></tr></table>
## Fixed vertical distance
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Fixed%20vertical%20distance.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/Fixed%20vertical%20distance.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script arranges the selected elements vertically with a fixed spacing. When we create an architecture diagram or mind map, we often need to arrange a large number of elements in a fixed spacing. `Fixed spacing` and `Fixed vertical Distance` scripts can save us a lot of time.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-vertical-distance.png'></td></tr></table>
## Lighten background color
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Lighten%20background%20color.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/Lighten%20background%20color.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script lightens the background color of the selected element by 2% at a time. You can use this script several times until you are satisfied. It is recommended to set a shortcut key for this script so that you can quickly try to DARKEN and LIGHTEN the color effect.In contrast to the `Modify background color opacity` script, the advantage is that the background color of the element is not affected by the canvas color, and the color value does not appear in a strange rgba() form.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/darken-lighten-background-color.png'></td></tr></table>
## Mindmap connector
```excalidraw-script-install
https://github.com/xllowl/obsidian-excalidraw-plugin/blob/master/ea-scripts/Mindmap%20connector.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/xllowl'>@xllowl</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/xllowl/obsidian-excalidraw-plugin/blob/master/ea-scripts/Mindmap%20connector.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script creates mindmap like lines(only right side available). The line will starts according to the creation time of the elements. So you may need to create the header element first.<br><img src='https://github.com/xllowl/obsidian-excalidraw-plugin/blob/master/images/mindmap%20connector.png'></td></tr></table>
## Modify background color opacity
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Modify%20background%20color%20opacity.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/Modify%20background%20color%20opacity.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script changes the opacity of the background color of the selected boxes. The default background color in Excalidraw is so dark that the text is hard to read. You can lighten the color a bit by setting transparency. And you can tweak the transparency over and over again until you're happy with it. Although excalidraw has the opacity option in its native property Settings, it also changes the transparency of the border. Use this script to change only the opacity of the background color without affecting the border.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-modify-background-color-opacity.png'></td></tr></table>
## Normalize Selected Arrows
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Normalize%20Selected%20Arrows.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/Normalize%20Selected%20Arrows.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will reset the start and end positions of the selected arrows. The arrow will point to the center of the connected box and will have a gap of 8px from the box.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-normalize-selected-arrows.png'></td></tr></table>
## OCR - Optical Character Recognition
```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 exctract 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>
## Organic Line
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Organic%20Line.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/Organic%20Line.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Converts selected freedraw lines such that pencil pressure will decrease from maximum to minimum from the beginning of the line to its end. The resulting line is placed at the back of the layers, under all other items. Helpful when drawing organic mindmaps.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-organic-line.jpg'></td></tr></table>
## Repeat Elements
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Repeat%20Elements.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/Repeat%20Elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will detect the difference between 2 selected elements, including position, size, angle, stroke and background color, and create several elements that repeat these differences based on the number of repetitions entered by the user.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-repeat-elements.png'></td></tr></table>
## Reverse arrows
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Reverse%20arrows.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/Reverse%20arrows.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Reverse the direction of **arrows** within the scope of selected elements.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-reverse-arrow.jpg'></td></tr></table>
## Scribble Helper
```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'></td></tr></table>
## Select Elements of Type
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Select%20Elements%20of%20Type.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/Select%20Elements%20of%20Type.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Prompts you with a list of the different element types in the active image. Only elements of the selected type will be selected on the canvas. If nothing is selected when running the script, then the script will process all the elements on the canvas. If some elements are selected when the script is executed, then the script will only process the selected elements.<br>The script is useful when, for example, you want to bring to front all the arrows, or want to change the color of all the text elements, etc.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-select-element-of-type.jpg'></td></tr></table>
## Set background color of unclosed line object by adding a shadow clone
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.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/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Use this script to set the background color of unclosed (i.e. open) line objects by creating a clone of the object. The script will set the stroke color of the clone to transparent and will add a straight line to close the object. Use settings to define the default background color, the fill style, and the strokeWidth of the clone. By default the clone will be grouped with the original object, you can disable this also in settings.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-set-background-color-of-unclosed-line.jpg'></td></tr></table>
## Set Dimensions
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Dimensions.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/Set%20Dimensions.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Currently there is no way to specify the exact location and size of objects in Excalidraw. You can bridge this gap with the following simple script.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-dimensions.jpg'></td></tr></table>
## Set Font Family
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Font%20Family.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/Set%20Font%20Family.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Sets font family of the text block (Virgil, Helvetica, Cascadia). Useful if you want to set a keyboard shortcut for selecting font family.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-font-family.jpg'></td></tr></table>
## Set Grid
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Grid.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/Set%20Grid.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The default grid size in Excalidraw is 20. Currently there is no way to change the grid size via the user interface. This script offers a way to bridge this gap.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-grid.jpg'></td></tr></table>
## Set Link Alias
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Link%20Alias.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/Set%20Link%20Alias.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Iterates all of the links in the selected TextElements and prompts the user to set or modify the alias for each link found.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-set-link-alias.jpg'></td></tr></table>
## Set Stroke Width of Selected Elements
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will set the stroke width of selected elements. This is helpful, for example, when you scale freedraw sketches and want to reduce or increase their line width.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-stroke-width.jpg'></td></tr></table>
## Set Text Alignment
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Text%20Alignment.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/Set%20Text%20Alignment.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Sets text alignment of text block (cetner, right, left). Useful if you want to set a keyboard shortcut for selecting text alignment.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-align.jpg'></td></tr></table>
## Split text by lines
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Split%20text%20by%20lines.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/Split%20text%20by%20lines.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Split lines of text into separate text elements for easier reorganization<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-split-lines.jpg'></td></tr></table>
## TheBrain-navigation
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/TheBrain-navigation.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/TheBrain-navigation.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">An Excalidraw based graph user interface for your Vault. Requires the <a href='https://github.com/SkepticMystic/breadcrumbs'>Breadcrumbs plugin</a> to be installed and configured as well. Generates a user interface similar to that of <a href='https://TheBrain.com'>TheBrain</a>. Watch this introduction to this script on <a href='https://youtu.be/J4T5KHERH_o'>YouTube</a>.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/TheBrain.jpg'></td></tr></table>
## Toggle Fullscreen on Mobile
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Toggle%20Fullscreen%20on%20Mobile.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/Toggle%20Fullscreen%20on%20Mobile.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Hides Obsidian workspace leaf padding and header (based on option in settings, default is "hide header" = false) which will take Excalidraw to full screen. ⚠ Note that if the header is not visible, it will be very difficult to invoke the command palette to end full screen. Only hide the header if you have a keyboard or you've practiced opening command palette!<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/ea-toggle-fullscreen.jpg'></td></tr></table>
## Transfer TextElements to Excalidraw markdown metadata
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Transfer%20TextElements%20to%20Excalidraw%20markdown%20metadata.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/Transfer%20TextElements%20to%20Excalidraw%20markdown%20metadata.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will delete the selected text elements from the canvas and will copy the text from these text elements into the Excalidraw markdown file as metadata. This means, that the text will no longer be visible in the drawing, however you will be able to search for the text in Obsidian and find the drawing containing this image.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-to-metadata.jpg'></td></tr></table>
## Zoom to Fit Selected Elements
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Zoom%20to%20Fit%20Selected%20Elements.md
```
<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/Zoom%20to%20Fit%20Selected%20Elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Similar to Excalidraw standard <kbd>SHIFT+2</kbd> feature: Zoom to fit selected elements, but with the ability to zoom to 1000%. Inspiration: [#272](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/272)</td></tr></table>
If you are enjoying the Excalidraw plugin then please support my work and enthusiasm by buying me a coffee on [https://ko-fi/zsolt](https://ko-fi.com/zsolt).
[<img src="https://user-images.githubusercontent.com/14358394/115450238-f39e8100-a21b-11eb-89d0-fa4b82cdbce8.png" class="coffee">](https://ko-fi.com/zsolt)
---
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>
Script Engine scripts are installed in the `Downloaded` subfolder of the `Excalidraw Automate script folder` specified in plugin settings.
In the `Command Palette` installed scripts are prefixed with `Downloaded/`, thus you can always know if you are executing a local script of your own, or one that you have downloaded from GitHub.
## Attention developers and hobby hackers
<img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/hobby-programmer.svg' align='left' style='background-color:whitesmoke; width:80px; margin-right:15px; margin-bottom:10px;'/>
If you want to modify scripts, I recommend moving them to the `Excalidraw Automate script folder` or a different subfolder under the script folder. Scripts in the `Downloaded` folder will be overwritten when you click the `Update this script` button. Note also, that at this time, I do not check if the script file has been updated on GitHub, thus the `Update this script` button is always visible once you have installed a script, not only when an update is availble (hope to build this feature in the future).
I would love to include your contribution in the script library. If you have a script of your own that you would like to share with the community, please open a [PR](https://github.com/zsviczian/obsidian-excalidraw-plugin/pulls) on GitHub. Be sure to include the following in your pull request
- The [script file](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts) with a self explanetory name. The name of the file will be the name of the script in the Command Palette.
- An [image](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/images) explaining the scripts purpose. Remember a picture speaks thousand words!
- An update to this file [ea-scripts/index.md](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/index.md)
---
# List of available scripts
- [[#Add Connector Point]]
- [[#Add Link to Existing File and Open]]
- [[#Add Link to New Page and Open]]
- [[#Add Next Step in Process]]
- [[#Box Each Selected Groups]]
- [[#Box Selected Elements]]
- [[#Change shape of selected elements]]
- [[#Connect elements]]
- [[#Convert freedraw to line]]
- [[#Convert selected text elements to sticky notes]]
- [[#Convert text to link with folder and alias]]
- [[#Copy Selected Element Styles to Global]]
- [[#Create new markdown file and embed into active drawing]]
- [[#Darken background color]]
- [[#Elbow connectors]]
- [[#Expand rectangles horizontally keep text centered]]
- [[#Expand rectangles horizontally]]
- [[#Expand rectangles vertically keep text centered]]
- [[#Expand rectangles vertically]]
- [[#Fixed horizontal distance between centers]]
- [[#Fixed inner distance]]
- [[#Fixed spacing]]
- [[#Fixed vertical distance between centers]]
- [[#Fixed vertical distance]]
- [[#Lighten background color]]
- [[Mindmap connector]]
- [[#Modify background color opacity]]
- [[#Normalize Selected Arrows]]
- [[#OCR - Optical Character Recognition]]
- [[#Organic Line]]
- [[#Repeat Elements]]
- [[#Reverse arrows]]
- [[#Scribble Helper]]
- [[#Select Elements of Type]]
- [[#Set background color of unclosed line object by adding a shadow clone]]
- [[#Set Dimensions]]
- [[#Set Font Family]]
- [[#Set Grid]]
- [[#Set Link Alias]]
- [[#Set Stroke Width of Selected Elements]]
- [[#Set Text Alignment]]
- [[#Split text by lines]]
- [[#Toggle Fullscreen on Mobile]]
- [[#Transfer TextElements to Excalidraw markdown metadata]]
- [[#Zoom to Fit Selected Elements]]
## Add Connector Point
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Connector%20Point.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/Add%20Connector%20Point.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will add a small circle to the top left of each text element in the selection and add the text and the "connector point" to a group. You can use the connector points to link text elements with an arrow (in for example a Wardley Map).<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-bullet-point.jpg'></td></tr></table>
## Add Link to Existing File and Open
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20Existing%20File%20and%20Open.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/Add%20Link%20to%20Existing%20File%20and%20Open.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Prompts for a file from the vault. Adds a link to the selected element pointing to the selected file. You can control in settings to open the file in the current active pane or an adjacent pane.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-link-and-open.jpg'></td></tr></table>
## Add Link to New Page and Open
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20New%20Page%20and%20Open.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/Add%20Link%20to%20New%20Page%20and%20Open.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Prompts for filename. Offers option to create and open a new Markdown or Excalidraw document. Adds link pointing to the new file, to the selected objects in the drawing. You can control in settings to open the file in the current active pane or an adjacent pane.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-link-to-new-page-and-pen.jpg'></td></tr></table>
## Add Next Step in Process
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Next%20Step%20in%20Process.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/Add%20Next%20Step%20in%20Process.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will prompt you for the title of the process step, then will create a stick note with the text. If an element is selected then the script will connect this new step with an arrow to the previous step (the selected element). If no element is selected, then the script assumes this is the first step in the process and will only output the sticky note with the text that was entered.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-process-step.jpg'></td></tr></table>
## Box Each Selected Groups
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Box%20Each%20Selected%20Groups.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/Box%20Each%20Selected%20Groups.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will add encapsulating boxes around each of the currently selected groups in Excalidraw.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-box-each-selected-groups.png'></td></tr></table>
## Box Selected Elements
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Box%20Selected%20Elements.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Box%20Selected%20Elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will add an encapsulating box around the currently selected elements in Excalidraw.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-box-elements.jpg'></td></tr></table>
## Change shape of selected elements
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Change%20shape%20of%20selected%20elements.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Change%20shape%20of%20selected%20elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script allows you to change the shape of selected Rectangles, Diamonds and Ellipses.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-change-shape.jpg'></td></tr></table>
## Connect elements
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Connect%20elements.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Connect%20elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will connect two objects with an arrow. If either of the objects are a set of grouped elements (e.g. a text element grouped with an encapsulating rectangle), the script will identify these groups, and connect the arrow to the largest object in the group (assuming you want to connect the arrow to the box around the text element).<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-connect-elements.jpg'></td></tr></table>
## Convert freedraw to line
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20freedraw%20to%20line.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/Convert%20freedraw%20to%20line.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Convert selected freedraw objects into editable lines. This will allow you to adjust your drawings by dragging line points and will also allow you to select shape fill in case of enclosed lines. You can adjust conversion point density in settings.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-convert-freedraw-to-line.jpg'></td></tr></table>
## Convert selected text elements to sticky notes
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.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/Convert%20selected%20text%20elements%20to%20sticky%20notes.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Converts selected plain text elements to sticky notes with transparent background and transparent stroke color (default setting, can be changed in plugin settings). Essentially converts text element into a wrappable format.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-textelement-to-transparent-stickynote.png'></td></tr></table>
## Convert text to link with folder and alias
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.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/Convert%20text%20to%20link%20with%20folder%20and%20alias.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Converts text elements to links pointing to a file in a selected folder and with the alias set as the original text. The script will prompt the user to select an existing folder from the vault.<br><code>original text</code> - <code>[[selected folder/original text|original text]]</code></td></tr></table>
## Copy Selected Element Styles to Global
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Copy%20Selected%20Element%20Styles%20to%20Global.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/Copy%20Selected%20Element%20Styles%20to%20Global.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will copy styles of any selected element into Excalidraw's global styles.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-copy-selected-element-styles-to-global.png'></td></tr></table>
## Create new markdown file and embed into active drawing
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md
```
<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%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.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 markdown document with the file name provided, open the new markdown document in an adjacent pane, and embed the markdown document into the active Excalidraw drawing.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-create-and-embed-new-markdown-file.jpg'></td></tr></table>
## Darken background color
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Darken%20background%20color.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/Darken%20background%20color.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script darkens the background color of the selected element by 2% at a time. You can use this script several times until you are satisfied. It is recommended to set a shortcut key for this script so that you can quickly try to DARKEN and LIGHTEN the color effect. In contrast to the `Modify background color opacity` script, the advantage is that the background color of the element is not affected by the canvas color, and the color value does not appear in a strange rgba() form.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/darken-lighten-background-color.png'></td></tr></table>
## Elbow connectors
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Elbow%20connectors.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/Elbow%20connectors.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script converts the selected connectors to elbows.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/elbow-connectors.png'></td></tr></table>
## Expand rectangles horizontally keep text centered
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.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/Expand%20rectangles%20horizontally%20keep%20text%20centered.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script expands the width of the selected rectangles until they are all the same width and keep the text centered.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif'></td></tr></table>
## Expand rectangles horizontally
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Expand%20rectangles%20horizontally.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/Expand%20rectangles%20horizontally.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script expands the width of the selected rectangles until they are all the same width.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif'></td></tr></table>
## Expand rectangles vertically keep text centered
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.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/Expand%20rectangles%20vertically%20keep%20text%20centered.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script expands the height of the selected rectangles until they are all the same height and keep the text centered.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif'></td></tr></table>
## Expand rectangles vertically
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Expand%20rectangles%20vertically.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/Expand%20rectangles%20vertically.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script expands the height of the selected rectangles until they are all the same height.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-expand-rectangles.gif'></td></tr></table>
## Fixed horizontal distance between centers
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Fixed%20horizontal%20distance%20between%20centers.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/Fixed%20horizontal%20distance%20between%20centers.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script arranges the selected elements horizontally with a fixed center spacing.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-horizontal-distance-between-centers.png'></td></tr></table>
## Fixed inner distance
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Fixed%20inner%20distance.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/Fixed%20inner%20distance.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script arranges selected elements and groups with a fixed inner distance.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-inner-distance.png'></td></tr></table>
## Fixed spacing
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Fixed%20spacing.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/Fixed%20spacing.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script arranges the selected elements horizontally with a fixed spacing. When we create an architecture diagram or mind map, we often need to arrange a large number of elements in a fixed spacing. `Fixed spacing` and `Fixed vertical Distance` scripts can save us a lot of time.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fix-space-demo.png'></td></tr></table>
## Fixed vertical distance between centers
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Fixed%20vertical%20distance%20between%20centers.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/Fixed%20vertical%20distance%20between%20centers.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script arranges the selected elements vertically with a fixed center spacing.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-vertical-distance-between-centers.png'></td></tr></table>
## Fixed vertical distance
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Fixed%20vertical%20distance.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/Fixed%20vertical%20distance.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script arranges the selected elements vertically with a fixed spacing. When we create an architecture diagram or mind map, we often need to arrange a large number of elements in a fixed spacing. `Fixed spacing` and `Fixed vertical Distance` scripts can save us a lot of time.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-vertical-distance.png'></td></tr></table>
## Lighten background color
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Lighten%20background%20color.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/Lighten%20background%20color.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script lightens the background color of the selected element by 2% at a time. You can use this script several times until you are satisfied. It is recommended to set a shortcut key for this script so that you can quickly try to DARKEN and LIGHTEN the color effect.In contrast to the `Modify background color opacity` script, the advantage is that the background color of the element is not affected by the canvas color, and the color value does not appear in a strange rgba() form.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/darken-lighten-background-color.png'></td></tr></table>
## Mindmap connector
```excalidraw-script-install
https://github.com/xllowl/obsidian-excalidraw-plugin/blob/master/ea-scripts/Mindmap%20connector.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/xllowl'>@xllowl</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/xllowl/obsidian-excalidraw-plugin/blob/master/ea-scripts/Mindmap%20connector.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script creates mindmap like lines(only right side available). The line will starts according to the creation time of the elements. So you may need to create the header element first.<br><img src='https://github.com/xllowl/obsidian-excalidraw-plugin/blob/master/images/mindmap%20connector.png'></td></tr></table>
## Modify background color opacity
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Modify%20background%20color%20opacity.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/Modify%20background%20color%20opacity.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script changes the opacity of the background color of the selected boxes. The default background color in Excalidraw is so dark that the text is hard to read. You can lighten the color a bit by setting transparency. And you can tweak the transparency over and over again until you're happy with it. Although excalidraw has the opacity option in its native property Settings, it also changes the transparency of the border. Use this script to change only the opacity of the background color without affecting the border.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-modify-background-color-opacity.png'></td></tr></table>
## Normalize Selected Arrows
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Normalize%20Selected%20Arrows.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/Normalize%20Selected%20Arrows.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will reset the start and end positions of the selected arrows. The arrow will point to the center of the connected box and will have a gap of 8px from the box.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-normalize-selected-arrows.png'></td></tr></table>
## OCR - Optical Character Recognition
```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 exctract 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>
## Organic Line
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Organic%20Line.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/Organic%20Line.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Converts selected freedraw lines such that pencil pressure will decrease from maximum to minimum from the beginning of the line to its end. The resulting line is placed at the back of the layers, under all other items. Helpful when drawing organic mindmaps.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-organic-line.jpg'></td></tr></table>
## Repeat Elements
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Repeat%20Elements.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/Repeat%20Elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will detect the difference between 2 selected elements, including position, size, angle, stroke and background color, and create several elements that repeat these differences based on the number of repetitions entered by the user.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-repeat-elements.png'></td></tr></table>
## Reverse arrows
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Reverse%20arrows.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/Reverse%20arrows.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Reverse the direction of **arrows** within the scope of selected elements.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-reverse-arrow.jpg'></td></tr></table>
## Scribble Helper
```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'></td></tr></table>
## Select Elements of Type
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Select%20Elements%20of%20Type.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/Select%20Elements%20of%20Type.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Prompts you with a list of the different element types in the active image. Only elements of the selected type will be selected on the canvas. If nothing is selected when running the script, then the script will process all the elements on the canvas. If some elements are selected when the script is executed, then the script will only process the selected elements.<br>The script is useful when, for example, you want to bring to front all the arrows, or want to change the color of all the text elements, etc.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-select-element-of-type.jpg'></td></tr></table>
## Set background color of unclosed line object by adding a shadow clone
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.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/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Use this script to set the background color of unclosed (i.e. open) line objects by creating a clone of the object. The script will set the stroke color of the clone to transparent and will add a straight line to close the object. Use settings to define the default background color, the fill style, and the strokeWidth of the clone. By default the clone will be grouped with the original object, you can disable this also in settings.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-set-background-color-of-unclosed-line.jpg'></td></tr></table>
## Set Dimensions
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Dimensions.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/Set%20Dimensions.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Currently there is no way to specify the exact location and size of objects in Excalidraw. You can bridge this gap with the following simple script.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-dimensions.jpg'></td></tr></table>
## Set Font Family
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Font%20Family.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/Set%20Font%20Family.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Sets font family of the text block (Virgil, Helvetica, Cascadia). Useful if you want to set a keyboard shortcut for selecting font family.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-font-family.jpg'></td></tr></table>
## Set Grid
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Grid.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/Set%20Grid.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The default grid size in Excalidraw is 20. Currently there is no way to change the grid size via the user interface. This script offers a way to bridge this gap.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-grid.jpg'></td></tr></table>
## Set Link Alias
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Link%20Alias.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/Set%20Link%20Alias.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Iterates all of the links in the selected TextElements and prompts the user to set or modify the alias for each link found.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-set-link-alias.jpg'></td></tr></table>
## Set Stroke Width of Selected Elements
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will set the stroke width of selected elements. This is helpful, for example, when you scale freedraw sketches and want to reduce or increase their line width.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-stroke-width.jpg'></td></tr></table>
## Set Text Alignment
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Text%20Alignment.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/Set%20Text%20Alignment.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Sets text alignment of text block (cetner, right, left). Useful if you want to set a keyboard shortcut for selecting text alignment.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-align.jpg'></td></tr></table>
## Split text by lines
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Split%20text%20by%20lines.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/Split%20text%20by%20lines.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Split lines of text into separate text elements for easier reorganization<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-split-lines.jpg'></td></tr></table>
## TheBrain-navigation
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/TheBrain-navigation.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/TheBrain-navigation.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">An Excalidraw based graph user interface for your Vault. Requires the <a href='https://github.com/SkepticMystic/breadcrumbs'>Breadcrumbs plugin</a> to be installed and configured as well. Generates a user interface similar to that of <a href='https://TheBrain.com'>TheBrain</a>. Watch this introduction to this script on <a href='https://youtu.be/J4T5KHERH_o'>YouTube</a>.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/TheBrain.jpg'></td></tr></table>
## Toggle Fullscreen on Mobile
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Toggle%20Fullscreen%20on%20Mobile.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/Toggle%20Fullscreen%20on%20Mobile.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Hides Obsidian workspace leaf padding and header (based on option in settings, default is "hide header" = false) which will take Excalidraw to full screen. ⚠ Note that if the header is not visible, it will be very difficult to invoke the command palette to end full screen. Only hide the header if you have a keyboard or you've practiced opening command palette!<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/ea-toggle-fullscreen.jpg'></td></tr></table>
## Transfer TextElements to Excalidraw markdown metadata
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Transfer%20TextElements%20to%20Excalidraw%20markdown%20metadata.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/Transfer%20TextElements%20to%20Excalidraw%20markdown%20metadata.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will delete the selected text elements from the canvas and will copy the text from these text elements into the Excalidraw markdown file as metadata. This means, that the text will no longer be visible in the drawing, however you will be able to search for the text in Obsidian and find the drawing containing this image.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-to-metadata.jpg'></td></tr></table>
## Zoom to Fit Selected Elements
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Zoom%20to%20Fit%20Selected%20Elements.md
```
<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/Zoom%20to%20Fit%20Selected%20Elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Similar to Excalidraw standard <kbd>SHIFT+2</kbd> feature: Zoom to fit selected elements, but with the ability to zoom to 1000%. Inspiration: [#272](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/272)</td></tr></table>

View File

@@ -0,0 +1,67 @@
/*
Automatically switches between the select and draw tools, based on whether a pen is being used.
1. Choose the select tool
2. Hover/use the pen to draw, move it away to return to select mode
*This is based on pen hover status, so will only work if your pen supports hover!*
If you click draw with the mouse or press select with the pen, switching will be disabled until the opposite input method is used.
**Note:** This script will stay active until the *Obsidian* window is closed.
Compatible with my *Hardware Eraser Support* script
```javascript
*/
(function() {
'use strict';
let promise
let timeout
let disable
function handlePointer(e) {
ea.setView("active");
var activeTool = ea.getExcalidrawAPI().getAppState().activeTool;
function setActiveTool(t) {
ea.getExcalidrawAPI().setActiveTool(t)
}
if (e.pointerType === 'pen') {
if (disable) return
if (!promise && activeTool.type==='selection') {
setActiveTool({type:"freedraw"})
}
if (timeout) clearTimeout(timeout)
function setTimeoutX(a,b) {
timeout = setTimeout(a,b)
return timeout
}
function revert() {
activeTool = ea.getExcalidrawAPI().getAppState().activeTool;
disable = false
if (activeTool.type==='freedraw') {
setActiveTool({type:"selection"})
} else if (activeTool.type==='selection') {
disable = true
}
promise = false
}
promise = new Promise(resolve => setTimeoutX(resolve, 500))
promise.then(() => revert())
}
}
function handleClick(e) {
ea.setView("active");
if (e.pointerType !== 'pen') {
disable = false
}
}
window.addEventListener('pointermove', handlePointer, { capture: true })
window.addEventListener('pointerdown', handleClick, { capture: true })
})();

View File

@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 27.2.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 448 512" style="enable-background:new 0 0 448 512;" xml:space="preserve">
<style type="text/css">
.st0{stroke:#000000;stroke-width:2;stroke-miterlimit:10;}
</style>
<g>
<g>
<path class="st0" d="M355.8,234.1"/>
</g>
<g>
<path d="M32.3,139.7l28.8,24.2l63.5-71.7L95.7,67c-7.2-6.3-18.2-5.6-24.5,1.6l-40.6,46.6C24.3,122.4,25,133.3,32.3,139.7z"/>
<path d="M61.2,165.3l-29.6-24.9c-3.7-3.3-5.9-7.8-6.3-12.7c-0.3-4.9,1.3-9.6,4.5-13.2L70.5,68c6.7-7.6,18.3-8.4,25.9-1.7L126,92.1
L61.2,165.3z M32.9,138.9l28,23.6l62.2-70.2l-28-24.6c-6.8-5.9-17.1-5.2-23.1,1.5l-40.6,46.6c-2.9,3.3-4.3,7.5-4,11.8
C27.6,132,29.6,136,32.9,138.9z"/>
</g>
<g>
<polygon points="218.7,240.1 212.3,168.6 197.2,155.4 133.7,228.1 148.9,241.3 "/>
<path d="M148.5,242.3l-16.2-14.1l64.8-74.2l16.2,14.1l6.5,73L148.5,242.3z M135.1,228l14.1,12.3l68.4-1.2l-6.2-70.1l-14.1-12.3
L135.1,228z"/>
</g>
<g>
<polygon points="192.6,151.6 129.1,224.3 66.2,168.4 129.6,96.7 "/>
<path d="M129.2,225.7l-64.5-57.2l64.8-73.2l64.5,56.2L129.2,225.7z M67.6,168.3l61.5,54.6l62.2-71.2l-61.5-53.6L67.6,168.3z"/>
</g>
<g>
<path d="M109.7,381.6c-23.7-22.2-40-49.3-48.9-78.2c8.2-0.9,22.4-3.6,30.1-12.3c-12.6-12.5-25.3-25-37.9-37.5c0-0.1,0-0.3,0-0.4
l-23.6-22c-6,60.7,15.5,123.7,63.7,168.8s112.5,62.4,172.7,52.4l-24.1-22.6C194.8,432.3,146.9,416.4,109.7,381.6z"/>
<path d="M232.6,456.1c-19.6,0-39.2-2.8-57.9-8.3c-30.9-9.1-58.6-24.9-82.3-47.1C68.7,378.6,51.1,352,40,321.8
c-10.6-28.8-14.6-60.2-11.6-90.7l0.2-2L54,252.8v0.4c6.2,6.1,12.4,12.3,18.6,18.4c6.3,6.3,12.7,12.5,19,18.8l0.7,0.7l-0.6,0.7
c-7.2,8.1-19.8,11.3-29.5,12.5c9.2,29.2,25.9,55.6,48.3,76.6l0,0c35.8,33.5,82.4,50.5,131.3,47.9l0.4,0l25.9,24.3l-2,0.3
C255,455.2,243.8,456.1,232.6,456.1z M30.2,233.3c-5.6,62.5,17.5,122.9,63.6,166c46,43.1,107.8,62.1,169.8,52.5l-22.3-20.9
c-49.2,2.5-96.2-14.7-132.3-48.5l0,0c-22.9-21.5-39.9-48.7-49.2-78.6l-0.4-1.2l1.2-0.1c9.3-1,21.6-3.8,28.8-11.3
c-6.1-6-12.2-12.1-18.3-18.1c-6.3-6.2-12.6-12.5-18.9-18.7L52,254v-0.4L30.2,233.3z"/>
</g>
<g>
<path d="M368.8,105.4c-56-52.4-133.5-67.2-201.3-45.5l21,19.6c56.1-13.2,117.7,1.1,163.1,43.7c33,30.9,51.7,71.2,55.9,112.7
c-0.2-0.4-0.3-0.6-0.3-0.6s-25.1-0.1-36.5,12.7c11.8,11.6,23.5,23.3,35.3,34.9v0.1l2.4,2.3c0.4,0.4,0.9,0.9,1.3,1.3l0,0l17.7,16.6
C444.7,234.1,424.8,157.7,368.8,105.4z"/>
<path d="M428,305.1L409,287.3l-1.3-1.3l-2.7-2.6v-0.1c-5.8-5.7-11.5-11.4-17.3-17.1c-5.9-5.8-11.8-11.7-17.7-17.5l-0.7-0.7
l0.6-0.7c10.5-11.8,31.7-12.9,36.4-13c-4.7-42.1-24.3-81.3-55.4-110.4c-43.5-40.9-104.2-57.1-162.2-43.5l-0.5,0.1l-22.6-21.1
l1.6-0.5c70.5-22.6,148-5,202.3,45.7c54.3,50.7,76.9,126.9,58.9,198.8L428,305.1z M407,282.6l3.4,3.3l16.4,15.4
c17.1-70.7-5.3-145.3-58.7-195.2l0,0c-53.3-49.9-129.3-67.4-198.7-45.8l19.4,18.1c58.5-13.6,119.6,2.9,163.5,44.1
c31.9,29.8,51.8,70.1,56.2,113.3l0.5,5.4l-2.5-4.9c-3.8,0.1-24.3,1.1-34.5,11.7c5.7,5.6,11.3,11.2,17,16.8
c5.9,5.8,11.7,11.6,17.6,17.4L407,282.6L407,282.6z"/>
</g>
<polygon points="425.2,382.2 302.7,283.9 299.4,437.6 340.9,383.8 382.3,456.5 398,447.5 359.4,379.8 "/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.3 KiB

399
ea-scripts/Auto Layout.md Normal file
View File

@@ -0,0 +1,399 @@
/*
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-download-raw.jpg)
Download this file and save to your Obsidian Vault including the first line, or open it in "Raw" and copy the entire contents to Obsidian.
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-auto-layout.png)
This script performs automatic layout for the selected top-level grouping objects. It is powered by [elkjs](https://github.com/kieler/elkjs) and needs to be connected to the Internet.
See documentation for more details:
https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.html
```javascript
*/
if (
!ea.verifyMinimumPluginVersion ||
!ea.verifyMinimumPluginVersion("1.5.21")
) {
new Notice(
"This script requires a newer version of Excalidraw. Please install the latest version."
);
return;
}
settings = ea.getScriptSettings();
//set default values on first run
if (!settings["Layout Options JSON"]) {
settings = {
"Layout Options JSON": {
height: "450px",
value: `{\n "org.eclipse.elk.layered.crossingMinimization.semiInteractive": "true",\n "org.eclipse.elk.layered.considerModelOrder.components": "FORCE_MODEL_ORDER"\n}`,
description: `You can use layout options to configure the layout algorithm. A list of all options and further details of their exact effects is available in <a href="http://www.eclipse.org/elk/reference.html" rel="nofollow">ELK's documentation</a>.`,
},
};
ea.setScriptSettings(settings);
}
if (typeof ELK === "undefined") {
loadELK(doAutoLayout);
} else {
doAutoLayout();
}
async function doAutoLayout() {
const selectedElements = ea.getViewSelectedElements();
const groups = ea
.getMaximumGroups(selectedElements)
.map((g) => g.filter((el) => el.containerId == null)) // ignore text in stickynote
.filter((els) => els.length > 0);
const stickynotesMap = selectedElements
.filter((el) => el.containerId != null)
.reduce((result, el) => {
result.set(el.containerId, el);
return result;
}, new Map());
const elk = new ELK();
const knownLayoutAlgorithms = await elk.knownLayoutAlgorithms();
const layoutAlgorithms = knownLayoutAlgorithms
.map((knownLayoutAlgorithm) => ({
id: knownLayoutAlgorithm.id,
displayText:
knownLayoutAlgorithm.id === "org.eclipse.elk.layered" ||
knownLayoutAlgorithm.id === "org.eclipse.elk.radial" ||
knownLayoutAlgorithm.id === "org.eclipse.elk.mrtree"
? "* " +
knownLayoutAlgorithm.name +
": " +
knownLayoutAlgorithm.description
: knownLayoutAlgorithm.name + ": " + knownLayoutAlgorithm.description,
}))
.sort((lha, rha) => lha.displayText.localeCompare(rha.displayText));
const layoutAlgorithmsSimple = knownLayoutAlgorithms
.map((knownLayoutAlgorithm) => ({
id: knownLayoutAlgorithm.id,
displayText:
knownLayoutAlgorithm.id === "org.eclipse.elk.layered" ||
knownLayoutAlgorithm.id === "org.eclipse.elk.radial" ||
knownLayoutAlgorithm.id === "org.eclipse.elk.mrtree"
? "* " + knownLayoutAlgorithm.name
: knownLayoutAlgorithm.name,
}))
.sort((lha, rha) => lha.displayText.localeCompare(rha.displayText));
// const knownOptions = knownLayoutAlgorithms
// .reduce(
// (result, knownLayoutAlgorithm) => [
// ...result,
// ...knownLayoutAlgorithm.knownOptions,
// ],
// []
// )
// .filter((value, index, self) => self.indexOf(value) === index) // remove duplicates
// .sort((lha, rha) => lha.localeCompare(rha));
// console.log("knownOptions", knownOptions);
const selectedAlgorithm = await utils.suggester(
layoutAlgorithms.map((algorithmInfo) => algorithmInfo.displayText),
layoutAlgorithms.map((algorithmInfo) => algorithmInfo.id),
"Layout algorithm"
);
const knownNodePlacementStrategy = [
"SIMPLE",
"INTERACTIVE",
"LINEAR_SEGMENTS",
"BRANDES_KOEPF",
"NETWORK_SIMPLEX",
];
const knownDirections = [
"UNDEFINED",
"RIGHT",
"LEFT",
"DOWN",
"UP"
];
let nodePlacementStrategy = "BRANDES_KOEPF";
let componentComponentSpacing = "10";
let nodeNodeSpacing = "100";
let nodeNodeBetweenLayersSpacing = "100";
let discoComponentLayoutAlgorithm = "org.eclipse.elk.layered";
let direction = "UNDEFINED";
if (selectedAlgorithm === "org.eclipse.elk.layered") {
nodePlacementStrategy = await utils.suggester(
knownNodePlacementStrategy,
knownNodePlacementStrategy,
"Node placement strategy"
);
selectedDirection = await utils.suggester(
knownDirections,
knownDirections,
"Direction"
);
direction = selectedDirection??"UNDEFINED";
} else if (selectedAlgorithm === "org.eclipse.elk.disco") {
const componentLayoutAlgorithms = layoutAlgorithmsSimple.filter(al => al.id !== "org.eclipse.elk.disco");
const selectedDiscoComponentLayoutAlgorithm = await utils.suggester(
componentLayoutAlgorithms.map((algorithmInfo) => algorithmInfo.displayText),
componentLayoutAlgorithms.map((algorithmInfo) => algorithmInfo.id),
"Disco Connected Components Layout Algorithm"
);
discoComponentLayoutAlgorithm = selectedDiscoComponentLayoutAlgorithm??"org.eclipse.elk.layered";
}
if (
selectedAlgorithm === "org.eclipse.elk.box" ||
selectedAlgorithm === "org.eclipse.elk.rectpacking"
) {
nodeNodeSpacing = await utils.inputPrompt("Node Spacing", "number", "10");
} else {
let userSpacingStr = await utils.inputPrompt(
"Components Spacing, Node Spacing, Node Node Between Layers Spacing",
"number, number, number",
"10, 100, 100"
);
let userSpacingArr = (userSpacingStr??"").split(",");
componentComponentSpacing = userSpacingArr[0] ?? "10";
nodeNodeSpacing = userSpacingArr[1] ?? "100";
nodeNodeBetweenLayersSpacing = userSpacingArr[2] ?? "100";
}
let layoutOptionsJson = {};
try {
layoutOptionsJson = JSON.parse(settings["Layout Options JSON"].value);
} catch (e) {
new Notice(
"Error reading Layout Options JSON, see developer console for more information",
4000
);
console.log(e);
}
layoutOptionsJson["elk.algorithm"] = selectedAlgorithm;
layoutOptionsJson["org.eclipse.elk.spacing.componentComponent"] =
componentComponentSpacing;
layoutOptionsJson["org.eclipse.elk.spacing.nodeNode"] = nodeNodeSpacing;
layoutOptionsJson["org.eclipse.elk.layered.spacing.nodeNodeBetweenLayers"] =
nodeNodeBetweenLayersSpacing;
layoutOptionsJson["org.eclipse.elk.layered.nodePlacement.strategy"] =
nodePlacementStrategy;
layoutOptionsJson["org.eclipse.elk.disco.componentCompaction.componentLayoutAlgorithm"] =
discoComponentLayoutAlgorithm;
layoutOptionsJson["org.eclipse.elk.direction"] = direction;
const graph = {
id: "root",
layoutOptions: layoutOptionsJson,
children: [],
edges: [],
};
let groupMap = new Map();
let targetElkMap = new Map();
let arrowEls = [];
for (let i = 0; i < groups.length; i++) {
const elements = groups[i];
if (
elements.length === 1 &&
(elements[0].type === "arrow" || elements[0].type === "line")
) {
if (
elements[0].type === "arrow" &&
elements[0].startBinding &&
elements[0].endBinding
) {
arrowEls.push(elements[0]);
}
} else {
let elkId = "g" + i;
elements.reduce((result, el) => {
result.set(el.id, elkId);
return result;
}, targetElkMap);
const box = ea.getBoundingBox(elements);
groupMap.set(elkId, {
elements: elements,
boundingBox: box,
});
graph.children.push({
id: elkId,
width: box.width,
height: box.height,
x: box.topX,
y: box.topY,
});
}
}
for (let i = 0; i < arrowEls.length; i++) {
const arrowEl = arrowEls[i];
const startElkId = targetElkMap.get(arrowEl.startBinding.elementId);
const endElkId = targetElkMap.get(arrowEl.endBinding.elementId);
graph.edges.push({
id: "e" + i,
sources: [startElkId],
targets: [endElkId],
});
}
const initTopX =
Math.min(...Array.from(groupMap.values()).map((v) => v.boundingBox.topX)) -
12;
const initTopY =
Math.min(...Array.from(groupMap.values()).map((v) => v.boundingBox.topY)) -
12;
elk
.layout(graph)
.then((resultGraph) => {
for (const elkEl of resultGraph.children) {
const group = groupMap.get(elkEl.id);
for (const groupEl of group.elements) {
const originalDistancX = groupEl.x - group.boundingBox.topX;
const originalDistancY = groupEl.y - group.boundingBox.topY;
const groupElDistanceX =
elkEl.x + initTopX + originalDistancX - groupEl.x;
const groupElDistanceY =
elkEl.y + initTopY + originalDistancY - groupEl.y;
groupEl.x = groupEl.x + groupElDistanceX;
groupEl.y = groupEl.y + groupElDistanceY;
if (stickynotesMap.has(groupEl.id)) {
const stickynote = stickynotesMap.get(groupEl.id);
stickynote.x = stickynote.x + groupElDistanceX;
stickynote.y = stickynote.y + groupElDistanceY;
}
}
}
ea.copyViewElementsToEAforEditing(selectedElements);
ea.addElementsToView(false, false);
normalizeSelectedArrows();
})
.catch(console.error);
}
function loadELK(doAfterLoaded) {
let script = document.createElement("script");
script.onload = function () {
if (typeof ELK !== "undefined") {
doAfterLoaded();
}
};
script.src =
"https://cdn.jsdelivr.net/npm/elkjs@0.8.2/lib/elk.bundled.min.js";
document.head.appendChild(script);
}
/*
* Normalize Selected Arrows
*/
function normalizeSelectedArrows() {
let gapValue = 2;
const selectedIndividualArrows = ea.getMaximumGroups(ea.getViewSelectedElements())
.reduce((result, g) => [...result, ...g.filter(el => el.type === 'arrow')], []);
const allElements = ea.getViewElements();
for (const arrow of selectedIndividualArrows) {
const startBindingEl = allElements.filter(
(el) => el.id === (arrow.startBinding || {}).elementId
)[0];
const endBindingEl = allElements.filter(
(el) => el.id === (arrow.endBinding || {}).elementId
)[0];
if (startBindingEl) {
recalculateStartPointOfLine(
arrow,
startBindingEl,
endBindingEl,
gapValue
);
}
if (endBindingEl) {
recalculateEndPointOfLine(arrow, endBindingEl, startBindingEl, gapValue);
}
}
ea.copyViewElementsToEAforEditing(selectedIndividualArrows);
ea.addElementsToView(false, false);
}
function recalculateStartPointOfLine(line, el, elB, gapValue) {
const aX = el.x + el.width / 2;
const bX =
line.points.length <= 2 && elB
? elB.x + elB.width / 2
: line.x + line.points[1][0];
const aY = el.y + el.height / 2;
const bY =
line.points.length <= 2 && elB
? elB.y + elB.height / 2
: line.y + line.points[1][1];
line.startBinding.gap = gapValue;
line.startBinding.focus = 0;
const intersectA = ea.intersectElementWithLine(
el,
[bX, bY],
[aX, aY],
line.startBinding.gap
);
if (intersectA.length > 0) {
line.points[0] = [0, 0];
for (let i = 1; i < line.points.length; i++) {
line.points[i][0] -= intersectA[0][0] - line.x;
line.points[i][1] -= intersectA[0][1] - line.y;
}
line.x = intersectA[0][0];
line.y = intersectA[0][1];
}
}
function recalculateEndPointOfLine(line, el, elB, gapValue) {
const aX = el.x + el.width / 2;
const bX =
line.points.length <= 2 && elB
? elB.x + elB.width / 2
: line.x + line.points[line.points.length - 2][0];
const aY = el.y + el.height / 2;
const bY =
line.points.length <= 2 && elB
? elB.y + elB.height / 2
: line.y + line.points[line.points.length - 2][1];
line.endBinding.gap = gapValue;
line.endBinding.focus = 0;
const intersectA = ea.intersectElementWithLine(
el,
[bX, bY],
[aX, aY],
line.endBinding.gap
);
if (intersectA.length > 0) {
line.points[line.points.length - 1] = [
intersectA[0][0] - line.x,
intersectA[0][1] - line.y,
];
}
}

View File

@@ -0,0 +1 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1670131481615" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3504" width="128" height="128" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M947.2 0H76.8C33.6 0 0 33.6 0 76.8v870.4C0 990.4 33.6 1024 76.8 1024h870.4c38.4 0 72-30.4 76.8-68.8V76.8C1024 33.6 990.4 0 947.2 0zM84.8 84.8h852.8V256H84.8V84.8z m256 256h596.8v256H340.8v-256z m-256 598.4V340.8H256v596.8H84.8z m256 0v-256h596.8v256H340.8z" p-id="3505"></path></svg>

After

Width:  |  Height:  |  Size: 616 B

View File

@@ -9,13 +9,12 @@ if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.5.21")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
settings = ea.getScriptSettings();
let settings = ea.getScriptSettings();
//set default values on first run
if(!settings["Border color"]) {
settings = {
"Border color" : {
value: "transparent",
value: "#000000",
description: "Any legal HTML color (#000000, rgb, color-name, etc.). Set to 'transparent' for transparent color."
},
"Background color" : {
@@ -28,27 +27,44 @@ if(!settings["Border color"]) {
valueset: ["hachure","cross-hatch","solid"]
}
};
ea.setScriptSettings(settings);
await ea.setScriptSettings(settings);
}
if(!settings["Max sticky note width"]) {
settings["Max sticky note width"] = {
value: "600",
description: "Maximum width of new sticky note. If text is longer, it will be wrapped",
valueset: ["400","600","800","1000","1200","1400","2000"]
}
await ea.setScriptSettings(settings);
}
const maxWidth = parseInt(settings["Max sticky note width"].value);
const strokeColor = settings["Border color"].value;
const backgroundColor = settings["Background color"].value;
const fillStyle = settings["Background fill style"].value;
elements = ea.getViewSelectedElements()
.filter((el)=>(el.type==="text")&&(el.containerId===null));
if(elements.length===0) return;
const elements = ea
.getViewSelectedElements()
.filter((el)=>(el.type==="text")&&(el.containerId===null));
if(elements.length===0) {
new Notice("Please select a text element");
return;
}
ea.style.strokeColor = strokeColor;
ea.style.backgroundColor = backgroundColor;
ea.style.fillStyle = fillStyle;
const padding = 6;
let boxes = [];
elements.forEach((el)=>{
const id = ea.addRect(el.x-padding,el.y-padding,el.width+2*padding,el.height+2*padding);
const boxes = [];
ea.copyViewElementsToEAforEditing(elements);
ea.getElements().forEach((el)=>{
const width = el.width+2*padding;
const widthOK = width<=maxWidth;
const id = ea.addRect(el.x-padding,el.y-padding,widthOK?width:maxWidth,el.height+2*padding);
boxes.push(id);
ea.getElement(id).boundElements=[{type:"text",id:el.id}];
el.containerId = id;
});
ea.copyViewElementsToEAforEditing(elements);
await ea.addElementsToView(false,false);
ea.selectElementsInView(ea.getViewElements().filter(el=>boxes.includes(el.id)));
await ea.addElementsToView(false,true);
const containers = ea.getViewElements().filter(el=>boxes.includes(el.id));
ea.getExcalidrawAPI().updateContainerSize(containers);
ea.selectElementsInView(containers);

View File

@@ -0,0 +1,72 @@
/*
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-deconstruct.jpg)
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.
```javascript
*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.7.29")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
const els = ea.getViewSelectedElements();
if (els.length === 0) {
new Notice("You must select elements first")
return;
}
const bb = ea.getBoundingBox(els);
ea.copyViewElementsToEAforEditing(els);
ea.getElements().filter(el=>el.type==="image").forEach(el=>{
const img = ea.targetView.excalidrawData.getFile(el.fileId);
const path = (img?.linkParts?.original)??(img?.file?.path);
if(img && path) {
ea.imagesDict[el.fileId] = {
mimeType: img.mimeType,
id: el.fileId,
dataURL: img.img,
created: img.mtime,
file: path,
hasSVGwithBitmap: img.isSVGwithBitmap,
latex: null,
};
return;
}
const equation = ea.targetView.excalidrawData.getEquation(el.fileId);
eqImg = ea.targetView.getScene()?.files[el.fileId]
if(equation && eqImg) {
ea.imagesDict[el.fileId] = {
mimeType: eqImg.mimeType,
id: el.fileId,
dataURL: eqImg.dataURL,
created: eqImg.created,
file: null,
hasSVGwithBitmap: null,
latex: equation.latex,
};
return;
}
});
let folder = ea.targetView.file.path;
folder = folder.lastIndexOf("/")===-1?"":folder.substring(0,folder.lastIndexOf("/"))+"/";
const fname = await utils.inputPrompt("Filename for new file","Filename","");
const template = app.metadataCache.getFirstLinkpathDest(ea.plugin.settings.templateFilePath,"");
const newPath = await ea.create ({
filename: fname + ".md",
foldername: folder,
templatePath: template?.path,
onNewPane: true
});
setTimeout(async ()=>{
const file = app.metadataCache.getFirstLinkpathDest(newPath,"")
ea.deleteViewElements(els);
ea.clear();
await ea.addImage(bb.topX,bb.topY,file,false);
await ea.addElementsToView(false, true, true);
ea.getExcalidrawAPI().history.clear(); //to avoid undo/redo messing up the decomposition
},1000);

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M169.7 .9c-22.8-1.6-41.9 14-47.5 34.7L110.4 80c.5 0 1.1 0 1.6 0c176.7 0 320 143.3 320 320c0 .5 0 1.1 0 1.6l44.4-11.8c20.8-5.5 36.3-24.7 34.7-47.5C498.5 159.5 352.5 13.5 169.7 .9zM399.8 410.2c.1-3.4 .2-6.8 .2-10.2c0-159.1-128.9-288-288-288c-3.4 0-6.8 .1-10.2 .2L.5 491.9c-1.5 5.5 .1 11.4 4.1 15.4s9.9 5.6 15.4 4.1L399.8 410.2zM176 272c-17.7 0-32-14.3-32-32s14.3-32 32-32s32 14.3 32 32s-14.3 32-32 32zm128 64c0 17.7-14.3 32-32 32s-32-14.3-32-32s14.3-32 32-32s32 14.3 32 32zM160 384c0 17.7-14.3 32-32 32s-32-14.3-32-32s14.3-32 32-32s32 14.3 32 32z"/></svg>

After

Width:  |  Height:  |  Size: 624 B

View File

@@ -13,12 +13,49 @@ https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.h
```javascript
*/
const selectedCenterConnectPoints = await utils.suggester(
['Yes', 'No'],
[true, false],
"Center connect points?"
);
const centerConnectPoints = selectedCenterConnectPoints??false;
const allElements = ea.getViewElements();
const elements = ea.getViewSelectedElements();
const lines = elements.filter((el)=>el.type==="arrow" || el.type==="line");
for (const line of lines) {
if (line.points.length >= 3) {
if(centerConnectPoints) {
const startBindingEl = allElements.filter(el => el.id === (line.startBinding||{}).elementId)[0];
const endBindingEl = allElements.filter(el => el.id === (line.endBinding||{}).elementId)[0];
if(startBindingEl) {
const startPointX = line.x +line.points[0][0];
if(startPointX >= startBindingEl.x && startPointX <= startBindingEl.x + startBindingEl.width) {
line.points[0][0] = startBindingEl.x + startBindingEl.width / 2 - line.x;
}
const startPointY = line.y +line.points[0][1];
if(startPointY >= startBindingEl.y && startPointY <= startBindingEl.y + startBindingEl.height) {
line.points[0][1] = startBindingEl.y + startBindingEl.height / 2 - line.y;
}
}
if(endBindingEl) {
const startPointX = line.x +line.points[line.points.length-1][0];
if(startPointX >= endBindingEl.x && startPointX <= endBindingEl.x + endBindingEl.width) {
line.points[line.points.length-1][0] = endBindingEl.x + endBindingEl.width / 2 - line.x;
}
const startPointY = line.y +line.points[line.points.length-1][1];
if(startPointY >= endBindingEl.y && startPointY <= endBindingEl.y + endBindingEl.height) {
line.points[line.points.length-1][1] = endBindingEl.y + endBindingEl.height / 2 - line.y;
}
}
}
for (var i = 0; i < line.points.length - 2; i++) {
var p1;
var p3;

View File

@@ -0,0 +1,9 @@
/*
This script adds the `Folder Note Core: Make current document folder note` function to Excalidraw drawings. Running this script will convert the active Excalidraw drawing into a folder note. If you already have embedded images in your drawing, those attachments will not be moved when the folder note is created. You need to take care of those attachments separately, or convert the drawing to a folder note prior to adding the attachments. The script requires the [Folder Note Core](https://github.com/aidenlx/folder-note-core) plugin.
```javascript*/
const FNC = app.plugins.plugins['folder-note-core']?.resolver;
const file = ea.targetView.file;
if(!FNC) return;
if(!FNC.createFolderForNoteCheck(file)) return;
FNC.createFolderForNote(file);

View File

@@ -0,0 +1,12 @@
<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">
<path fill="none" stroke-width="2" d="M10.5 20H4a2 2 0 0 1-2-2V5c0-1.1.9-2 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H20a2 2 0 0 1 2 2v3"></path>
<circle fill="none" stroke-width="2" cx="18" cy="18" r="3"></circle>
<path fill="none" stroke-width="2" d="M18 14v1"></path>
<path fill="none" stroke-width="2" d="M18 21v1"></path>
<path fill="none" stroke-width="2" d="M22 18h-1"></path>
<path fill="none" stroke-width="2" d="M15 18h-1"></path>
<path fill="none" stroke-width="2" d="m21 15-.88.88"></path>
<path fill="none" stroke-width="2" d="M15.88 20.12 15 21"></path>
<path fill="none" stroke-width="2" d="m21 21-.88-.88"></path>
<path fill="none" stroke-width="2" d="M15.88 15.88 15 15"></path>
</svg>

After

Width:  |  Height:  |  Size: 912 B

View File

@@ -0,0 +1,75 @@
/*
Adds support for pen inversion, a.k.a. the hardware eraser on the back of your pen.
Simply use the eraser on a supported pen, and it will erase. Your previous tool will be restored when the eraser leaves the screen.
(Tested with a surface pen, but should work with all windows ink devices, and probably others)
**Note:** This script will stay active until the *Obsidian* window is closed.
Compatible with my *Auto Draw for Pen* script
```javascript
*/
(function() {
'use strict';
let activated
let revert
function handlePointer(e) {
const activeTool = ea.getExcalidrawAPI().getAppState().activeTool;
const isEraser = e.pointerType === 'pen' && e.buttons & 32
function setActiveTool(t) {
ea.getExcalidrawAPI().setActiveTool(t)
}
if (!activated && isEraser) {
//Store previous tool
const btns = document.querySelectorAll('.App-toolbar input.ToolIcon_type_radio')
for (const i in btns) {
if (btns[i]?.checked) {
revert = btns[i]
}
}
revert = activeTool
// Activate eraser tool
setActiveTool({type: "eraser"})
activated = true
// Force Excalidraw to recognize this the same as pen tip
// https://github.com/excalidraw/excalidraw/blob/4a9fac2d1e5c4fac334201ef53c6f5d2b5f6f9f5/src/components/App.tsx#L2945-L2951
Object.defineProperty(e, 'button', {
value: 0,
writable: false
});
}
// Keep on eraser!
if (isEraser && activated) {
setActiveTool({type: "eraser"})
}
if (activated && !isEraser) {
// Revert tool on release
// revert.click()
setActiveTool(revert)
activated = false
// Force delete "limbo" elements
// This doesn't happen on the web app
// It's a bug caused by switching to eraser during a stroke
ea.setView("active");
var del = []
for (const i in ea.getViewElements()) {
const element = ea.getViewElements()[i];
if (element.opacity === 20) {
del.push(element)
}
}
ea.deleteViewElements(del)
setActiveTool(revert)
}
}
window.addEventListener('pointerdown', handlePointer, { capture: true })
window.addEventListener('pointermove', handlePointer, { capture: true })
})();

View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 27.2.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 448 512" style="enable-background:new 0 0 448 512;" xml:space="preserve">
<style type="text/css">
.st0{stroke:#000000;stroke-width:2;stroke-miterlimit:10;}
</style>
<path class="st0" d="M355.8,234.1"/>
<g>
<path class="st0" d="M404.8,293.5L306.9,208l-120,137.4l97.9,85.5c13.6,11.9,34.4,10.5,46.3-3.1l76.8-88
C419.9,326.2,418.5,305.5,404.8,293.5z M389.4,322.2l-78.2,89.6c-3.8,4.3-10.4,4.8-14.8,1l-77.8-68l92-105.3l77.8,68
C392.8,311.2,393.2,317.8,389.4,322.2z"/>
<polygon class="st0" points="52.4,103.7 64.4,238.9 93,263.8 213,126.4 184.4,101.4 "/>
<rect x="108.3" y="185.1" transform="matrix(0.6578 -0.7532 0.7532 0.6578 -108.9276 230.7956)" class="st0" width="182.4" height="100.3"/>
<path class="st0" d="M109.7,381.6c-23.7-22.2-40-49.3-48.9-78.2c8.2-0.9,22.4-3.6,30.1-12.3c-12.6-12.5-25.3-25-37.9-37.5
c0-0.1,0-0.3,0-0.4l-23.6-22c-6,60.7,15.5,123.7,63.7,168.8s112.5,62.4,172.7,52.4l-24.1-22.6C194.8,432.3,146.9,416.4,109.7,381.6
z"/>
<path class="st0" d="M368.8,105.4c-56-52.4-133.5-67.2-201.3-45.5l21,19.6c56.1-13.2,117.7,1.1,163.1,43.7
c33,30.9,51.7,71.2,55.9,112.7c-0.2-0.4-0.3-0.6-0.3-0.6s-25.1-0.1-36.5,12.7c11.8,11.6,23.5,23.3,35.3,34.9c0,0,0,0.1,0,0.1
l2.4,2.3c0.4,0.4,0.9,0.9,1.3,1.3c0,0,0,0,0,0l17.7,16.6C444.7,234.1,424.8,157.7,368.8,105.4z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,53 @@
/*
![](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"]
};
const api = ea.getExcalidrawAPI();
const st = api.getAppState();
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;
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});
}
}
const invertPaletteColors = (palette) => Object.keys(palette).forEach(key => palette[key] = invertColor(palette[key]));
Object.keys(colorPalette).forEach(key => invertPaletteColors(colorPalette[key]));
ea.copyViewElementsToEAforEditing(ea.getViewElements());
ea.getElements().forEach(el=>{
el.strokeColor = invertColor(el.strokeColor);
el.backgroundColor = invertColor(el.backgroundColor);
});
ea.viewUpdateScene({
appState:{
colorPalette,
viewBackgroundColor: invertColor(st.viewBackgroundColor),
currentItemStrokeColor: invertColor(st.currentItemStrokeColor),
currentItemBackgroundColor: invertColor(st.currentItemBackgroundColor)
},
elements: ea.getElements()
});

View File

@@ -0,0 +1,13 @@
<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">
<path stroke-width="2" fill="none" d="M12 16a4 4 0 1 0 0-8 4 4 0 0 0 0 8z"></path>
<path stroke-width="2" fill="none" d="M12 8a2.828 2.828 0 1 0 4 4"></path>
<path stroke-width="2" fill="none" d="M12 2v2"></path>
<path stroke-width="2" fill="none" d="M12 20v2"></path>
<path stroke-width="2" fill="none" d="m4.93 4.93 1.41 1.41"></path>
<path stroke-width="2" fill="none" d="m17.66 17.66 1.41 1.41"></path>
<path stroke-width="2" fill="none" d="M2 12h2"></path>
<path stroke-width="2" fill="none" d="M20 12h2"></path>
<path stroke-width="2" fill="none" d="m6.34 17.66-1.41 1.41"></path>
<path stroke-width="2" fill="none" d="m19.07 4.93-1.41 1.41"></path>
</svg>

After

Width:  |  Height:  |  Size: 865 B

View File

@@ -0,0 +1,361 @@
/*
format **the left to right** mind map
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-mindmap-format-1.png)
# tree
Mind map is actually a tree, so you must have a **root node**. The script will determine **the leftmost element** of the selected element as the root element (node is excalidraw element, e.g. rectangle, diamond, ellipse, text, image, but it can't be arrow, line, freedraw, **group**)
The element connecting node and node must be an **arrow** and have the correct direction, e.g. **parent node -> children node**
# sort
The order of nodes in the Y axis or vertical direction is determined by **the creation time** of the arrow connecting it
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-mindmap-format-2.png)
So if you want to readjust the order, you can **delete arrows and reconnect them**
# setting
Script provides options to adjust the style of mind map, The option is at the bottom of the option of the exalidraw plugin(e.g. Settings -> Community plugins -> Excalidraw -> drag to bottom)
# problem
1. since the start bingding and end bingding of the arrow are easily disconnected from the node, so if there are unformatted parts, please **check the connection** and use the script to **reformat**
```javascript
*/
let settings = ea.getScriptSettings();
//set default values on first run
if (!settings["MindMap Format"]) {
settings = {
"MindMap Format": {
value: "Excalidraw/MindMap Format",
description:
"This is prepared for the namespace of MindMap Format and does not need to be modified",
},
"default gap": {
value: 10,
description: "Interval size of element",
},
"curve length": {
value: 40,
description: "The length of the curve part in the mind map line",
},
"length between element and line": {
value: 50,
description:
"The distance between the tail of the connection and the connecting elements of the mind map",
},
};
ea.setScriptSettings(settings);
}
// default X coordinate of the middle point of the arc
const defaultDotX = Number(settings["curve length"].value);
// The default length from the middle point of the arc on the X axis
const defaultLengthWithCenterDot = Number(
settings["length between element and line"].value
);
// Initial trimming distance of the end point on the Y axis
const initAdjLength = 4;
// default gap
const defaultGap = Number(settings["default gap"].value);
const setCenter = (parent, line) => {
// Focus and gap need the api calculation of excalidraw
// e.g. determineFocusDistance, but they are not available now
// so they are uniformly set to 0/1
line.startBinding.focus = 0;
line.startBinding.gap = 1;
line.endBinding.focus = 0;
line.endBinding.gap = 1;
line.x = parent.x + parent.width;
line.y = parent.y + parent.height / 2;
};
/**
* set the middle point of curve
* @param {any} lineEl the line element of excalidraw
* @param {number} height height of dot on Y axis
* @param {number} [ratio=1] coefficient of the initial trimming distance of the end point on the Y axis, default is 1
*/
const setTopCurveDotOnLine = (lineEl, height, ratio = 1) => {
if (lineEl.points.length < 3) {
lineEl.points.splice(1, 0, [defaultDotX, lineEl.points[0][1] - height]);
} else if (lineEl.points.length === 3) {
lineEl.points[1] = [defaultDotX, lineEl.points[0][1] - height];
} else {
lineEl.points.splice(2, lineEl.points.length - 3);
lineEl.points[1] = [defaultDotX, lineEl.points[0][1] - height];
}
lineEl.points[2][0] = lineEl.points[1][0] + defaultLengthWithCenterDot;
// adjust the curvature of the second line segment
lineEl.points[2][1] = lineEl.points[1][1] - initAdjLength * ratio * 0.8;
};
const setMidCurveDotOnLine = (lineEl) => {
if (lineEl.points.length < 3) {
lineEl.points.splice(1, 0, [defaultDotX, lineEl.points[0][1]]);
} else if (lineEl.points.length === 3) {
lineEl.points[1] = [defaultDotX, lineEl.points[0][1]];
} else {
lineEl.points.splice(2, lineEl.points.length - 3);
lineEl.points[1] = [defaultDotX, lineEl.points[0][1]];
}
lineEl.points[2][0] = lineEl.points[1][0] + defaultLengthWithCenterDot;
lineEl.points[2][1] = lineEl.points[1][1];
};
/**
* set the middle point of curve
* @param {any} lineEl the line element of excalidraw
* @param {number} height height of dot on Y axis
* @param {number} [ratio=1] coefficient of the initial trimming distance of the end point on the Y axis, default is 1
*/
const setBottomCurveDotOnLine = (lineEl, height, ratio = 1) => {
if (lineEl.points.length < 3) {
lineEl.points.splice(1, 0, [defaultDotX, lineEl.points[0][1] + height]);
} else if (lineEl.points.length === 3) {
lineEl.points[1] = [defaultDotX, lineEl.points[0][1] + height];
} else {
lineEl.points.splice(2, lineEl.points.length - 3);
lineEl.points[1] = [defaultDotX, lineEl.points[0][1] + height];
}
lineEl.points[2][0] = lineEl.points[1][0] + defaultLengthWithCenterDot;
// adjust the curvature of the second line segment
lineEl.points[2][1] = lineEl.points[1][1] + initAdjLength * ratio * 0.8;
};
const setTextXY = (rect, text) => {
text.x = rect.x + (rect.width - text.width) / 2;
text.y = rect.y + (rect.height - text.height) / 2;
};
const setChildrenXY = (parent, children, line, elementsMap) => {
children.x = parent.x + parent.width + line.points[2][0];
children.y =
parent.y + parent.height / 2 + line.points[2][1] - children.height / 2;
if (
["rectangle", "diamond", "ellipse"].includes(children.type) &&
![null, undefined].includes(children.boundElements)
) {
const textDesc = children.boundElements.filter(
(el) => el.type === "text"
)[0];
if (textDesc !== undefined) {
const textEl = elementsMap.get(textDesc.id);
setTextXY(children, textEl);
}
}
};
/**
* returns the height of the upper part of all child nodes
* and the height of the lower part of all child nodes
* @param {Number[]} childrenTotalHeightArr
* @returns {Number[]} [topHeight, bottomHeight]
*/
const getNodeCurrentHeight = (childrenTotalHeightArr) => {
if (childrenTotalHeightArr.length <= 0) return [0, 0];
else if (childrenTotalHeightArr.length === 1)
return [childrenTotalHeightArr[0] / 2, childrenTotalHeightArr[0] / 2];
const heightArr = childrenTotalHeightArr;
let topHeight = 0,
bottomHeight = 0;
const isEven = heightArr.length % 2 === 0;
const mid = Math.floor(heightArr.length / 2);
const topI = mid - 1;
const bottomI = isEven ? mid : mid + 1;
topHeight = isEven ? 0 : heightArr[mid] / 2;
for (let i = topI; i >= 0; i--) {
topHeight += heightArr[i];
}
bottomHeight = isEven ? 0 : heightArr[mid] / 2;
for (let i = bottomI; i < heightArr.length; i++) {
bottomHeight += heightArr[i];
}
return [topHeight, bottomHeight];
};
/**
* handle the height of each point in the single-level tree
* @param {Array} lines
* @param {Map} elementsMap
* @param {Boolean} isEven
* @param {Number} mid 'lines' array midpoint index
* @returns {Array} height array corresponding to 'lines'
*/
const handleDotYValue = (lines, elementsMap, isEven, mid) => {
const getTotalHeight = (line, elementsMap) => {
return elementsMap.get(line.endBinding.elementId).totalHeight;
};
const getTopHeight = (line, elementsMap) => {
return elementsMap.get(line.endBinding.elementId).topHeight;
};
const getBottomHeight = (line, elementsMap) => {
return elementsMap.get(line.endBinding.elementId).bottomHeight;
};
const heightArr = new Array(lines.length).fill(0);
const upI = mid === 0 ? 0 : mid - 1;
const bottomI = isEven ? mid : mid + 1;
let initHeight = isEven ? 0 : getTopHeight(lines[mid], elementsMap);
for (let i = upI; i >= 0; i--) {
heightArr[i] = initHeight + getBottomHeight(lines[i], elementsMap);
initHeight += getTotalHeight(lines[i], elementsMap);
}
initHeight = isEven ? 0 : getBottomHeight(lines[mid], elementsMap);
for (let i = bottomI; i < lines.length; i++) {
heightArr[i] = initHeight + getTopHeight(lines[i], elementsMap);
initHeight += getTotalHeight(lines[i], elementsMap);
}
return heightArr;
};
/**
* format single-level tree
* @param {any} parent
* @param {Array} lines
* @param {Map} childrenDescMap
* @param {Map} elementsMap
*/
const formatTree = (parent, lines, childrenDescMap, elementsMap) => {
lines.forEach((item) => setCenter(parent, item));
const isEven = lines.length % 2 === 0;
const mid = Math.floor(lines.length / 2);
const heightArr = handleDotYValue(lines, childrenDescMap, isEven, mid);
lines.forEach((item, index) => {
if (isEven) {
if (index < mid) setTopCurveDotOnLine(item, heightArr[index], index + 1);
else setBottomCurveDotOnLine(item, heightArr[index], index - mid + 1);
} else {
if (index < mid) setTopCurveDotOnLine(item, heightArr[index], index + 1);
else if (index === mid) setMidCurveDotOnLine(item);
else setBottomCurveDotOnLine(item, heightArr[index], index - mid);
}
});
lines.forEach((item) => {
if (item.endBinding !== null) {
setChildrenXY(
parent,
elementsMap.get(item.endBinding.elementId),
item,
elementsMap
);
}
});
};
const generateTree = (elements) => {
const elIdMap = new Map([[elements[0].id, elements[0]]]);
let minXEl = elements[0];
for (let i = 1; i < elements.length; i++) {
elIdMap.set(elements[i].id, elements[i]);
if (
!(elements[i].type === "arrow" || elements[i].type === "line") &&
elements[i].x < minXEl.x
) {
minXEl = elements[i];
}
}
const root = {
el: minXEl,
totalHeight: minXEl.height,
topHeight: 0,
bottomHeight: 0,
linkChildrensLines: [],
isLeafNode: false,
children: [],
};
const preIdSet = new Set(); // The id_set of Elements that is already in the tree, avoid a dead cycle
const dfsForTreeData = (root) => {
if (preIdSet.has(root.el.id)) {
return 0;
}
preIdSet.add(root.el.id);
let lines = root.el.boundElements.filter(
(el) =>
el.type === "arrow" &&
!preIdSet.has(el.id) &&
elIdMap.get(el.id)?.startBinding?.elementId === root.el.id
);
if (lines.length === 0) {
root.isLeafNode = true;
root.totalHeight = root.el.height + 2 * defaultGap;
[root.topHeight, root.bottomHeight] = [
root.totalHeight / 2,
root.totalHeight / 2,
];
return root.totalHeight;
} else {
lines = lines.map((elementDesc) => {
preIdSet.add(elementDesc.id);
return elIdMap.get(elementDesc.id);
});
}
const linkChildrensLines = [];
lines.forEach((el) => {
const line = el;
if (
line &&
line.endBinding !== null &&
line.endBinding !== undefined &&
!preIdSet.has(elIdMap.get(line.endBinding.elementId).id)
) {
const children = elIdMap.get(line.endBinding.elementId);
linkChildrensLines.push(line);
root.children.push({
el: children,
totalHeight: 0,
topHeight: 0,
bottomHeight: 0,
linkChildrensLines: [],
isLeafNode: false,
children: [],
});
}
});
let totalHeight = 0;
root.children.forEach((el) => (totalHeight += dfsForTreeData(el)));
root.linkChildrensLines = linkChildrensLines;
if (root.children.length === 0) {
root.isLeafNode = true;
root.totalHeight = root.el.height + 2 * defaultGap;
[root.topHeight, root.bottomHeight] = [
root.totalHeight / 2,
root.totalHeight / 2,
];
} else if (root.children.length > 0) {
root.totalHeight = Math.max(root.el.height + 2 * defaultGap, totalHeight);
[root.topHeight, root.bottomHeight] = getNodeCurrentHeight(
root.children.map((item) => item.totalHeight)
);
}
return totalHeight;
};
dfsForTreeData(root);
const dfsForFormat = (root) => {
if (root.isLeafNode) return;
const childrenDescMap = new Map(
root.children.map((item) => [item.el.id, item])
);
formatTree(root.el, root.linkChildrensLines, childrenDescMap, elIdMap);
root.children.forEach((el) => dfsForFormat(el));
};
dfsForFormat(root);
};
const elements = ea.getViewSelectedElements();
generateTree(elements);
ea.copyViewElementsToEAforEditing(elements);
await ea.addElementsToView(false, false);

View File

@@ -0,0 +1 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1673428425027" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1642" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24"><path d="M388.7 542.88c-16.57 0-30-13.43-30-30s13.43-30 30-30c52.3 0 94.85-42.55 94.85-94.85v-67.81c0-40.96 15.84-79.58 44.6-108.74 28.76-29.16 67.16-45.53 108.12-46.1l3.43-0.05c16.57-0.22 30.18 13.02 30.41 29.58 0.23 16.57-13.02 30.18-29.58 30.41l-3.43 0.05c-51.58 0.71-93.55 43.25-93.55 94.84v67.81c0 85.4-69.47 154.86-154.85 154.86z" fill="#000000" p-id="1643"></path><path d="M640.12 860.42h-0.42l-3.43-0.05c-40.96-0.56-79.36-16.93-108.12-46.09s-44.6-67.78-44.6-108.74v-67.8c0-52.3-42.55-94.85-94.85-94.85-16.57 0-30-13.43-30-30s13.43-30 30-30c85.38 0 154.85 69.47 154.85 154.85v67.8c0 51.59 41.96 94.13 93.55 94.84l3.43 0.05c16.57 0.23 29.81 13.84 29.59 30.41-0.24 16.42-13.62 29.58-30 29.58z" fill="#000000" p-id="1644"></path><path d="M640.11 542.88H388.7c-16.57 0-30-13.43-30-30s13.43-30 30-30h251.42c16.57 0 30 13.43 30 30-0.01 16.57-13.44 30-30.01 30z" fill="#000000" p-id="1645"></path><path d="M343.89 638.95H137.78c-38.6 0-70-31.4-70-70V456.81c0-38.6 31.4-70 70-70h206.11c38.6 0 70 31.4 70 70v112.13c0 38.6-31.4 70.01-70 70.01zM137.78 446.81c-5.51 0-10 4.49-10 10v112.13c0 5.51 4.49 10 10 10h206.11c5.51 0 10-4.49 10-10V456.81c0-5.51-4.49-10-10-10H137.78zM830.16 316.96h-93.98c-69.51 0-126.07-56.55-126.07-126.07S666.66 64.83 736.18 64.83h93.98c69.51 0 126.07 56.55 126.07 126.07-0.01 69.5-56.56 126.06-126.07 126.06z m-93.98-192.13c-36.43 0-66.07 29.64-66.07 66.07s29.64 66.07 66.07 66.07h93.98c36.43 0 66.07-29.64 66.07-66.07s-29.64-66.07-66.07-66.07h-93.98zM830.16 638.95h-93.98c-69.51 0-126.07-56.55-126.07-126.07 0-69.51 56.55-126.07 126.07-126.07h93.98c69.51 0 126.07 56.55 126.07 126.07-0.01 69.51-56.56 126.07-126.07 126.07z m-93.98-192.14c-36.43 0-66.07 29.64-66.07 66.07 0 36.43 29.64 66.07 66.07 66.07h93.98c36.43 0 66.07-29.64 66.07-66.07 0-36.43-29.64-66.07-66.07-66.07h-93.98z" fill="#000000" p-id="1646"></path><path d="M830.16 959.17h-93.98c-69.51 0-126.07-56.55-126.07-126.07s56.55-126.07 126.07-126.07h93.98c69.51 0 126.07 56.55 126.07 126.07s-56.56 126.07-126.07 126.07z m-93.98-192.13c-36.43 0-66.07 29.64-66.07 66.07s29.64 66.07 66.07 66.07h93.98c36.43 0 66.07-29.64 66.07-66.07s-29.64-66.07-66.07-66.07h-93.98z" fill="#000000" p-id="1647"></path></svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@@ -26,8 +26,7 @@ if(!settings["Gap"]) {
let gapValue = settings["Gap"].value;
const selectedIndividualArrows = ea.getMaximumGroups(ea.getViewSelectedElements())
.reduce((result, group) => (group.length === 1 && (group[0].type === 'arrow' || group[0].type === 'line')) ?
[...result, group[0]] : result, []);
.reduce((result, g) => [...result, ...g.filter(el => el.type === 'arrow')], []);
const allElements = ea.getViewElements();
for(const arrow of selectedIndividualArrows) {

View File

@@ -5,7 +5,15 @@ Converts selected freedraw lines such that pencil pressure will decrease from ma
```javascript
*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.8.8")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
let elements = ea.getViewSelectedElements().filter((el)=>["freedraw","line","arrow"].includes(el.type));
//if nothing is selected find the last element that was drawn and use it if it is the right element type
if(elements.length === 0) {
elements = ea.getViewSelectedElements();
const len = elements.length;
@@ -14,14 +22,59 @@ if(elements.length === 0) {
}
elements = [elements[len]];
}
elements.forEach((el)=>{
const lineType = await utils.suggester(["Thick to thin", "Thin to thick to thin"],["l1","l2"],"Select the type of line");
if(!lineType) return;
ea.copyViewElementsToEAforEditing(elements);
ea.getElements().forEach((el)=>{
el.simulatePressure = false;
el.type = "freedraw";
el.pressures = [];
const len = el.points.length;
for(i=0;i<len;i++)
el.pressures.push((len-i)/len);
el.pressures = Array(el.points.length).fill(1);
el.customData = {
strokeOptions: {
... lineType === "l1"
? {
options: {
thinning: 1,
smoothing: 0.5,
streamline: 0.5,
easing: "linear",
start: {
taper: 0,
cap: true
},
end: {
taper: true,
easing: "linear",
cap: false
}
}
}
: {
options: {
thinning: 4,
smoothing: 0.5,
streamline: 0.5,
easing: "linear",
start: {
taper: true,
easing: "linear",
cap: true
},
end: {
taper: true,
easing: "linear",
cap: false
}
}
}
}
};
});
ea.copyViewElementsToEAforEditing(elements);
await ea.addElementsToView(false,false);
elements.forEach((el)=>ea.moveViewElementToZIndex(el.id,0));
await ea.addElementsToView(false,true);
elements.forEach((el)=>ea.moveViewElementToZIndex(el.id,0));
const ids=ea.getElements().map(el=>el.id);
ea.selectElementsInView(ea.getViewElements().filter(el=>ids.contains(el.id)));

View File

@@ -75,3 +75,5 @@ Open the script you are interested in and save it to your Obsidian Vault includi
|[Toggle Fullscreen on Mobile](Toggle%20Fullscreen%20on%20Mobile.md)|Hides Obsidian workspace leaf padding and header (based on option in settings, default is "hide header" = false) which will take Excalidraw to full screen. ⚠ Note that if the header is not visible, it will be very difficult to invoke the command palette to end full screen. Only hide the header if you have a keyboard or you've practiced opening command palette!|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/ea-toggle-fullscreen.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Transfer TextElements to Excalidraw markdown metadata](Transfer%20TextElements%20to%20Excalidraw%20markdown%20metadata.md)|The script will delete the selected text elements from the canvas and will copy the text from these text elements into the Excalidraw markdown file as metadata. This means, that the text will no longer be visible in the drawing, however you will be able to search for the text in Obsidian and find the drawing containing this image.|![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-to-metadata.jpg)|[@zsviczian](https://github.com/zsviczian)|
|[Zoom to Fit Selected Elements](Zoom%20to%20Fit%20Selected%20Elements.md)|Similar to Excalidraw standard <kbd>SHIFT+2</kbd> feature: Zoom to fit selected elements, but with the ability to zoom to 1000%. Inspiration: [#272](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/272)||[@zsviczian](https://github.com/zsviczian)|
|[Hardware Eraser Suppoer](Hardware%20Eraser%20Support.md)|Allows the use of pen inversion/hardware erasers on supported pens.|[@threethan](https://github.com/threethan)|
|[Hardware Eraser Suppoer](Auto%20Draw%20for%20Pen.md)|Automatically switched from the Select tool to the Draw tool when a pen is hovered, and then back.|[@threethan](https://github.com/threethan)|

View File

@@ -1,29 +1,386 @@
/*
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-scribble-helper.jpg)
iOS scribble helper for better handwriting experience with text elements. If no elements are selected then the script creates a text element at the pointer position and you can use the edit box to modify the text with scribble. If a text element is selected then the script opens the input prompt where you can modify this text with scribble.
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.
```javascript
*/
elements = ea.getViewSelectedElements().filter(el=>el.type==="text");
if(elements.length > 1) {
new Notice ("Select only 1 or 0 text elements.")
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.8.25")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
const text = await utils.inputPrompt("Edit text","",(elements.length === 1)?elements[0].rawText:"");
if(!text) return;
const helpLINK = "https://youtu.be/BvYkOaly-QM";
const DBLCLICKTIMEOUT = 300;
const maxWidth = 600;
const padding = 6;
const api = ea.getExcalidrawAPI();
const win = ea.targetView.ownerWindow;
if(!win.ExcalidrawScribbleHelper) win.ExcalidrawScribbleHelper = {};
if(typeof win.ExcalidrawScribbleHelper.penOnly === "undefined") {
win.ExcalidrawScribbleHelper.penOnly = false;
}
let windowOpen = false; //to prevent the modal window to open again while writing with scribble
let prevZoomValue = api.getAppState().zoom.value; //used to avoid trigger on pinch zoom
if(elements.length === 1) {
ea.copyViewElementsToEAforEditing(elements);
ea.getElements()[0].originalText = text;
ea.getElements()[0].text = text;
ea.getElements()[0].rawText = text;
// -------------
// Load settings
// -------------
let settings = ea.getScriptSettings();
//set default values on first-ever run of the script
if(!settings["Default action"]) {
settings = {
"Default action" : {
value: "Text",
valueset: ["Text","Sticky","Wrap"],
description: "What type of element should CTRL/CMD+ENTER create. TEXT: A regular text element. " +
"STICKY: A sticky note with border color and background color " +
"(using the current setting of the canvas). STICKY: A sticky note with transparent " +
"border and background color."
},
};
await ea.setScriptSettings(settings);
}
if(typeof win.ExcalidrawScribbleHelper.action === "undefined") {
win.ExcalidrawScribbleHelper.action = settings["Default action"].value;
}
//---------------------------------------
// Color Palette for stroke color setting
//---------------------------------------
// https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.6.8
const defaultStrokeColors = [
"#000000", "#343a40", "#495057", "#c92a2a", "#a61e4d",
"#862e9c", "#5f3dc4", "#364fc7", "#1864ab", "#0b7285",
"#087f5b", "#2b8a3e", "#5c940d", "#e67700", "#d9480f"
];
const loadColorPalette = () => {
const st = api.getAppState();
const strokeColors = new Set();
let strokeColorPalette = st.colorPalette?.elementStroke ?? defaultStrokeColors;
if(Object.entries(strokeColorPalette).length === 0) {
strokeColorPalette = defaultStrokeColors;
}
ea.getViewElements().forEach(el => {
if(el.strokeColor.toLowerCase()==="transparent") return;
strokeColors.add(el.strokeColor);
});
strokeColorPalette.forEach(color => {
strokeColors.add(color)
});
strokeColors.add(st.currentItemStrokeColor ?? ea.style.strokeColor);
return strokeColors;
}
//----------------------------------------------------------
// Define variables to cache element location on first click
//----------------------------------------------------------
// if a single element is selected when the action is started, update that existing text
let containerElements = ea.getViewSelectedElements()
.filter(el=>["arrow","rectangle","ellipse","line","diamond"].contains(el.type));
let selectedTextElements = ea.getViewSelectedElements().filter(el=>el.type==="text");
//-------------------------------------------
// Functions to add and remove event listners
//-------------------------------------------
const addEventHandler = (handler) => {
if(win.ExcalidrawScribbleHelper.eventHandler) {
win.removeEventListner("pointerdown", handler);
}
win.addEventListener("pointerdown",handler);
win.ExcalidrawScribbleHelper.eventHandler = handler;
win.ExcalidrawScribbleHelper.window = win;
}
const removeEventHandler = (handler) => {
win.removeEventListener("pointerdown",handler);
delete win.ExcalidrawScribbleHelper.eventHandler;
delete win.ExcalidrawScribbleHelper.window;
}
//Stop the script if scribble helper is clicked and no eligable element is selected
let silent = false;
if (win.ExcalidrawScribbleHelper?.eventHandler) {
removeEventHandler(win.ExcalidrawScribbleHelper.eventHandler);
delete win.ExcalidrawScribbleHelper.eventHandler;
delete win.ExcalidrawScribbleHelper.window;
if(!(containerElements.length === 1 || selectedTextElements.length === 1)) {
new Notice ("Scribble Helper was stopped",1000);
return;
}
silent = true;
}
// ----------------------
// Custom dialog controls
// ----------------------
if (typeof win.ExcalidrawScribbleHelper.penOnly === "undefined") {
win.ExcalidrawScribbleHelper.penOnly = undefined;
}
if (typeof win.ExcalidrawScribbleHelper.penDetected === "undefined") {
win.ExcalidrawScribbleHelper.penDetected = false;
}
let timer = Date.now();
let eventHandler = () => {};
const customControls = (container) => {
const helpDIV = container.createDiv();
helpDIV.innerHTML = `<a href="${helpLINK}" target="_blank">Click here for help</a>`;
const viewBackground = api.getAppState().viewBackgroundColor;
const el1 = new ea.obsidian.Setting(container)
.setName(`Text color`)
.addDropdown(dropdown => {
Array.from(loadColorPalette()).forEach(color => {
const options = dropdown.addOption(color, color).selectEl.options;
options[options.length-1].setAttribute("style",`color: ${color
}; background: ${viewBackground};`);
});
dropdown
.setValue(ea.style.strokeColor)
.onChange(value => {
ea.style.strokeColor = value;
el1.nameEl.style.color = value;
})
})
el1.nameEl.style.color = ea.style.strokeColor;
el1.nameEl.style.background = viewBackground;
el1.nameEl.style.fontWeight = "bold";
const el2 = new ea.obsidian.Setting(container)
.setName(`Trigger editor by pen double tap only`)
.addToggle((toggle) => toggle
.setValue(win.ExcalidrawScribbleHelper.penOnly)
.onChange(value => {
win.ExcalidrawScribbleHelper.penOnly = value;
})
)
el2.settingEl.style.border = "none";
el2.settingEl.style.display = win.ExcalidrawScribbleHelper.penDetected ? "" : "none";
}
// -------------------------------
// Click / dbl click event handler
// -------------------------------
eventHandler = async (evt) => {
if(windowOpen) return;
if(ea.targetView !== app.workspace.activeLeaf.view) removeEventHandler(eventHandler);
if(evt && evt.target && !evt.target.hasClass("excalidraw__canvas")) return;
if(evt && (evt.ctrlKey || evt.altKey || evt.metaKey || evt.shiftKey)) return;
const st = api.getAppState();
win.ExcalidrawScribbleHelper.penDetected = st.penDetected;
//don't trigger text editor when editing a line or arrow
if(st.editingElement && ["arrow","line"].contains(st.editingElment.type)) return;
if(typeof win.ExcalidrawScribbleHelper.penOnly === "undefined") {
win.ExcalidrawScribbleHelper.penOnly = false;
}
if (evt && win.ExcalidrawScribbleHelper.penOnly &&
win.ExcalidrawScribbleHelper.penDetected && evt.pointerType !== "pen") return;
const now = Date.now();
//the <50 condition is to avoid false double click when pinch zooming
if((now-timer > DBLCLICKTIMEOUT) || (now-timer < 50)) {
prevZoomValue = st.zoom.value;
timer = now;
containerElements = ea.getViewSelectedElements()
.filter(el=>["arrow","rectangle","ellipse","line","diamond"].contains(el.type));
selectedTextElements = ea.getViewSelectedElements().filter(el=>el.type==="text");
return;
}
//further safeguard against triggering when pinch zooming
if(st.zoom.value !== prevZoomValue) return;
//sleeping to allow keyboard to pop up on mobile devices
await sleep(200);
ea.clear();
//if a single element with text is selected, edit the text
//(this can be an arrow, a sticky note, or just a text element)
if(selectedTextElements.length === 1) {
editExistingTextElement(selectedTextElements);
return;
}
let containerID;
let container;
//if no text elements are selected (i.e. not multiple text elements selected),
//check if there is a single eligeable container selected
if(selectedTextElements.length === 0) {
if(containerElements.length === 1) {
ea.copyViewElementsToEAforEditing(containerElements);
containerID = containerElements[0].id
container = ea.getElement(containerID);
}
}
const {x,y} = ea.targetView.currentPosition;
if(ea.targetView !== app.workspace.activeLeaf.view) return;
const actionButtons = [
{
caption: `A`,
tooltip: "Add as Text Element",
action: () => {
win.ExcalidrawScribbleHelper.action="Text";
if(settings["Default action"].value!=="Text") {
settings["Default action"].value = "Text";
ea.setScriptSettings(settings);
};
return;
}
},
{
caption: "📝",
tooltip: "Add as Sticky Note (rectangle with border color and background color)",
action: () => {
win.ExcalidrawScribbleHelper.action="Sticky";
if(settings["Default action"].value!=="Sticky") {
settings["Default action"].value = "Sticky";
ea.setScriptSettings(settings);
};
return;
}
},
{
caption: "☱",
tooltip: "Add as Wrapped Text (rectangle with transparent border and background)",
action: () => {
win.ExcalidrawScribbleHelper.action="Wrap";
if(settings["Default action"].value!=="Wrap") {
settings["Default action"].value = "Wrap";
ea.setScriptSettings(settings);
};
return;
}
}
];
if(win.ExcalidrawScribbleHelper.action !== "Text") actionButtons.push(actionButtons.shift());
if(win.ExcalidrawScribbleHelper.action === "Wrap") actionButtons.push(actionButtons.shift());
ea.style.strokeColor = st.currentItemStrokeColor ?? ea.style.strokeColor;
ea.style.roughness = st.currentItemRoughness ?? ea.style.roughness;
ea.setStrokeSharpness(st.currentItemRoundness === "round" ? 0 : st.currentItemRoundness)
ea.style.backgroundColor = st.currentItemBackgroundColor ?? ea.style.backgroundColor;
ea.style.fillStyle = st.currentItemFillStyle ?? ea.style.fillStyle;
ea.style.fontFamily = st.currentItemFontFamily ?? ea.style.fontFamily;
ea.style.fontSize = st.currentItemFontSize ?? ea.style.fontSize;
ea.style.textAlign = (container && ["arrow","line"].contains(container.type))
? "center"
: (container && ["rectangle","diamond","ellipse"].contains(container.type))
? "center"
: st.currentItemTextAlign ?? "center";
ea.style.verticalAlign = "middle";
windowOpen = true;
const text = await utils.inputPrompt (
"Edit text", "", "", containerID?undefined:actionButtons, 5, true, customControls, true
);
windowOpen = false;
if(!text || text.trim() === "") return;
const textId = ea.addText(x,y, text);
if (!container && (win.ExcalidrawScribbleHelper.action === "Text")) {
ea.addElementsToView(false, false, true);
addEventHandler(eventHandler);
return;
}
const textEl = ea.getElement(textId);
if(!container && (win.ExcalidrawScribbleHelper.action === "Wrap")) {
ea.style.backgroundColor = "transparent";
ea.style.strokeColor = "transparent";
}
if(!container && (win.ExcalidrawScribbleHelper.action === "Sticky")) {
textEl.textAlign = "center";
}
const boxes = [];
if(container) {
boxes.push(containerID);
const linearElement = ["arrow","line"].contains(container.type);
const l = linearElement ? container.points.length-1 : 0;
const dx = linearElement && (container.points[l][0] < 0) ? -1 : 1;
const dy = linearElement && (container.points[l][1] < 0) ? -1 : 1;
cx = container.x + dx*container.width/2;
cy = container.y + dy*container.height/2;
textEl.x = cx - textEl.width/2;
textEl.y = cy - textEl.height/2;
}
if(!container) {
const width = textEl.width+2*padding;
const widthOK = width<=maxWidth;
containerID = ea.addRect(
textEl.x-padding,
textEl.y-padding,
widthOK ? width : maxWidth,
textEl.height + 2 * padding
);
container = ea.getElement(containerID);
}
boxes.push(containerID);
container.boundElements=[{type:"text",id: textId}];
textEl.containerId = containerID;
//ensuring the correct order of elements, first container, then text
delete ea.elementsDict[textEl.id];
ea.elementsDict[textEl.id] = textEl;
await ea.addElementsToView(false,false,true);
const containers = ea.getViewElements().filter(el=>boxes.includes(el.id));
if(["rectangle","diamond","ellipse"].includes(container.type)) api.updateContainerSize(containers);
ea.selectElementsInView(containers);
};
// ---------------------
// Edit Existing Element
// ---------------------
const editExistingTextElement = async (elements) => {
windowOpen = true;
ea.copyViewElementsToEAforEditing(elements);
const el = ea.getElements()[0];
ea.style.strokeColor = el.strokeColor;
const text = await utils.inputPrompt(
"Edit text","",elements[0].rawText,undefined,5,true,customControls,true
);
windowOpen = false;
if(!text) return;
el.strokeColor = ea.style.strokeColor;
el.originalText = text;
el.text = text;
el.rawText = text;
ea.refreshTextElementSize(el.id);
await ea.addElementsToView(false,false);
return;
if(el.containerId) {
const containers = ea.getViewElements().filter(e=>e.id === el.containerId);
api.updateContainerSize(containers);
ea.selectElementsInView(containers);
}
}
ea.addText(0,0,text);
await ea.addElementsToView(true, false, true);
//--------------
// Start actions
//--------------
if(!win.ExcalidrawScribbleHelper?.eventHandler) {
if(!silent) new Notice(
"To create a new text element,\ndouble-tap the screen.\n\n" +
"To edit text,\ndouble-tap an existing element.\n\n" +
"To stop the script,\ntap it again or switch to a different tab.",
5000
);
addEventHandler(eventHandler);
}
if(containerElements.length === 1 || selectedTextElements.length === 1) {
timer = timer - 100;
eventHandler();
}

View File

@@ -8,11 +8,17 @@ https://zsviczian.github.io/obsidian-excalidraw-plugin/ExcalidrawScriptsEngine.h
```javascript
*/
const grid = parseInt(await utils.inputPrompt("Grid size?",null,"20"));
if(isNaN(grid)) return; //this is to avoid passing an illegal value to Excalidraw
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.8.11")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
const api = ea.getExcalidrawAPI();
let appState = api.getAppState();
const grid = parseInt(await utils.inputPrompt("Grid size?",null,appState.previousGridSize?.toString()??"20"));
if(isNaN(grid)) return; //this is to avoid passing an illegal value to Excalidraw
appState.gridSize = grid;
appState.previousGridSize = grid;
api.updateScene({
appState,
commitToHistory:false

View File

@@ -1,7 +1,7 @@
/*
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-set-background-color-of-unclosed-line.jpg)
Use this script to set the background color of unclosed (i.e. open) line and freedraw objects by creating a clone of the object. The script will set the stroke color of the clone to transparent and will add a straight line to close the object. Use settings to define the default background color, the fill style, and the strokeWidth of the clone. By default the clone will be grouped with the original object, you can disable this also in settings.
Use this script to set the background color of unclosed (i.e. open) line, arrow and freedraw objects by creating a clone of the object. The script will set the stroke color of the clone to transparent and will add a straight line to close the object. Use settings to define the default background color, the fill style, and the strokeWidth of the clone. By default the clone will be grouped with the original object, you can disable this also in settings.
```javascript
*/
@@ -41,9 +41,9 @@ const backgroundColor = settings["Background Color"].value;
const fillStyle = settings["Fill Style"].value;
const shouldGroup = settings["Group 'shadow' with original"].value;
const elements = ea.getViewSelectedElements().filter(el=>el.type==="line" || el.type==="freedraw");
const elements = ea.getViewSelectedElements().filter(el=>el.type==="line" || el.type==="freedraw" || el.type==="arrow");
if(elements.length === 0) {
new Notice("No line or freedraw object is selected");
new Notice("No line or freedraw object is selected");
}
ea.copyViewElementsToEAforEditing(elements);
@@ -52,19 +52,20 @@ elementsToMove = [];
elements.forEach((el)=>{
const newEl = ea.cloneElement(el);
ea.elementsDict[newEl.id] = newEl;
newEl.roughness = 1;
if(!inheritStrokeWidth) newEl.strokeWidth = 2;
newEl.roughness = 1;
if(!inheritStrokeWidth) newEl.strokeWidth = 2;
newEl.strokeColor = "transparent";
newEl.backgroundColor = backgroundColor;
newEl.fillStyle = fillStyle;
const i = el.points.length-1;
newEl.points.push([
//adding an extra point close to the last point in case distance is long from last point to origin and there is a sharp bend. This will avoid a spike due to a tight curve.
el.points[i][0]*0.9,
newEl.fillStyle = fillStyle;
if (newEl.type === "arrow") newEl.type = "line";
const i = el.points.length-1;
newEl.points.push([
//adding an extra point close to the last point in case distance is long from last point to origin and there is a sharp bend. This will avoid a spike due to a tight curve.
el.points[i][0]*0.9,
el.points[i][1]*0.9,
]);
]);
newEl.points.push([0,0]);
if(shouldGroup) ea.addToGroup([el.id,newEl.id]);
if(shouldGroup) ea.addToGroup([el.id,newEl.id]);
elementsToMove.push({fillId: newEl.id, shapeId: el.id});
});
@@ -72,9 +73,9 @@ await ea.addElementsToView(false,false);
elementsToMove.forEach((x)=>{
const viewElements = ea.getViewElements();
ea.moveViewElementToZIndex(
x.fillId,
x.fillId,
viewElements.indexOf(viewElements.filter(el=>el.id === x.shapeId)[0])-1
)
)
});
ea.selectElementsInView(ea.getElements());

490
ea-scripts/Slideshow.md Normal file
View File

@@ -0,0 +1,490 @@
/*
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-slideshow-1.jpg)
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-slideshow-2.jpg)
The script will convert your drawing into a slideshow presentation.
```javascript
*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.8.17")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
//constants
const STEPCOUNT = 100;
const FRAME_SLEEP = 1; //milliseconds
const EDIT_ZOOMOUT = 0.7; //70% of original slide zoom, set to a value between 1 and 0
//utility & convenience functions
const inPopoutWindow = ea.targetView.ownerDocument !== document;
const win = ea.targetView.ownerWindow;
const api = ea.getExcalidrawAPI();
const contentEl = ea.targetView.contentEl;
const sleep = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
//clean up potential clutter from previous run
window.removePresentationEventHandlers?.();
//check if line or arrow is selected, if not inform the user and terminate presentation
let lineEl = ea.getViewElements().filter(el=>["line","arrow"].contains(el.type) && el.customData?.slideshow)[0];
const selectedEl = ea.getViewSelectedElement();
let preventHideAction = false;
if(lineEl && selectedEl && ["line","arrow"].contains(selectedEl.type)) {
api.setToast({
message:"Using selected line instead of hidden line. Note that there is a hidden presentation path for this drawing. Run the slideshow script without selecting any elements to access the hidden presentation path",
duration: 5000,
closable: true
})
preventHideAction = true;
lineEl = selectedEl;
}
if(!lineEl) lineEl = selectedEl;
if(!lineEl || !["line","arrow"].contains(lineEl.type)) {
api.setToast({
message:"Please select the line or arrow for the presentation path",
duration: 3000,
closable: true
})
return;
}
//goto fullscreen
const gotoFullscreen = async () => {
if(app.isMobile) {
ea.viewToggleFullScreen(true);
} else {
if(!inPopoutWindow) {
await contentEl.webkitRequestFullscreen();
await sleep(500);
}
ea.setViewModeEnabled(true);
}
const deltaWidth = () => contentEl.clientWidth-api.getAppState().width;
let watchdog = 0;
while (deltaWidth()>50 && watchdog++<20) await sleep(100); //wait for Excalidraw to resize to fullscreen
contentEl.querySelector(".layer-ui__wrapper").addClass("excalidraw-hidden");
}
//hide the arrow and save the arrow color before doing so
const originalProps = lineEl.customData?.slideshow?.hidden
? lineEl.customData.slideshow.originalProps
: {
strokeColor: lineEl.strokeColor,
backgroundColor: lineEl.backgroundColor,
locked: lineEl.locked,
};
let hidden = lineEl.customData?.slideshow?.hidden ?? false;
const hideArrow = async (setToHidden) => {
ea.clear();
ea.copyViewElementsToEAforEditing(ea.getViewElements().filter(el=>el.id === lineEl.id));
const el = ea.getElement(lineEl.id);
el.strokeColor = "transparent";
el.backgroundColor = "transparent";
const customData = el.customData;
if(setToHidden && !preventHideAction) {
el.locked = true;
el.customData = {
...customData,
slideshow: {
originalProps,
hidden: true
}
}
hidden = true;
} else {
if(customData) delete el.customData.slideshow;
hidden = false;
}
await ea.addElementsToView();
}
//----------------------------
//scroll-to-location functions
//----------------------------
let slide = -1;
const slideCount = Math.floor(lineEl.points.length/2)-1;
const getNextSlide = (forward) => {
slide = forward
? slide < slideCount ? slide + 1 : 0
: slide <= 0 ? slideCount : slide - 1;
return {
pointA:lineEl.points[slide*2],
pointB:lineEl.points[slide*2+1]
}
}
const getSlideRect = ({pointA, pointB}) => {
const {width, height} = api.getAppState();
const x1 = lineEl.x+pointA[0];
const y1 = lineEl.y+pointA[1];
const x2 = lineEl.x+pointB[0];
const y2 = lineEl.y+pointB[1];
const ratioX = width/Math.abs(x1-x2);
const ratioY = height/Math.abs(y1-y2);
let ratio = ratioX<ratioY?ratioX:ratioY;
if (ratio < 0.1) ratio = 0.1;
if (ratio > 10) ratio = 10;
const deltaX = (ratio===ratioY)?(width/ratio - Math.abs(x1-x2))/2:0;
const deltaY = (ratio===ratioX)?(height/ratio - Math.abs(y1-y2))/2:0;
return {
left: (x1<x2?x1:x2)-deltaX,
top: (y1<y2?y1:y2)-deltaY,
right: (x1<x2?x2:x1)+deltaX,
bottom: (y1<y2?y2:y1)+deltaY,
nextZoom: ratio
};
}
let busy = false;
const scrollToNextRect = async ({left,top,right,bottom,nextZoom},steps = STEPCOUNT) => {
let watchdog = 0;
while(busy && watchdog++<15) await(100);
if(busy && watchdog >= 15) return;
busy = true;
api.updateScene({appState:{shouldCacheIgnoreZoom:true}});
const {scrollX, scrollY, zoom} = api.getAppState();
const zoomStep = (zoom.value-nextZoom)/steps;
const xStep = (left+scrollX)/steps;
const yStep = (top+scrollY)/steps;
for(i=1;i<=steps;i++) {
api.updateScene({
appState: {
scrollX:scrollX-(xStep*i),
scrollY:scrollY-(yStep*i),
zoom:{value:zoom.value-zoomStep*i},
}
});
await sleep(FRAME_SLEEP);
}
api.updateScene({appState:{shouldCacheIgnoreZoom:false}});
busy = false;
}
const navigate = async (dir) => {
const forward = dir === "fwd";
const prevSlide = slide;
const nextSlide = getNextSlide(forward);
//exit if user navigates from last slide forward or first slide backward
const shouldExit = forward
? slide<=prevSlide
: slide>=prevSlide;
if(shouldExit) {
exitPresentation();
return;
}
if(slideNumberEl) slideNumberEl.innerText = `${slide+1}/${slideCount+1}`;
const nextRect = getSlideRect(nextSlide);
await scrollToNextRect(nextRect);
if(settingsModal) {
slideNumberDropdown.setValue(`${slide}`.padStart(3,"0"));
}
}
//--------------------------
// Settings Modal
//--------------------------
let settingsModal;
let slideNumberDropdown;
const presentationSettings = () => {
let dirty = false;
settingsModal = new ea.obsidian.Modal(app);
const getSlideNumberLabel = (i) => {
switch(i) {
case 0: return "1 - Start";
case slideCount: return `${i+1} - End`;
default: return `${i+1}`;
}
}
const getSlidesList = () => {
const options = {};
for(i=0;i<=slideCount;i++) {
options[`${i}`.padStart(3,"0")] = getSlideNumberLabel(i);
}
return options;
}
settingsModal.onOpen = () => {
settingsModal.contentEl.createEl("h1",{text: "Slideshow Actions"});
settingsModal.contentEl.createEl("p",{text: "To open this window double click presentation script icon or press ENTER during presentation."});
new ea.obsidian.Setting(settingsModal.contentEl)
.setName("Jump to slide")
.addDropdown(dropdown => {
slideNumberDropdown = dropdown;
dropdown
.addOptions(getSlidesList())
.setValue(`${slide}`.padStart(3,"0"))
.onChange(value => {
slide = parseInt(value)-1;
navigate("fwd");
})
})
if(!preventHideAction) {
new ea.obsidian.Setting(settingsModal.contentEl)
.setName("Hide navigation arrow after slideshow")
.setDesc("Toggle on: arrow hidden, toggle off: arrow visible")
.addToggle(toggle => toggle
.setValue(hidden)
.onChange(value => hideArrow(value))
)
}
new ea.obsidian.Setting(settingsModal.contentEl)
.setName("Edit current slide")
.setDesc("Pressing 'e' during the presentation will open the current slide for editing.")
.addButton(button => button
.setButtonText("Edit")
.onClick(async ()=>{
await hideArrow(false);
exitPresentation(true);
})
)
}
settingsModal.onClose = () => {
setTimeout(()=>delete settingsModal);
}
settingsModal.open();
contentEl.appendChild(settingsModal.containerEl);
}
//--------------------------------------
//Slideshow control
//--------------------------------------
let controlPanelEl;
let slideNumberEl;
const createNavigationPanel = () => {
//create slideshow controlpanel container
const top = contentEl.innerHeight;
const left = contentEl.innerWidth;
controlPanelEl = contentEl.createDiv({
cls: ["excalidraw","excalidraw-presentation-panel"],
attr: {
style: `
width: calc(var(--default-button-size)*3);
z-index:5;
position: absolute;
top:calc(${top}px - var(--default-button-size)*2);
left:calc(${left}px - var(--default-button-size)*3.5);`
}
});
const panelColumn = controlPanelEl.createDiv({
cls: "panelColumn",
});
panelColumn.createDiv({
cls: ["Island", "buttonList"],
attr: {
style: `
height: calc(var(--default-button-size)*1.5);
width: 100%;
background: var(--island-bg-color);`,
}
}, el=>{
el.createEl("button",{
text: "<",
attr: {
style: `
margin-top: calc(var(--default-button-size)*0.25);
margin-left: calc(var(--default-button-size)*0.25);`
}
}, button => button .onclick = () => navigate("bkwd"));
el.createEl("button",{
text: ">",
attr: {
style: `
margin-top: calc(var(--default-button-size)*0.25);
margin-right: calc(var(--default-button-size)*0.25);`
}
}, button => button.onclick = () => navigate("fwd"));
slideNumberEl = el.createEl("span",{
text: "1",
cls: ["ToolIcon__keybinding"],
})
});
}
//keyboard navigation
const keydownListener = (e) => {
e.preventDefault();
switch(e.key) {
case "Escape":
if(app.isMobile || inPopoutWindow) exitPresentation();
break;
case "ArrowRight":
case "ArrowDown":
navigate("fwd");
break;
case "ArrowLeft":
case "ArrowUp":
navigate("bkwd");
break;
case "Enter":
presentationSettings();
break;
case "End":
slide = slideCount - 1;
navigate("fwd");
break;
case "Home":
slide = -1;
navigate("fwd");
break;
case "e":
(async ()=>{
await hideArrow(false);
exitPresentation(true);
})()
break;
}
}
//slideshow panel drag
let pos1 = pos2 = pos3 = pos4 = 0;
const updatePosition = (deltaY = 0, deltaX = 0) => {
const {
offsetTop,
offsetLeft,
clientWidth: width,
clientHeight: height,
} = controlPanelEl;
controlPanelEl.style.top = (offsetTop - deltaY) + 'px';
controlPanelEl.style.left = (offsetLeft - deltaX) + 'px';
}
const pointerUp = () => {
win.removeEventListener('pointermove', onDrag, true);
}
let dblClickTimer = 0;
const pointerDown = (e) => {
const now = Date.now();
pos3 = e.clientX;
pos4 = e.clientY;
win.addEventListener('pointermove', onDrag, true);
if(now-dblClickTimer < 400) {
presentationSettings();
}
dblClickTimer = now;
}
const onDrag = (e) => {
e.preventDefault();
pos1 = pos3 - e.clientX;
pos2 = pos4 - e.clientY;
pos3 = e.clientX;
pos4 = e.clientY;
updatePosition(pos2, pos1);
}
const initializeEventListners = () => {
win.addEventListener('keydown',keydownListener);
controlPanelEl.addEventListener('pointerdown', pointerDown, false);
win.addEventListener('pointerup', pointerUp, false);
//event listners for terminating the presentation
window.removePresentationEventHandlers = () => {
ea.onLinkClickHook = null;
controlPanelEl.parentElement?.removeChild(controlPanelEl);
if(!app.isMobile) win.removeEventListener('fullscreenchange', fullscreenListener);
win.removeEventListener('keydown',keydownListener);
win.removeEventListener('pointerup',pointerUp);
contentEl.querySelector(".layer-ui__wrapper")?.removeClass("excalidraw-hidden");
delete window.removePresentationEventHandlers;
}
ea.onLinkClickHook = () => {
exitPresentation();
return true;
};
if(!app.isMobile) {
win.addEventListener('fullscreenchange', fullscreenListener);
}
}
const exitPresentation = async (openForEdit = false) => {
if(openForEdit) ea.targetView.preventAutozoom();
if(!app.isMobile && !inPopoutWindow && document?.fullscreenElement) await document.exitFullscreen();
if(app.isMobile) {
ea.viewToggleFullScreen(true);
} else {
ea.setViewModeEnabled(false);
}
if(settingsModal) settingsModal.close();
ea.clear();
ea.copyViewElementsToEAforEditing(ea.getViewElements().filter(el=>el.id === lineEl.id));
const el = ea.getElement(lineEl.id);
if(!hidden) {
el.strokeColor = originalProps.strokeColor;
el.backgroundProps = originalProps.backgroundColor;
el.locked = openForEdit ? false : originalProps.locked;
}
await ea.addElementsToView();
if(!hidden) ea.selectElementsInView([el]);
if(openForEdit) {
const nextSlide = getNextSlide(--slide);
let nextRect = getSlideRect(nextSlide);
const offsetW = (nextRect.right-nextRect.left)*(1-EDIT_ZOOMOUT)/2;
const offsetH = (nextRect.bottom-nextRect.top)*(1-EDIT_ZOOMOUT)/2
nextRect = {
left: nextRect.left-offsetW,
right: nextRect.right+offsetW,
top: nextRect.top-offsetH,
bottom: nextRect.bottom+offsetH,
nextZoom: nextRect.nextZoom*EDIT_ZOOMOUT > 0.1 ? nextRect.nextZoom*EDIT_ZOOMOUT : 0.1 //0.1 is the minimu zoom value
};
await scrollToNextRect(nextRect,1);
api.startLineEditor(
ea.getViewSelectedElement(),
[slide*2,slide*2+1]
);
}
window.removePresentationEventHandlers?.();
setTimeout(()=>{
//Resets pointer offsets. Ugly solution.
//During testing offsets were wrong after presentation, but don't know why.
//This should solve it even if they are wrong.
ea.targetView.refresh();
})
}
const fullscreenListener = (e) => {
e.preventDefault();
exitPresentation();
}
//--------------------------
// Start presentation or open presentation settings on double click
//--------------------------
const start = async () => {
await gotoFullscreen();
await hideArrow(hidden);
createNavigationPanel();
initializeEventListners();
//navigate to the first slide on start
setTimeout(()=>navigate("fwd"));
}
const timestamp = Date.now();
if(window.ExcalidrawSlideshow && (window.ExcalidrawSlideshow.script === utils.scriptFile.path) && (timestamp - window.ExcalidrawSlideshow.timestamp <400) ) {
if(window.ExcalidrawSlideshowStartTimer) {
clearTimeout(window.ExcalidrawSlideshowStartTimer);
delete window.ExcalidrawSlideshowStartTimer;
}
await start();
presentationSettings();
} else {
window.ExcalidrawSlideshow = {
script: utils.scriptFile.path,
timestamp
};
window.ExcalidrawSlideshowStartTimer = setTimeout(start,500);
}

1
ea-scripts/Slideshow.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 5.9 KiB

View File

@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" stroke="#000" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><g fill="none"><circle cx="12" cy="12" r="10"></circle><path d="M17 12h.01"></path><path d="M12 12h.01"></path><path d="M7 12h.01"></path></g></svg>
<svg xmlns="http://www.w3.org/2000/svg" stroke="#000" width="24" height="24" viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><g stroke-width="2" fill="none"><circle cx="12" cy="12" r="10"></circle><path d="M17 12h.01"></path><path d="M12 12h.01"></path><path d="M7 12h.01"></path></g></svg>

Before

Width:  |  Height:  |  Size: 309 B

After

Width:  |  Height:  |  Size: 327 B

View File

@@ -0,0 +1,126 @@
/*
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-sticky-note-matrix.jpg)
Converts selected plain text element to sticky notes by dividing the text element line by line into separate sticky notes. The color of the stikcy note as well as the arrangement of the grid can be configured in plugin settings.
```javascript
*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.5.21")) {
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
return;
}
let settings = ea.getScriptSettings();
//set default values on first run
if(!settings["Border color"]) {
settings = {
"Border color" : {
value: "black",
description: "Any legal HTML color (#000000, rgb, color-name, etc.). Set to 'transparent' for transparent color."
},
"Background color" : {
value: "gold",
description: "Background color of the sticky note. Set to 'transparent' for transparent color."
},
"Background fill style" : {
value: "solid",
description: "Fill style of the sticky note",
valueset: ["hachure","cross-hatch","solid"]
}
};
await ea.setScriptSettings(settings);
}
if(!settings["Max sticky note width"]) {
settings["Max sticky note width"] = {
value: "600",
description: "Maximum width of new sticky note. If text is longer, it will be wrapped",
valueset: ["400","600","800","1000","1200","1400","2000"]
}
await ea.setScriptSettings(settings);
}
if(!settings["Sticky note width"]) {
settings["Sticky note width"] = {
value: "100",
description: "Preferred width of the sticky note. Set to 0 if unset.",
}
settings["Sticky note height"] = {
value: "120",
description: "Preferred height of the sticky note. Set to 0 if unset.",
}
settings["Rows per column"] = {
value: "3",
description: "If multiple text elements are converted to sticky notes in one step, how many rows before a next column is created. Only effective if fixed width & height are given. 0 for unset.",
}
settings["Gap"] = {
value: "10",
description: "Gap between rows and columns",
}
await ea.setScriptSettings(settings);
}
const pref_width = parseInt(settings["Sticky note width"].value);
const pref_height = parseInt(settings["Sticky note height"].value);
const pref_rows = parseInt(settings["Rows per column"].value);
const pref_gap = parseInt(settings["Gap"].value);
const maxWidth = parseInt(settings["Max sticky note width"].value);
const strokeColor = settings["Border color"].value;
const backgroundColor = settings["Background color"].value;
const fillStyle = settings["Background fill style"].value;
elements = ea.getViewSelectedElements().filter((el)=>el.type==="text");
elements.forEach((el)=>{
ea.style.strokeColor = el.strokeColor;
ea.style.fontFamily = el.fontFamily;
ea.style.fontSize = el.fontSize;
const text = el.text.split("\n");
for(i=0;i<text.length;i++) {
ea.addText(el.x,el.y+i*el.height/text.length,text[i].trim());
}
});
ea.deleteViewElements(elements);
ea.style.strokeColor = strokeColor;
ea.style.backgroundColor = backgroundColor;
ea.style.fillStyle = fillStyle;
const padding = 6;
const boxes = [];
const doMatrix = pref_width > 0 && pref_height > 0 && pref_rows > 0 && pref_gap > 0;
let row = 0;
let col = doMatrix ? -1 : 0;
ea.getElements().forEach((el, idx)=>{
if(doMatrix) {
if(idx % pref_rows === 0) {
row=0;
col++;
} else {
row++;
}
}
const width = pref_width > 0 ? pref_width : el.width+2*padding;
const widthOK = pref_width > 0 || width<=maxWidth;
const id = ea.addRect(
(doMatrix?col*pref_width+col*pref_gap:0)+el.x-padding,
(doMatrix?row*pref_height+row*pref_gap:0),
widthOK?width:maxWidth,pref_height > 0 ? pref_height : el.height+2*padding
);
boxes.push(id);
ea.getElement(id).boundElements=[{type:"text",id:el.id}];
el.containerId = id;
});
const els = Object.entries(ea.elementsDict);
let newEls = [];
for(i=0;i<els.length/2;i++) {
newEls.push(els[els.length/2+i]);
newEls.push(els[i])
}
ea.elementsDict = Object.fromEntries(newEls);
await ea.addElementsToView(false,true);
const containers = ea.getViewElements().filter(el=>boxes.includes(el.id));
ea.getExcalidrawAPI().updateContainerSize(containers);
ea.selectElementsInView(containers);

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"><circle stroke-width="2" cx="12" cy="5" r="1"></circle><circle stroke-width="2" cx="19" cy="5" r="1"></circle><circle stroke-width="2" cx="5" cy="5" r="1"></circle><circle stroke-width="2" cx="12" cy="12" r="1"></circle><circle stroke-width="2" cx="19" cy="12" r="1"></circle><circle stroke-width="2" cx="5" cy="12" r="1"></circle><circle stroke-width="2" cx="12" cy="19" r="1"></circle><circle stroke-width="2" cx="19" cy="19" r="1"></circle><circle stroke-width="2" cx="5" cy="19" r="1"></circle></svg>

After

Width:  |  Height:  |  Size: 685 B

View File

@@ -0,0 +1,52 @@
/*
![](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-uniform-size.jpg)
The script will standardize the sizes of rectangles, diamonds and ellipses adjusting all the elements to match the largest width and height within the group.
```javascript
*/
const boxShapesDispaly=["○ ellipse","□ rectangle","◇ diamond"];
const boxShapes=["ellipse","rectangle","diamond"];
let editedElements = [];
const elements = ea.getViewSelectedElements().filter(el=>boxShapes.contains(el.type));
if(elements.length===0) {
new Notice("No rectangle, or diamond or ellipse elements are selected. Please select some elements");
return;
}
const typeSet = new Set();
elements.forEach(el=>typeSet.add(el.type));
const elementType = await utils.suggester(
Array.from(typeSet).map((item) => {
switch(item) {
case "ellipse": return "○ ellipse";
case "rectangle": return "□ rectangle";
case "diamond": return "◇ diamond";
default: return item;
}
}),
Array.from(typeSet),
"Select element types to resize"
);
if(!elementType) return;
ea.copyViewElementsToEAforEditing(elements.filter(el=>el.type===elementType));
let width = height = 0;
ea.getElements().forEach(el=>{
if(el.width>width) width = el.width;
if(el.height>height) height = el.height;
})
ea.getElements().forEach(el=>{
el.width = width;
el.height = height;
})
const ids = ea.getElements().map(el=>el.id);
await ea.addElementsToView(false,true);
ea.getExcalidrawAPI().updateContainerSize(ea.getViewElements().filter(el=>ids.contains(el.id)));

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d="M40 352c-22.1 0-40 17.9-40 40l0 48c0 22.1 17.9 40 40 40l48 0c22.1 0 40-17.9 40-40l0-48c0-22.1-17.9-40-40-40l-48 0zm192 0c-22.1 0-40 17.9-40 40l0 48c0 22.1 17.9 40 40 40l48 0c22.1 0 40-17.9 40-40l0-48c0-22.1-17.9-40-40-40l-48 0zM40 320l48 0c22.1 0 40-17.9 40-40l0-48c0-22.1-17.9-40-40-40l-48 0c-22.1 0-40 17.9-40 40l0 48c0 22.1 17.9 40 40 40zM232 192c-22.1 0-40 17.9-40 40l0 48c0 22.1 17.9 40 40 40l48 0c22.1 0 40-17.9 40-40l0-48c0-22.1-17.9-40-40-40l-48 0zM40 160l48 0c22.1 0 40-17.9 40-40l0-48c0-22.1-17.9-40-40-40L40 32C17.9 32 0 49.9 0 72l0 48c0 22.1 17.9 40 40 40zM232 32c-22.1 0-40 17.9-40 40l0 48c0 22.1 17.9 40 40 40l48 0c22.1 0 40-17.9 40-40l0-48c0-22.1-17.9-40-40-40l-48 0z"/></svg>

After

Width:  |  Height:  |  Size: 930 B

File diff suppressed because one or more lines are too long

View File

@@ -31,6 +31,8 @@ I would love to include your contribution in the script library. If you have a s
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20Existing%20File%20and%20Open.svg"/></div>|[[#Add Link to Existing File and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20New%20Page%20and%20Open.svg"/></div>|[[#Add Link to New Page and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Next%20Step%20in%20Process.svg"/></div>|[[#Add Next Step in Process]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Auto%20Draw%20for%20Pen.svg"/></div>|[[#Auto Draw for Pen]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Auto%20Layout.svg"/></div>|[[#Auto Layout]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Box%20Each%20Selected%20Groups.svg"/></div>|[[#Box Each Selected Groups]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Box%20Selected%20Elements.svg"/></div>|[[#Box Selected Elements]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Change%20shape%20of%20selected%20elements.svg"/></div>|[[#Change shape of selected elements]]|
@@ -41,6 +43,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/Copy%20Selected%20Element%20Styles%20to%20Global.svg"/></div>|[[#Copy Selected Element Styles to Global]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.svg"/></div>|[[#Create new markdown file and embed into active drawing]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Darken%20background%20color.svg"/></div>|[[#Darken background color]]|
|<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/Elbow%20connectors.svg"/></div>|[[#Elbow connectors]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Expand%20rectangles%20horizontally%20keep%20text%20centered.svg"/></div>|[[#Expand rectangles horizontally keep text centered]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Expand%20rectangles%20horizontally.svg"/></div>|[[#Expand rectangles horizontally]]|
@@ -51,12 +54,15 @@ 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/Fixed%20spacing.svg"/></div>|[[#Fixed spacing]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Fixed%20vertical%20distance%20between%20centers.svg"/></div>|[[#Fixed vertical distance between centers]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Fixed%20vertical%20distance.svg"/></div>|[[#Fixed vertical distance]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Folder%20Note%20Core%20-%20Make%20Current%20Drawing%20a%20Folder.svg"/></div>|[[#Folder Note Core - Make Current Drawing a Folder]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Grid%20Selected%20Images.svg"/></div>|[[#Grid selected images]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Hardware%20Eraser%20Support.svg"/></div>|[[#Hardware Eraser Support]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Invert%20colors.svg"/></div>|[[#Invert colors]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Lighten%20background%20color.svg"/></div>|[[#Lighten background color]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20connector.svg"/></div>|[[#Mindmap connector]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20format.svg"/></div>|[[#Mindmap format]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Modify%20background%20color%20opacity.svg"/></div>|[[#Modify background color opacity]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Normalize%20Selected%20Arrows.svg"/></div>|[[#Normalize Selected Arrows]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/OCR%20-%20Optical%20Character%20Recognition.svg"/></div>|[[#OCR - Optical Character Recognition]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Organic%20Line.svg"/></div>|[[#Organic Line]]|
|<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/Rename%20Image.svg"/></div>|[[#Rename Image]]|
@@ -71,11 +77,14 @@ I would love to include your contribution in the script library. If you have a s
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Link%20Alias.svg"/></div>|[[#Set Link Alias]]|
|<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/Set%20Text%20Alignment.svg"/></div>|[[#Set Text Alignment]]|
|<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/Split%20text%20by%20lines.svg"/></div>|[[#Split text by lines]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20Arch.svg"/></div>|[[#Text Arch]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Transfer%20TextElements%20to%20Excalidraw%20markdown%20metadata.svg"/></div>|[[#Transfer TextElements to Excalidraw markdown metadata]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20to%20Sticky%20Notes.svg"/></div>|[[#Text to Sticky Notes]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Uniform%20size.svg"/></div>|[[#Uniform Size]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Zoom%20to%20Fit%20Selected%20Elements.svg"/></div>|[[#Zoom to Fit Selected Elements]]|
## Add Connector Point
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Connector%20Point.md
@@ -100,6 +109,24 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Add%20Next%20Step%20in%20Process.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will prompt you for the title of the process step, then will create a stick note with the text. If an element is selected then the script will connect this new step with an arrow to the previous step (the selected element). If no element is selected, then the script assumes this is the first step in the process and will only output the sticky note with the text that was entered.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-add-process-step.jpg'></td></tr></table>
## Alternative Pens
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Alternative%20Pens.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/Alternative%20Pens.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will load pen presets overriding the default freedraw line in Excalidraw. Once you've downloaded this script, check the script description for a detailed how to guide.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-alternative-pens.jpg'></td></tr></table>
## Auto Draw for Pen
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Auto%20Draw%20for%20Pen.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/threethan'>@threethan</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/Auto%20Draw%20for%20Pen.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Automatically switches from select mode to drawing mode when hovering a pen, and then back.</td></tr></table>
## Auto Layout
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Auto%20Layout.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/Auto%20Layout.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script performs automatic layout for the selected top-level grouping objects. It is powered by <a href='https://github.com/kieler/elkjs'>elkjs</a> and needs to be connected to the Internet.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-auto-layout.png'></td></tr></table>
## Box Each Selected Groups
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Box%20Each%20Selected%20Groups.md
@@ -160,6 +187,12 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/1-2-3'>@1-2-3</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Darken%20background%20color.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script darkens the background color of the selected element by 2% at a time. You can use this script several times until you are satisfied. It is recommended to set a shortcut key for this script so that you can quickly try to DARKEN and LIGHTEN the color effect. In contrast to the `Modify background color opacity` script, the advantage is that the background color of the element is not affected by the canvas color, and the color value does not appear in a strange rgba() form.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/darken-lighten-background-color.png'></td></tr></table>
## Deconstruct selected elements into new drawing
```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><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-deconstruct.jpg'></td></tr></table>
## Elbow connectors
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Elbow%20connectors.md
@@ -220,12 +253,30 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/1-2-3'>@1-2-3</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Fixed%20vertical%20distance.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script arranges the selected elements vertically with a fixed spacing. When we create an architecture diagram or mind map, we often need to arrange a large number of elements in a fixed spacing. `Fixed spacing` and `Fixed vertical Distance` scripts can save us a lot of time.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-fixed-vertical-distance.png'></td></tr></table>
## Folder Note Core - Make Current Drawing a Folder
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Folder%20Note%20Core%20-%20Make%20Current%20Drawing%20a%20Folder.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/Folder%20Note%20Core%20-%20Make%20Current%20Drawing%20a%20Folder.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script adds the `Folder Note Core: Make current document folder note` function to Excalidraw drawings. Running this script will convert the active Excalidraw drawing into a folder note. If you already have embedded images in your drawing, those attachments will not be moved when the folder note is created. You need to take care of those attachments separately, or convert the drawing to a folder note prior to adding the attachments. The script requires the <a href="https://github.com/aidenlx/folder-note-core" target="_blank">Folder Note Core</a> plugin.</td></tr></table>
## Grid selected images
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Grid%20Selected%20Images.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/7flash'>@7flash</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/Grid%20Selected%20Images.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script arranges selected images into compact grid view, removing gaps in-between, resizing when necessary and breaking into multiple rows/columns.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-grid-selected-images.png'></td></tr></table>
## Hardware Eraser Support
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Hardware%20Eraser%20Support.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/threethan'>@threethan</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/Hardware%20Eraser%20Support.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Allows you to use inversion, aka hardware eraser, on supported pens.</td></tr></table>
## Invert colors
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Invert%20colors.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/Invert%20colors.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script inverts the colors on the canvas including the color palette in Element Properties.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-invert-colors.jpg'></td></tr></table>
## Lighten background color
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Lighten%20background%20color.md
@@ -238,6 +289,12 @@ 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/xllowl'>@xllowl</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/Mindmap%20connector.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script creates mindmap like lines (only right side and down available currently) for selected elements. The line will start according to the creation time of the elements. So you should create the header element first.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/mindmap%20connector.png'></td></tr></table>
## Mindmap format
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20format.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/pandoralink'>@pandoralink</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/Mindmap%20format.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Automatically formats a mindmap from left to right based on the creation sequence of arrows.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-mindmap-format-1.png'><br>A mindmap is actually a tree, so you must have a <b>root node</b>. The script will determine <b>the leftmost element</b> of the selected element as the root element (the node must be a rectangle, diamond, ellipse, text, image, but it can't be an arrow, line, freedraw, or <b>group</b>)<br>The element connecting node and node must be an <b>arrow</b> and have the correct direction, e.g. <b>parent node -> child node</b>.<br>The order of nodes in the Y axis or vertical direction is determined by <b>the creation time</b> of the arrow connecting it.<br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-mindmap-format-2.png"><br>If you want to readjust the order, you can <b>delete arrows and reconnect them</b>.<br>The script provides options to adjust the style of the mindmap. Options are at the bottom of excalidraw plugin options (Settings -> Community plugins -> Excalidraw -> drag to bottom).<br>Since the start bingding and end bingding of the arrows are easily disconnected from the node, if there are unformatted parts, please <b>check the connection</b> and use the script to <b>reformat</b>.</td></tr></table>
## Modify background color opacity
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Modify%20background%20color%20opacity.md
@@ -250,12 +307,6 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/1-2-3'>@1-2-3</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Normalize%20Selected%20Arrows.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will reset the start and end positions of the selected arrows. The arrow will point to the center of the connected box and will have a gap of 8px from the box.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-normalize-selected-arrows.png'></td></tr></table>
## OCR - Optical Character Recognition
```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 exctract 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>
## Organic Line
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Organic%20Line.md
@@ -340,6 +391,12 @@ 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/Set%20Text%20Alignment.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Sets text alignment of text block (cetner, right, left). Useful if you want to set a keyboard shortcut for selecting text alignment.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-align.jpg'></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/HhRHFhWkmCk" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></td></tr></table>
## Split text by lines
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Split%20text%20by%20lines.md
@@ -352,14 +409,20 @@ 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/Text%20Arch.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Fit a text to the arch of a circle. The script will prompt you for the radius of the circle and then split your text to individual letters and place each letter to the arch defined by the radius. Setting a lower radius value will increase the arching of the text. Note that the arched-text will no longer be editable as a text element and it will no longer function as a markdown link. Emojis are currently not supported.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/text-arch.jpg'></td></tr></table>
## Transfer TextElements to Excalidraw markdown metadata
## Text to Sticky Notes
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Transfer%20TextElements%20to%20Excalidraw%20markdown%20metadata.md
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20to%20Sticky%20Notes.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/Transfer%20TextElements%20to%20Excalidraw%20markdown%20metadata.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script will delete the selected text elements from the canvas and will copy the text from these text elements into the Excalidraw markdown file as metadata. This means, that the text will no longer be visible in the drawing, however you will be able to search for the text in Obsidian and find the drawing containing this image.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-to-metadata.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/Text%20to%20Sticky%20Notes.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Converts selected plain text element to sticky notes by dividing the text element line by line into separate sticky notes. The color of the stikcy note as well as the arrangement of the grid can be configured in plugin settings.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-sticky-note-matrix.jpg'></td></tr></table>
## Uniform Size
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Uniform%20size.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/Uniform%20size.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data"><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-uniform-size.jpg"><br>The script will standardize the sizes of rectangles, diamonds and ellipses adjusting all the elements to match the largest width and height within the group.</td></tr></table>
## Zoom to Fit Selected Elements
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Zoom%20to%20Fit%20Selected%20Elements.md
```
<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/Zoom%20to%20Fit%20Selected%20Elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Similar to Excalidraw standard <kbd>SHIFT+2</kbd> feature: Zoom to fit selected elements, but with the ability to zoom to 1000%. Inspiration: [#272](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/272)</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/Zoom%20to%20Fit%20Selected%20Elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Similar to Excalidraw standard <kbd>SHIFT+2</kbd> feature: Zoom to fit selected elements, but with the ability to zoom to 1000%. Inspiration: [#272](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/272)</td></tr></table>

View File

@@ -0,0 +1,17 @@
{
constantPressure: true,
options: {
smoothing: 0.4,
thinning: -0.5,
streamline: 0.4,
easing: "linear",
start: {
taper: 5,
cap: false,
},
end: {
taper: 5,
cap: false,
},
}
}

View File

@@ -0,0 +1,16 @@
{
options: {
smoothing: 0.22,
thinning: 0.8,
streamline: 0.22,
easing: "easeInQuad",
start: {
taper: true,
cap: true,
},
end: {
taper: 1,
cap: true,
},
}
}

View File

@@ -0,0 +1,16 @@
{
constantPressure: true,
options: {
thinning: 4,
smoothing: 0.5,
streamline: 0.5,
start: {
taper: true,
easing: "linear",
},
end: {
taper: true,
easing: "linear",
}
}
}

View File

@@ -0,0 +1,16 @@
{
constantPressure: true,
options: {
thinning: 4,
smoothing: 0.5,
streamline: 0.5,
start: {
taper: 0,
cap: true
},
end: {
taper: true,
easing: "linear",
}
}
}

View File

@@ -0,0 +1,18 @@
{
hasOutline: true,
outlineWidth: 4,
options: {
thinning: 3,
smoothing: 0.5,
streamline: 0.5,
easing: "easeInOutElastic",
start: {
taper: 50,
cap: true
},
end: {
taper: 50,
cap: true
}
}
}

View File

@@ -0,0 +1,19 @@
{
constantPressure: true,
hasOutline: true,
outlineWidth: 4,
options: {
thinning: 1,
smoothing: 0.5,
streamline: 0.5,
easing: "linear",
start: {
taper: 0,
cap: true
},
end: {
taper: 0,
cap: true
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 322 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

After

Width:  |  Height:  |  Size: 224 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

10
manifest-beta.json Normal file
View File

@@ -0,0 +1,10 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "1.8.15-beta",
"minAppVersion": "0.16.0",
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
"author": "Zsolt Viczian",
"authorUrl": "https://zsolt.blog",
"isDesktopOnly": false
}

View File

@@ -1,10 +1,11 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "1.7.26",
"minAppVersion": "0.15.6",
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
"author": "Zsolt Viczian",
"authorUrl": "https://zsolt.blog",
"isDesktopOnly": false
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "1.9.0",
"minAppVersion": "1.1.6",
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
"author": "Zsolt Viczian",
"authorUrl": "https://zsolt.blog",
"fundingUrl": "https://ko-fi.com/zsolt",
"isDesktopOnly": false
}

View File

@@ -1,6 +1,6 @@
{
"name": "obsidian-excalidraw-plugin",
"version": "1.7.26",
"version": "1.8.10",
"description": "This is an Obsidian.md plugin that lets you view and edit Excalidraw drawings",
"main": "lib/index.js",
"types": "lib/index.d.ts",
@@ -18,52 +18,52 @@
"license": "MIT",
"dependencies": {
"@types/lz-string": "^1.3.34",
"@zsviczian/excalidraw": "0.13.0-obsidian",
"clsx": "^1.1.1",
"@zsviczian/excalidraw": "0.15.2-obsidian-1",
"chroma-js": "^2.4.2",
"clsx": "^1.2.1",
"colormaster": "^1.2.1",
"gl-matrix": "^3.4.3",
"lz-string": "^1.4.4",
"monkey-around": "^2.3.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "^5.0.1",
"roughjs": "^4.5.2",
"colormaster": "1.2.1",
"chroma-js": "^2.4.2",
"gl-matrix": "^3.4.3"
"html2canvas": "^1.4.1",
"@popperjs/core": "^2.11.6",
"nanoid": "^4.0.0"
},
"devDependencies": {
"@babel/core": "^7.16.12",
"@babel/preset-env": "^7.16.11",
"@babel/preset-react": "^7.16.7",
"@excalidraw/eslint-config": "1.0.0",
"@excalidraw/prettier-config": "1.0.2",
"@popperjs/core": "^2.11.5",
"@rollup/plugin-babel": "^5.3.0",
"@rollup/plugin-commonjs": "^21.0.1",
"@rollup/plugin-node-resolve": "^13.1.3",
"@rollup/plugin-replace": "^3.0.1",
"@rollup/plugin-typescript": "^8.3.0",
"@types/js-beautify": "^1.13.3",
"@babel/core": "^7.20.12",
"@babel/preset-env": "^7.20.2",
"@babel/preset-react": "^7.18.6",
"@excalidraw/eslint-config": "^1.0.3",
"@excalidraw/prettier-config": "^1.0.2",
"@rollup/plugin-babel": "^6.0.3",
"@rollup/plugin-commonjs": "^24.0.0",
"@rollup/plugin-node-resolve": "^15.0.1",
"@rollup/plugin-replace": "^5.0.2",
"@rollup/plugin-typescript": "^11.0.0",
"@types/chroma-js": "^2.1.4",
"@types/node": "^15.12.4",
"@types/react-dom": "^17.0.2",
"@types/js-beautify": "^1.13.3",
"@types/node": "^18.11.18",
"@types/react-dom": "^18.0.10",
"@zerollup/ts-transform-paths": "^1.7.18",
"cross-env": "^7.0.3",
"eslint-config-prettier": "8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"html2canvas": "^1.4.0",
"nanoid": "^4.0.0",
"obsidian": "^0.16.3",
"prettier": "^2.5.1",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-prettier": "^4.2.1",
"obsidian": "^1.1.1",
"prettier": "^2.8.2",
"rollup": "^2.70.1",
"rollup-plugin-copy": "^3.4.0",
"rollup-plugin-postprocess": "github:brettz9/rollup-plugin-postprocess#update",
"rollup-plugin-terser": "^7.0.2",
"rollup-plugin-typescript2": "^0.31.2",
"rollup-plugin-visualizer": "^5.6.0",
"rollup-plugin-typescript2": "^0.34.1",
"rollup-plugin-visualizer": "^5.9.0",
"rollup-plugin-web-worker-loader": "^1.6.1",
"tslib": "^2.3.1",
"ttypescript": "^1.5.13",
"typescript": "^4.5.5"
"tslib": "^2.4.1",
"ttypescript": "^1.5.15",
"typescript": "^4.9.4"
},
"resolutions": {
"@typescript-eslint/typescript-estree": "5.3.0"

View File

@@ -1,3 +1,6 @@
//https://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
//https://img.youtube.com/vi/uZz5MgzWXiM/maxresdefault.jpg
import { FileId } from "@zsviczian/excalidraw/types/element/types";
import { BinaryFileData, DataURL } from "@zsviczian/excalidraw/types/types";
import { App, MarkdownRenderer, Notice, TFile } from "obsidian";
@@ -19,6 +22,7 @@ import { ExportSettings } from "./ExcalidrawView";
import { t } from "./lang/helpers";
import { tex2dataURL } from "./LaTeX";
import ExcalidrawPlugin from "./main";
import { blobToBase64, getDataURLFromURL, getMimeType, getPDFDoc, getURLImageExtension } from "./utils/FileUtils";
import {
errorlog,
getDataURL,
@@ -33,18 +37,33 @@ import {
LinkParts,
svgToBase64,
} from "./utils/Utils";
import { ValueOf } from "./types";
const THEME_FILTER = "invert(100%) hue-rotate(180deg) saturate(1.25)";
export declare type MimeType =
| "image/svg+xml"
| "image/png"
| "image/jpeg"
| "image/gif"
| "image/webp"
| "image/bmp"
| "image/x-icon"
| "application/octet-stream";
//An ugly workaround for the following situation.
//File A is a markdown file that has an embedded Excalidraw file B
//Later file A is embedded into file B as a Markdown embed
//Because MarkdownRenderer.renderMarkdown does not take a depth parameter as input
//EmbeddedFileLoader cannot track the recursion depth (as it can when Excalidraw drawings are embedded)
//For this reason, the markdown TFile is added to the Watchdog when rendering starts
//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",
gif: "image/gif",
webp: "image/webp",
bmp: "image/bmp",
ico: "image/x-icon",
avif: "image/avif",
jfif: "image/jfif",
} as const;
export declare type MimeType = ValueOf<typeof IMAGE_MIME_TYPES> | "application/octet-stream";
export type FileData = BinaryFileData & {
size: Size;
hasSVGwithBitmap: boolean;
@@ -56,6 +75,59 @@ export type Size = {
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
* @param svg: SVGSVGElement
* @param colorMap: {[color: string]: string;} | null
* @returns svg with colors replaced
*/
const replaceSVGColors = (svg: SVGSVGElement | string, colorMap: ColorMap | null): SVGSVGElement | string => {
if(!colorMap) {
return svg;
}
if(typeof svg === 'string') {
// Replace colors in the SVG string
for (const [oldColor, newColor] of Object.entries(colorMap)) {
const fillRegex = new RegExp(`fill="${oldColor}"`, 'g');
svg = svg.replaceAll(fillRegex, `fill="${newColor}"`);
const strokeRegex = new RegExp(`stroke="${oldColor}"`, 'g');
svg = svg.replaceAll(strokeRegex, `stroke="${newColor}"`);
}
return svg;
}
// Modify the fill and stroke attributes of child nodes
const childNodes = (node: ChildNode) => {
if (node instanceof SVGElement) {
const oldFill = node.getAttribute('fill');
const oldStroke = node.getAttribute('stroke');
if (oldFill && colorMap[oldFill]) {
node.setAttribute('fill', colorMap[oldFill]);
}
if (oldStroke && colorMap[oldStroke]) {
node.setAttribute('stroke', colorMap[oldStroke]);
}
}
for(const child of node.childNodes) {
childNodes(child);
}
}
for (const child of svg.childNodes) {
childNodes(child);
}
return svg;
}
export class EmbeddedFile {
public file: TFile = null;
public isSVGwithBitmap: boolean = false;
@@ -68,22 +140,32 @@ export class EmbeddedFile {
public linkParts: LinkParts;
private hostPath: string;
public attemptCounter: number = 0;
/*public isHyperlink: boolean = false;*/
public isHyperlink: boolean = false;
public hyperlink:DataURL;
public colorMap: ColorMap | null = null;
constructor(plugin: ExcalidrawPlugin, hostPath: string, imgPath: string) {
constructor(plugin: ExcalidrawPlugin, hostPath: string, imgPath: string, colorMapJSON?: string) {
this.plugin = plugin;
this.resetImage(hostPath, imgPath);
if(this.file && (this.plugin.ea.isExcalidrawFile(this.file) || this.file.extension.toLowerCase() === "svg")) {
try {
this.colorMap = colorMapJSON ? JSON.parse(colorMapJSON) : null;
} catch (error) {
this.colorMap = null;
}
}
}
public resetImage(hostPath: string, imgPath: string) {
/*if(imgPath.startsWith("https://") || imgPath.startsWith("http://")) {
this.img=imgPath;
this.imgInverted=imgPath;
this.isHyperlink = true;
return;
}*/
this.imgInverted = this.img = "";
this.mtime = 0;
if(imgPath.startsWith("https://") || imgPath.startsWith("http://")){
this.isHyperlink = true;
this.hyperlink = imgPath as DataURL;
return;
};
this.linkParts = getLinkParts(imgPath);
this.hostPath = hostPath;
if (!this.linkParts.path) {
@@ -111,6 +193,9 @@ export class EmbeddedFile {
}
private fileChanged(): boolean {
if(this.isHyperlink) {
return false;
}
if (!this.file) {
this.file = app.metadataCache.getFirstLinkpathDest(
this.linkParts.path,
@@ -131,13 +216,13 @@ export class EmbeddedFile {
isDark: boolean,
isSVGwithBitmap: boolean,
) {
if (!this.file) {
if (!this.file && !this.isHyperlink) {
return;
}
if (this.fileChanged()) {
this.imgInverted = this.img = "";
}
this.mtime = this.file.stat.mtime;
this.mtime = this.isHyperlink ? 0 : this.file.stat.mtime;
this.size = size;
this.mimeType = mimeType;
switch (isDark && isSVGwithBitmap) {
@@ -152,18 +237,20 @@ export class EmbeddedFile {
}
public isLoaded(isDark: boolean): boolean {
if (!this.file) {
this.file = app.metadataCache.getFirstLinkpathDest(
this.linkParts.path,
this.hostPath,
); // maybe the file has synchronized in the mean time
if(!this.file) {
this.attemptCounter++;
return true;
if(!this.isHyperlink) {
if (!this.file) {
this.file = app.metadataCache.getFirstLinkpathDest(
this.linkParts.path,
this.hostPath,
); // maybe the file has synchronized in the mean time
if(!this.file) {
this.attemptCounter++;
return true;
}
}
if (this.fileChanged()) {
return false;
}
}
if (this.fileChanged()) {
return false;
}
if (this.isSVGwithBitmap && isDark) {
return this.imgInverted !== "";
@@ -172,10 +259,7 @@ export class EmbeddedFile {
}
public getImage(isDark: boolean) {
/*if(this.isHyperlink) {
return this.img;
}*/
if (!this.file) {
if (!this.file && !this.isHyperlink) {
return "";
}
if (isDark && this.isSVGwithBitmap) {
@@ -189,11 +273,12 @@ export class EmbeddedFile {
* @returns true if image should scale such as the updated images has the same area as the previous images, false if the image should be displayed at 100%
*/
public shouldScale() {
return !Boolean(this.linkParts && this.linkParts.original && this.linkParts.original.endsWith("|100%"));
return this.isHyperlink || !Boolean(this.linkParts && this.linkParts.original && this.linkParts.original.endsWith("|100%"));
}
}
export class EmbeddedFilesLoader {
private pdfDocsMap: Map<string, any> = new Map();
private plugin: ExcalidrawPlugin;
private isDark: boolean;
public terminate = false;
@@ -205,6 +290,11 @@ export class EmbeddedFilesLoader {
this.uid = nanoid();
}
public emptyPDFDocsMap() {
this.pdfDocsMap.forEach((pdfDoc) => pdfDoc.destroy());
this.pdfDocsMap.clear();
}
public async getObsidianImage(inFile: TFile | EmbeddedFile, depth: number): Promise<{
mimeType: MimeType;
fileId: FileId;
@@ -212,26 +302,53 @@ export class EmbeddedFilesLoader {
created: number;
hasSVGwithBitmap: boolean;
size: { height: number; width: number };
}> {
const result = await this._getObsidianImage(inFile, depth);
this.emptyPDFDocsMap();
return result;
}
private async _getObsidianImage(inFile: TFile | EmbeddedFile, depth: number): Promise<{
mimeType: MimeType;
fileId: FileId;
dataURL: DataURL;
created: number;
hasSVGwithBitmap: boolean;
size: { height: number; width: number };
}> {
if (!this.plugin || !inFile) {
return null;
}
const isHyperlink = inFile instanceof EmbeddedFile ? inFile.isHyperlink : false;
const hyperlink = inFile instanceof EmbeddedFile ? inFile.hyperlink : "";
const file: TFile = inFile instanceof EmbeddedFile ? inFile.file : inFile;
if(file && markdownRendererRecursionWatcthdog.has(file)) {
new Notice(`Loading of ${file.path}. Please check if there is an inifinite loop of one file embedded in the other.`);
return null;
}
const linkParts =
inFile instanceof EmbeddedFile
? inFile.linkParts
: {
original: file.path,
path: file.path,
isBlockRef: false,
ref: null,
width: this.plugin.settings.mdSVGwidth,
height: this.plugin.settings.mdSVGmaxHeight,
};
isHyperlink
? null
: inFile instanceof EmbeddedFile
? inFile.linkParts
: {
original: file.path,
path: file.path,
isBlockRef: false,
ref: null,
width: this.plugin.settings.mdSVGwidth,
height: this.plugin.settings.mdSVGmaxHeight,
page: null,
};
let hasSVGwithBitmap = false;
const isExcalidrawFile = this.plugin.isExcalidrawFile(file);
const isExcalidrawFile = !isHyperlink && this.plugin.isExcalidrawFile(file);
const isPDF = !isHyperlink && file.extension.toLowerCase() === "pdf";
if (
!isHyperlink && !isPDF &&
!(
IMAGE_TYPES.contains(file.extension) ||
isExcalidrawFile ||
@@ -240,7 +357,9 @@ export class EmbeddedFilesLoader {
) {
return null;
}
const ab = await app.vault.readBinary(file);
const ab = isHyperlink || isPDF
? null
: await app.vault.readBinary(file);
const getExcalidrawSVG = async (isDark: boolean) => {
//debug({where:"EmbeddedFileLoader.getExcalidrawSVG",uid:this.uid,file:file.name});
@@ -253,19 +372,23 @@ export class EmbeddedFilesLoader {
: false,
withTheme: !!forceTheme,
};
const svg = await createSVG(
file.path,
true,
exportSettings,
this,
forceTheme,
null,
null,
[],
this.plugin,
depth+1,
getExportPadding(this.plugin, file),
);
const svg = replaceSVGColors(
await createSVG(
file.path,
true,
exportSettings,
this,
forceTheme,
null,
null,
[],
this.plugin,
depth+1,
getExportPadding(this.plugin, file),
),
inFile instanceof EmbeddedFile ? inFile.colorMap : null
) as SVGSVGElement;
//https://stackoverflow.com/questions/51154171/remove-css-filter-on-child-elements
const imageList = svg.querySelectorAll(
"image:not([href^='data:image/svg'])",
@@ -291,65 +414,63 @@ export class EmbeddedFilesLoader {
const excalidrawSVG = isExcalidrawFile
? await getExcalidrawSVG(this.isDark)
: null;
let mimeType: MimeType = "image/svg+xml";
if (!isExcalidrawFile) {
switch (file.extension) {
case "png":
mimeType = "image/png";
break;
case "jpeg":
mimeType = "image/jpeg";
break;
case "jpg":
mimeType = "image/jpeg";
break;
case "gif":
mimeType = "image/gif";
break;
case "webp":
mimeType = "image/webp";
break;
case "bmp":
mimeType = "image/bmp";
break;
case "ico":
mimeType = "image/x-icon"
break;
case "svg":
case "md":
mimeType = "image/svg+xml";
break;
default:
mimeType = "application/octet-stream";
}
}
let dataURL =
excalidrawSVG ??
(file.extension === "svg"
? await getSVGData(app, file)
: file.extension === "md"
? null
: await getDataURL(ab, mimeType));
if(!dataURL) {
const result = await this.convertMarkdownToSVG(this.plugin, file, linkParts);
const [pdfDataURL, pdfSize] = isPDF
? await this.pdfToDataURL(file,linkParts)
: [null, null];
let mimeType: MimeType = isPDF
? "image/png"
: "image/svg+xml";
const extension = isHyperlink
? getURLImageExtension(hyperlink)
: file.extension;
if (!isExcalidrawFile && !isPDF) {
mimeType = getMimeType(extension);
}
let dataURL =
isHyperlink
? (
inFile instanceof EmbeddedFile
? await getDataURLFromURL(inFile.hyperlink, mimeType)
: null
)
: excalidrawSVG ?? pdfDataURL ??
(file.extension === "svg"
? await getSVGData(app, file, inFile instanceof EmbeddedFile ? inFile.colorMap : null)
: file.extension === "md"
? null
: await getDataURL(ab, mimeType));
if(!isHyperlink && !dataURL) {
markdownRendererRecursionWatcthdog.add(file);
const result = await this.convertMarkdownToSVG(this.plugin, file, linkParts, depth);
markdownRendererRecursionWatcthdog.delete(file);
dataURL = result.dataURL;
hasSVGwithBitmap = result.hasSVGwithBitmap;
}
const size = await getImageSize(dataURL);
return {
mimeType,
fileId: await generateIdFromFile(ab),
dataURL,
created: file.stat.mtime,
hasSVGwithBitmap,
size,
};
try{
const size = isPDF ? pdfSize : await getImageSize(dataURL);
return {
mimeType,
fileId: await generateIdFromFile(
isHyperlink || isPDF ? (new TextEncoder()).encode(dataURL as string) : ab
),
dataURL,
created: isHyperlink ? 0 : file.stat.mtime,
hasSVGwithBitmap,
size,
};
} catch(e) {
return null;
}
}
public async loadSceneFiles(
excalidrawData: ExcalidrawData,
addFiles: Function,
addFiles: (files: FileData[], isDark: boolean, final?: boolean) => void,
depth:number
) {
if(depth > 4) {
@@ -367,9 +488,9 @@ export class EmbeddedFilesLoader {
const embeddedFile: EmbeddedFile = entry.value[1];
if (!embeddedFile.isLoaded(this.isDark)) {
//debug({where:"EmbeddedFileLoader.loadSceneFiles",uid:this.uid,status:"embedded Files are not loaded"});
const data = await this.getObsidianImage(embeddedFile, depth);
const data = await this._getObsidianImage(embeddedFile, depth);
if (data) {
files.push({
const fileData = {
mimeType: data.mimeType,
id: entry.value[0],
dataURL: data.dataURL,
@@ -377,10 +498,17 @@ export class EmbeddedFilesLoader {
size: data.size,
hasSVGwithBitmap: data.hasSVGwithBitmap,
shouldScale: embeddedFile.shouldScale()
});
};
try {
addFiles([fileData], this.isDark, false);
}
catch(e) {
errorlog({ where: "EmbeddedFileLoader.loadSceneFiles", error: e });
}
//files.push(fileData);
}
} else if (embeddedFile.isSVGwithBitmap) {
files.push({
const fileData = {
mimeType: embeddedFile.mimeType,
id: entry.value[0],
dataURL: embeddedFile.getImage(this.isDark) as DataURL,
@@ -388,7 +516,14 @@ export class EmbeddedFilesLoader {
size: embeddedFile.size,
hasSVGwithBitmap: embeddedFile.isSVGwithBitmap,
shouldScale: embeddedFile.shouldScale()
});
};
//files.push(fileData);
try {
addFiles([fileData], this.isDark, false);
}
catch(e) {
errorlog({ where: "EmbeddedFileLoader.loadSceneFiles", error: e });
}
}
}
@@ -399,7 +534,7 @@ export class EmbeddedFilesLoader {
const latex = equation.value[1].latex;
const data = await tex2dataURL(latex, this.plugin);
if (data) {
files.push({
const fileData = {
mimeType: data.mimeType,
id: equation.value[0],
dataURL: data.dataURL,
@@ -407,27 +542,83 @@ export class EmbeddedFilesLoader {
size: data.size,
hasSVGwithBitmap: false,
shouldScale: true
});
};
files.push(fileData);
}
}
}
this.emptyPDFDocsMap();
if (this.terminate) {
return;
}
//debug({where:"EmbeddedFileLoader.loadSceneFiles",uid:this.uid,status:"add Files"});
try {
//in try block because by the time files are loaded the user may have closed the view
addFiles(files, this.isDark);
addFiles(files, this.isDark, true);
} catch (e) {
errorlog({ where: "EmbeddedFileLoader.loadSceneFiles", error: e });
}
}
private async pdfToDataURL(
file: TFile,
linkParts: LinkParts,
): Promise<[DataURL,{width:number, height:number}]> {
try {
let width = 0, height = 0;
const pdfDoc = this.pdfDocsMap.get(file.path) ?? await getPDFDoc(file);
if(!this.pdfDocsMap.has(file.path)) {
this.pdfDocsMap.set(file.path, pdfDoc);
}
const pageNum = isNaN(linkParts.page) ? 1 : (linkParts.page??1);
const scale = this.plugin.settings.pdfScale;
// Render the page
const renderPage = async (num:number) => {
const canvas = createEl("canvas");
const ctx = canvas.getContext('2d');
// Get page
const page = await pdfDoc.getPage(num);
// Set scale
const viewport = page.getViewport({ scale });
height = canvas.height = viewport.height;
width = canvas.width = viewport.width;
const renderCtx = {
canvasContext: ctx,
background: 'rgba(0,0,0,0)',
viewport
};
await page.render(renderCtx).promise;
return canvas;
};
const canvas = await renderPage(pageNum);
if(canvas) {
const result: [DataURL,{width:number, height:number}] = [`data:image/png;base64,${await new Promise((resolve, reject) => {
canvas.toBlob(async (blob) => {
const dataURL = await blobToBase64(blob);
resolve(dataURL);
});
})}` as DataURL, {width, height}];
canvas.width = 0; //free memory iOS bug
canvas.height = 0;
return result;
}
} catch(e) {
console.log(e);
return [null,null];
}
}
private async convertMarkdownToSVG(
plugin: ExcalidrawPlugin,
file: TFile,
linkParts: LinkParts,
depth: number,
): Promise<{dataURL: DataURL, hasSVGwithBitmap:boolean}> {
//1.
//get the markdown text
@@ -554,7 +745,7 @@ export class EmbeddedFilesLoader {
const ef = new EmbeddedFile(plugin,file.path,src);
//const f = app.metadataCache.getFirstLinkpathDest(src.split("#")[0],file.path);
if(!ef.file) continue;
const embeddedFile = await this.getObsidianImage(ef,1);
const embeddedFile = await this._getObsidianImage(ef,1);
const img = createEl("img");
if(width) img.setAttribute("width", width);
if(height) img.setAttribute("height", height);
@@ -650,12 +841,12 @@ export class EmbeddedFilesLoader {
};
}
const getSVGData = async (app: App, file: TFile): Promise<DataURL> => {
const svg = await app.vault.read(file);
const getSVGData = async (app: App, file: TFile, colorMap: ColorMap | null): Promise<DataURL> => {
const svg = replaceSVGColors(await app.vault.read(file), colorMap) as string;
return svgToBase64(svg) as DataURL;
};
const generateIdFromFile = async (file: ArrayBuffer): Promise<FileId> => {
export const generateIdFromFile = async (file: ArrayBuffer): Promise<FileId> => {
let id: FileId;
try {
const hashBuffer = await window.crypto.subtle.digest("SHA-1", file);

View File

@@ -2,16 +2,19 @@ import ExcalidrawPlugin from "./main";
import {
FillStyle,
StrokeStyle,
StrokeSharpness,
ExcalidrawElement,
ExcalidrawBindableElement,
FileId,
NonDeletedExcalidrawElement,
ExcalidrawImageElement,
ExcalidrawTextElement,
StrokeRoundness,
RoundnessType,
} from "@zsviczian/excalidraw/types/element/types";
import { normalizePath, Notice, TFile, WorkspaceLeaf } from "obsidian";
import * as obsidian_module from "obsidian";
import ExcalidrawView, { ExportSettings, TextMode } from "./ExcalidrawView";
import { ExcalidrawData } from "./ExcalidrawData";
import { ExcalidrawData, getMarkdownDrawingSection } from "./ExcalidrawData";
import {
FRONTMATTER,
nanoid,
@@ -19,6 +22,7 @@ import {
MAX_IMAGE_SIZE,
COLOR_NAMES,
fileid,
GITHUB_RELEASES,
} from "./Constants";
import { getDrawingFilename, } from "./utils/FileUtils";
import {
@@ -32,11 +36,11 @@ import {
isVersionNewerThanOther,
log,
scaleLoadedImage,
wrapText,
wrapTextAtCharLength,
} from "./utils/Utils";
import { getNewOrAdjacentLeaf, isObsidianThemeDark } from "./utils/ObsidianUtils";
import { AppState, Point } from "@zsviczian/excalidraw/types/types";
import { EmbeddedFilesLoader, FileData } from "./EmbeddedFileLoader";
import { AppState, BinaryFileData, DataURL, Point } from "@zsviczian/excalidraw/types/types";
import { EmbeddedFile, EmbeddedFilesLoader, FileData } from "./EmbeddedFileLoader";
import { tex2dataURL } from "./LaTeX";
//import Excalidraw from "@zsviczian/excalidraw";
import { Prompt } from "./dialogs/Prompt";
@@ -59,6 +63,7 @@ import RYBPlugin from "colormaster/plugins/ryb";
import CMYKPlugin from "colormaster/plugins/cmyk";
import { TInput } from "colormaster/types";
import {ConversionResult, svgToExcalidraw} from "./svgToExcalidraw/parser"
import { ROUNDNESS } from "./Constants";
extendPlugins([
HarmonyPlugin,
@@ -84,6 +89,7 @@ const {
getCommonBoundingBox,
getMaximumGroups,
measureText,
getDefaultLineHeight,
//@ts-ignore
} = excalidrawLib;
@@ -96,6 +102,12 @@ declare global {
}
export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
/**
* Utility function that returns the Obsidian Module object.
*/
get obsidian() {
return obsidian_module;
};
plugin: ExcalidrawPlugin;
targetView: ExcalidrawView = null; //the view currently edited
elementsDict: {[key:string]:any}; //contains the ExcalidrawElements currently edited in Automate indexed by el.id
@@ -110,7 +122,8 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
strokeStyle: StrokeStyle; //type StrokeStyle = "solid" | "dashed" | "dotted"
roughness: number;
opacity: number;
strokeSharpness: StrokeSharpness; //type StrokeSharpness = "round" | "sharp"
strokeSharpness?: StrokeRoundness; //defaults to undefined, use strokeRoundess and roundess instead. Only kept for legacy script compatibility type StrokeRoundness = "round" | "sharp"
roundness: null | { type: RoundnessType; value?: number };
fontFamily: number; //1: Virgil, 2:Helvetica, 3:Cascadia, 4:LocalFont
fontSize: number;
textAlign: string; //"left"|"right"|"center"
@@ -123,6 +136,7 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
viewBackgroundColor: string;
gridSize: number;
};
colorPalette: {};
constructor(plugin: ExcalidrawPlugin, view?: ExcalidrawView) {
this.plugin = plugin;
@@ -130,6 +144,19 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
this.targetView = view;
}
/**
*
* @returns the last recorded pointer position on the Excalidraw canvas
*/
public getViewLastPointerPosition(): {x:number, y:number} {
//@ts-ignore
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "getExcalidrawAPI()");
return null;
}
return this.targetView.currentPosition;
}
/**
*
* @returns
@@ -181,10 +208,12 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
setStrokeSharpness(val: number) {
switch (val) {
case 0:
this.style.strokeSharpness = "round";
this.style.roundness = {
type: ROUNDNESS.LEGACY
}
return "round";
default:
this.style.strokeSharpness = "sharp";
this.style.roundness = null; //sharp
return "sharp";
}
};
@@ -301,10 +330,14 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
"excalidraw-url-prefix"?: string;
"excalidraw-export-transparent"?: boolean;
"excalidraw-export-dark"?: boolean;
"excalidraw-export-svgpadding"?: number;
"excalidraw-export-padding"?: number;
"excalidraw-export-pngscale"?: number;
"excalidraw-default-mode"?: "view" | "zen";
"excalidraw-onload-script"?: string;
"excalidraw-linkbutton-opacity"?: number;
"excalidraw-autoexport"?: boolean;
};
plaintext?: string; //text to insert above the `# Text Elements` section
}): Promise<string> {
const template = params?.templatePath
? await getTemplate(
@@ -343,7 +376,7 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
const scene = {
type: "excalidraw",
version: 2,
source: "https://excalidraw.com",
source: GITHUB_RELEASES+PLUGIN_VERSION,
elements,
appState: {
theme: template?.appState?.theme ?? this.canvas.theme,
@@ -374,23 +407,51 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
template?.appState?.currentItemFontSize ?? this.style.fontSize,
currentItemTextAlign:
template?.appState?.currentItemTextAlign ?? this.style.textAlign,
currentItemStrokeSharpness:
template?.appState?.currentItemStrokeSharpness ??
this.style.strokeSharpness,
currentItemStartArrowhead:
template?.appState?.currentItemStartArrowhead ??
this.style.startArrowHead,
currentItemEndArrowhead:
template?.appState?.currentItemEndArrowhead ??
this.style.endArrowHead,
currentItemLinearStrokeSharpness:
template?.appState?.currentItemLinearStrokeSharpness ??
this.style.strokeSharpness,
currentItemRoundness: //type StrokeRoundness = "round" | "sharp"
template?.appState?.currentItemLinearStrokeSharpness ?? //legacy compatibility
template?.appState?.currentItemStrokeSharpness ?? //legacy compatibility
template?.appState?.currentItemRoundness ??
this.style.roundness ? "round":"sharp",
gridSize: template?.appState?.gridSize ?? this.canvas.gridSize,
colorPalette: template?.appState?.colorPalette ?? this.colorPalette,
},
files: template?.files ?? {},
};
const generateMD = ():string => {
let outString = params.plaintext ? params.plaintext + "\n\n" : "";
const textElements = this.getElements().filter(el => el.type === "text") as ExcalidrawTextElement[];
outString += "# Text Elements\n";
textElements.forEach(te=> {
outString += `${te.rawText ?? (te.originalText ?? te.text)} ^${te.id}\n\n`;
});
const elementsWithLinks = this.getElements().filter( el => el.type !== "text" && el.link)
elementsWithLinks.forEach(el=>{
outString += `${el.link} ^${el.id}\n\n`;
})
outString += Object.keys(this.imagesDict).length > 0
? "\n# Embedded files\n"
: "";
Object.keys(this.imagesDict).forEach((key: FileId)=> {
const item = this.imagesDict[key];
if(item.latex) {
outString += `${key}: $$${item.latex}$$\n`;
} else {
outString += `${key}: [[${item.file}]]\n`;
}
})
return outString;
}
return this.plugin.createAndOpenDrawing(
params?.filename
? params.filename + (params.filename.endsWith(".md") ? "": ".excalidraw.md")
@@ -399,8 +460,8 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
params?.foldername ? params.foldername : this.plugin.settings.folder,
this.plugin.settings.compatibilityMode
? JSON.stringify(scene, null, "\t")
: frontmatter +
(await this.plugin.exportSceneToMD(JSON.stringify(scene, null, "\t"))),
: frontmatter + generateMD() +
getMarkdownDrawingSection(JSON.stringify(scene, null, "\t"),this.plugin.settings.compress)
);
};
@@ -454,7 +515,8 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
this.getElements(),
this.plugin,
0,
padding
padding,
this.imagesDict
);
};
@@ -508,7 +570,8 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
this.getElements(),
this.plugin,
0,
padding
padding,
this.imagesDict,
);
};
@@ -519,7 +582,7 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
* @returns
*/
wrapText(text: string, lineLen: number): string {
return wrapText(text, lineLen, this.plugin.settings.forceWrap);
return wrapTextAtCharLength(text, lineLen, this.plugin.settings.forceWrap);
};
private boxedElement(
@@ -545,7 +608,11 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
strokeStyle: this.style.strokeStyle,
roughness: this.style.roughness,
opacity: this.style.opacity,
strokeSharpness: this.style.strokeSharpness,
roundness: this.style.strokeSharpness
? (this.style.strokeSharpness === "round"
? {type: ROUNDNESS.ADAPTIVE_RADIUS}
: null)
: this.style.roundness,
seed: Math.floor(Math.random() * 100000),
version: 1,
versionNonce: Math.floor(Math.random() * 1000000000),
@@ -687,6 +754,26 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
return id;
};
/**
* Refresh the size of a text element to fit its contents
* @param id - the id of the text element
*/
refreshTextElementSize(id: string) {
const element = this.getElement(id);
if (element.type !== "text") {
return;
}
const { w, h, baseline } = _measureText(
element.text,
element.fontSize,
element.fontFamily,
getDefaultLineHeight(element.fontFamily)
);
// @ts-ignore
element.width = w; element.height = h; element.baseline = baseline;
}
/**
*
* @param topX
@@ -705,9 +792,11 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
wrapAt?: number;
width?: number;
height?: number;
textAlign?: string;
textAlign?: "left" | "center" | "right";
box?: boolean | "box" | "blob" | "ellipse" | "diamond";
boxPadding?: number;
boxStrokeColor?: string;
textVerticalAlign?: "top" | "middle" | "bottom";
},
id?: string,
): string {
@@ -718,12 +807,15 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
text,
this.style.fontSize,
this.style.fontFamily,
getDefaultLineHeight(this.style.fontFamily)
);
const width = formatting?.width ? formatting.width : w;
const height = formatting?.height ? formatting.height : h;
let boxId: string = null;
const boxPadding = formatting?.boxPadding ?? 30;
const strokeColor = this.style.strokeColor;
this.style.strokeColor = formatting?.boxStrokeColor ?? strokeColor;
if (formatting?.box) {
switch (formatting.box) {
case "ellipse":
@@ -759,6 +851,7 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
);
}
}
this.style.strokeColor = strokeColor;
const isContainerBound = boxId && formatting.box !== "blob";
this.elementsDict[id] = {
text,
@@ -767,12 +860,13 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
textAlign: formatting?.textAlign
? formatting.textAlign
: this.style.textAlign ?? "left",
verticalAlign: this.style.verticalAlign,
verticalAlign: formatting?.textVerticalAlign ?? this.style.verticalAlign,
baseline,
...this.boxedElement(id, "text", topX, topY, width, height),
containerId: isContainerBound ? boxId : null,
originalText: isContainerBound ? originalText : text,
rawText: isContainerBound ? originalText : text,
lineHeight: getDefaultLineHeight(this.style.fontFamily),
};
if (boxId && formatting?.box === "blob") {
this.addToGroup([id, boxId]);
@@ -893,7 +987,7 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
async addImage(
topX: number,
topY: number,
imageFile: TFile,
imageFile: TFile | string,
scale: boolean = true, //true will scale the image to MAX_IMAGE_SIZE, false will insert image at 100% of its size
): Promise<string> {
const id = nanoid();
@@ -901,17 +995,28 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
this.plugin,
this.canvas.theme === "dark",
);
const image = await loader.getObsidianImage(imageFile,0);
const image = (typeof imageFile === "string")
? await loader.getObsidianImage(new EmbeddedFile(this.plugin, "", imageFile),0)
: await loader.getObsidianImage(imageFile,0);
if (!image) {
return null;
}
const fileId = imageFile.extension === "md" ? fileid() as FileId : image.fileId;
const fileId = typeof imageFile === "string"
? image.fileId
: imageFile.extension === "md" || imageFile.extension.toLowerCase() === "pdf" ? fileid() as FileId : image.fileId;
this.imagesDict[fileId] = {
mimeType: image.mimeType,
id: fileId,
dataURL: image.dataURL,
created: image.created,
file: imageFile.path + (scale ? "":"|100%"),
isHyperlink: typeof imageFile === "string",
hyperlink: typeof imageFile === "string"
? imageFile
: null,
file: typeof imageFile === "string"
? null
: imageFile.path + (scale ? "":"|100%"),
hasSVGwithBitmap: image.hasSVGwithBitmap,
latex: null,
};
@@ -1147,7 +1252,7 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
strokeStyle: "solid",
roughness: 1,
opacity: 100,
strokeSharpness: "sharp",
roundness: null,
fontFamily: 1,
fontSize: 20,
textAlign: "left",
@@ -1172,11 +1277,26 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
};
/**
*
* sets the target view for EA. All the view operations and the access to Excalidraw API will be performend on this view
* if view is null or undefined, the function will first try setView("active"), then setView("first").
* @param view
* @returns
* @returns targetView
*/
setView(view: ExcalidrawView | "first" | "active"): ExcalidrawView {
setView(view?: ExcalidrawView | "first" | "active"): ExcalidrawView {
if(!view) {
const v = app.workspace.getActiveViewOfType(ExcalidrawView);
if (v instanceof ExcalidrawView) {
this.targetView = v;
}
else {
const leaves =
app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW);
if (!leaves || leaves.length == 0) {
return;
}
this.targetView = leaves[0].view as ExcalidrawView;
}
}
if (view == "active") {
const v = app.workspace.getActiveViewOfType(ExcalidrawView);
if (!(v instanceof ExcalidrawView)) {
@@ -1221,11 +1341,11 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
errorMessage("targetView not set", "getViewElements()");
return [];
}
const current = this.targetView?.excalidrawRef?.current;
if (!current) {
const api = this.targetView.excalidrawAPI;
if (!api) {
return [];
}
return current?.getSceneElements();
return api.getSceneElements();
};
/**
@@ -1309,34 +1429,84 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
});
};
setViewModeEnabled(enabled: boolean): void {
//@ts-ignore
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
return;
}
const view = this.targetView as ExcalidrawView;
view.updateScene({appState:{viewModeEnabled: enabled}});
view.toolsPanelRef?.current?.setExcalidrawViewMode(enabled);
}
/**
* This function gives you a more hands on access to Excalidraw.
* @param scene - The scene you want to load to Excalidraw
* @param restore - Use this if the scene includes legacy excalidraw file elements that need to be converted to the latest excalidraw data format (not a typical usecase)
* @returns
*/
viewUpdateScene (
scene: {
elements?: ExcalidrawElement[],
appState?: AppState,
files?: BinaryFileData,
commitToHistory?: boolean,
},
restore: boolean = false,
):void {
//@ts-ignore
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
return;
}
this.targetView.updateScene(scene,restore);
}
/**
* zoom tarteView to fit elements provided as input
* elements === [] will zoom to fit the entire scene
* selectElements toggles whether the elements should be in a selected state at the end of the operation
* @param selectElements
* @param elements
*/
viewZoomToElements(
selectElements: boolean,
elements: ExcalidrawElement[]
):void {
//@ts-ignore
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
return;
}
this.targetView.zoomToElements(selectElements,elements);
}
/**
*
* @param forceViewMode
* @returns
*/
viewToggleFullScreen(forceViewMode: boolean = false): void {
if (app.isMobile) {
errorMessage("mobile not supported", "viewToggleFullScreen()");
return;
}
//@ts-ignore
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
return;
}
const view = this.targetView as ExcalidrawView;
const isFullscreen = view.isFullscreen();
if (forceViewMode) {
const ref = this.getExcalidrawAPI();
this.targetView.updateScene({
view.updateScene({
//elements: ref.getSceneElements(),
appState: {
viewModeEnabled: true,
...ref.appState,
viewModeEnabled: !isFullscreen,
},
commitToHistory: false,
});
this.targetView.toolsPanelRef?.current?.setExcalidrawViewMode(!isFullscreen);
}
const view = this.targetView as ExcalidrawView;
if (view.isFullscreen()) {
if (isFullscreen) {
view.exitFullscreen();
} else {
view.gotoFullscreen();
@@ -1492,6 +1662,30 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
pointerPosition: { x: number; y: number }; //the pointer position on canvas at the time of drop
}) => boolean = null;
/**
* 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>;
/**
* 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>;
/**
* If set, this callback is triggered whenever the active canvas color changes
*/
@@ -1687,6 +1881,7 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
text,
this.style.fontSize,
this.style.fontFamily,
getDefaultLineHeight(this.style.fontFamily),
);
return { width: size.w ?? 0, height: size.h ?? 0 };
};
@@ -1723,7 +1918,7 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
* @returns
*/
verifyMinimumPluginVersion(requiredVersion: string): boolean {
return PLUGIN_VERSION === requiredVersion || isVersionNewerThanOther(PLUGIN_VERSION,requiredVersion);
return verifyMinimumPluginVersion(requiredVersion);
};
/**
@@ -1944,6 +2139,7 @@ export function _measureText(
newText: string,
fontSize: number,
fontFamily: number,
lineHeight: number,
) {
//following odd error with mindmap on iPad while synchornizing with desktop.
if (!fontSize) {
@@ -1951,10 +2147,12 @@ export function _measureText(
}
if (!fontFamily) {
fontFamily = 1;
lineHeight = getDefaultLineHeight(fontFamily);
}
const metrics = measureText(
newText,
`${fontSize.toString()}px ${getFontFamily(fontFamily)}` as any,
lineHeight
);
return { w: metrics.width, h: metrics.height, baseline: metrics.baseline };
}
@@ -2042,6 +2240,14 @@ async function getTemplate(
}
}
if(filenameParts.hasTaskbone) {
groupElements = groupElements.filter( el =>
el.type==="freedraw" ||
( el.type==="image" &&
!plugin.isExcalidrawFile(excalidrawData.getFile(el.fileId)?.file)
));
}
return {
elements: groupElements,
appState: scene.appState,
@@ -2071,6 +2277,7 @@ export async function createPNG(
plugin: ExcalidrawPlugin,
depth: number,
padding?: number,
imagesDict?: any,
) {
if (!loader) {
loader = new EmbeddedFilesLoader(plugin);
@@ -2081,18 +2288,25 @@ export async function createPNG(
: null;
let elements = template?.elements ?? [];
elements = elements.concat(automateElements);
const files = imagesDict ?? {};
if(template?.files) {
Object.values(template.files).forEach((f:any)=>{
files[f.id]=f;
});
}
return await getPNG(
{
type: "excalidraw",
version: 2,
source: "https://excalidraw.com",
source: GITHUB_RELEASES+PLUGIN_VERSION,
elements,
appState: {
theme: forceTheme ?? template?.appState?.theme ?? canvasTheme,
viewBackgroundColor:
template?.appState?.viewBackgroundColor ?? canvasBackgroundColor,
},
files: template?.files ?? {},
files,
},
{
withBackground:
@@ -2116,6 +2330,7 @@ export async function createSVG(
plugin: ExcalidrawPlugin,
depth: number,
padding?: number,
imagesDict?: any,
): Promise<SVGSVGElement> {
if (!loader) {
loader = new EmbeddedFilesLoader(plugin);
@@ -2126,19 +2341,25 @@ export async function createSVG(
let elements = template?.elements ?? [];
elements = elements.concat(automateElements);
padding = padding ?? plugin.settings.exportPaddingSVG;
const files = imagesDict ?? {};
if(template?.files) {
Object.values(template.files).forEach((f:any)=>{
files[f.id]=f;
});
}
const svg = await getSVG(
{
//createAndOpenDrawing
type: "excalidraw",
version: 2,
source: "https://excalidraw.com",
source: GITHUB_RELEASES+PLUGIN_VERSION,
elements,
appState: {
theme: forceTheme ?? template?.appState?.theme ?? canvasTheme,
viewBackgroundColor:
template?.appState?.viewBackgroundColor ?? canvasBackgroundColor,
},
files: template?.files ?? {},
files,
},
{
withBackground:
@@ -2253,7 +2474,7 @@ export const insertLaTeXToView = (view: ExcalidrawView) => {
const prompt = new Prompt(
app,
t("ENTER_LATEX"),
"",
view.plugin.settings.latexBoilerplate,
"\\color{red}\\oint_S {E_n dA = \\frac{1}{{\\varepsilon _0 }}} Q_{inside}",
);
prompt.openAndGetValue(async (formula: string) => {
@@ -2276,6 +2497,8 @@ export const search = async (view: ExcalidrawView) => {
return;
}
let text = await ScriptEngine.inputPrompt(
view,
view.plugin,
view.plugin.app,
"Search for",
"use quotation marks for exact match",
@@ -2335,4 +2558,8 @@ export const cloneElement = (el: ExcalidrawElement):any => {
updated: Date.now(),
versionNonce: Math.floor(Math.random() * 1000000000),
}
}
export const verifyMinimumPluginVersion = (requiredVersion: string): boolean => {
return PLUGIN_VERSION === requiredVersion || isVersionNewerThanOther(PLUGIN_VERSION,requiredVersion);
}

View File

@@ -17,6 +17,7 @@ import {
FRONTMATTER_KEY_LINKBUTTON_OPACITY,
FRONTMATTER_KEY_ONLOAD_SCRIPT,
FRONTMATTER_KEY_AUTOEXPORT,
DEVICE,
} from "./Constants";
import { _measureText } from "./ExcalidrawAutomate";
import ExcalidrawPlugin from "./main";
@@ -24,14 +25,17 @@ import { JSON_parse } from "./Constants";
import { TextMode } from "./ExcalidrawView";
import {
compress,
debug,
decompress,
//getBakPath,
getBinaryFileFromDataURL,
getContainerElement,
getExportTheme,
getLinkParts,
hasExportTheme,
isVersionNewerThanOther,
LinkParts,
wrapText,
wrapTextAtCharLength,
} from "./utils/Utils";
import { getAttachmentsFolderAndFilePath, isObsidianThemeDark } from "./utils/ObsidianUtils";
import {
@@ -39,8 +43,8 @@ import {
ExcalidrawImageElement,
FileId,
} from "@zsviczian/excalidraw/types/element/types";
import { BinaryFiles, SceneData } from "@zsviczian/excalidraw/types/types";
import { EmbeddedFile } from "./EmbeddedFileLoader";
import { BinaryFiles, DataURL, SceneData } from "@zsviczian/excalidraw/types/types";
import { EmbeddedFile, MimeType } from "./EmbeddedFileLoader";
type SceneDataWithFiles = SceneData & { files: BinaryFiles };
@@ -52,6 +56,14 @@ declare module "obsidian" {
}
}
const {
wrapText,
getFontString,
getMaxContainerWidth,
getDefaultLineHeight,
//@ts-ignore
} = excalidrawLib;
export enum AutoexportPreference {
none,
both,
@@ -64,6 +76,15 @@ export const REGEX_LINK = {
//![[link|alias]] [alias](link){num}
// 1 2 3 4 5 67 8 9
EXPR: /(!)?(\[\[([^|\]]+)\|?([^\]]+)?]]|\[([^\]]*)]\(([^)]*)\))(\{(\d+)\})?/g, //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/187
getResList: (text: string): IteratorResult<RegExpMatchArray, any>[] => {
const res = text.matchAll(REGEX_LINK.EXPR);
let parts: IteratorResult<RegExpMatchArray, any>;
const resultList = [];
while(!(parts = res.next()).done) {
resultList.push(parts);
}
return resultList;
},
getRes: (text: string): IterableIterator<RegExpMatchArray> => {
return text.matchAll(REGEX_LINK.EXPR);
},
@@ -210,15 +231,16 @@ const estimateMaxLineLen = (text: string, originalText: string): number => {
return null;
}
for (const line of splitText) {
if (line.length > maxLineLen) {
maxLineLen = line.length;
const l = line.trim();
if (l.length > maxLineLen) {
maxLineLen = l.length;
}
}
return maxLineLen;
};
const wrap = (text: string, lineLen: number) =>
lineLen ? wrapText(text, lineLen, false, 0) : text;
lineLen ? wrapTextAtCharLength(text, lineLen, false, 0) : text;
export class ExcalidrawData {
public textElements: Map<
@@ -228,7 +250,7 @@ export class ExcalidrawData {
public elementLinks: Map<string, string> = null;
public scene: any = null;
public deletedElements: ExcalidrawElement[] = [];
private file: TFile = null;
public file: TFile = null;
private app: App;
private showLinkBrackets: boolean;
private linkPrefix: string;
@@ -257,6 +279,8 @@ export class ExcalidrawData {
return;
}
const saveVersion = this.scene.source.split("https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/")[1]??"1.8.16";
const elements = this.scene.elements;
for (const el of elements) {
if (el.boundElements) {
@@ -347,12 +371,17 @@ export class ExcalidrawData {
} catch (e) {}
});
const ellipseAndRhombusContainerWrapping = !isVersionNewerThanOther(saveVersion,"1.8.16");
//Remove from bound elements references that do not exist in the scene
const containers = elements.filter(
(container: any) =>
container.boundElements && container.boundElements.length > 0,
);
containers.forEach((container: any) => {
if(ellipseAndRhombusContainerWrapping && !container.customData?.legacyTextWrap) {
container.customData = {...container.customData, legacyTextWrap: true};
}
const filteredBoundElements = container.boundElements.filter(
(boundEl: any) => elements.some((el: any) => el.id === boundEl.id),
);
@@ -508,8 +537,9 @@ export class ExcalidrawData {
if(!elementLink.done) {
text = text.replace(/^%%\*\*\*>>>text element-link:\[\[[^<*\]]*]]<<<\*\*\*%%/gm,"");
textEl.link = elementLink.value[1];
}
}
const parseRes = await this.parse(text);
textEl.rawText = text;
this.textElements.set(id, {
raw: text,
parsed: parseRes.parsed,
@@ -531,13 +561,26 @@ export class ExcalidrawData {
data.indexOf("# Embedded files\n") + "# Embedded files\n".length,
);
//Load Embedded files
const REG_FILEID_FILEPATH = /([\w\d]*):\s*\[\[([^\]]*)]]\n/gm;
const REG_FILEID_FILEPATH = /([\w\d]*):\s*\[\[([^\]]*)]]\s?(\{[^}]*})?\n/gm;
res = data.matchAll(REG_FILEID_FILEPATH);
while (!(parts = res.next()).done) {
const embeddedFile = new EmbeddedFile(
this.plugin,
this.file.path,
parts.value[2],
parts.value[3],
);
this.setFile(parts.value[1] as FileId, embeddedFile);
}
//Load links
const REG_LINKID_FILEPATH = /([\w\d]*):\s*(https?:\/\/[^\s]*)\n/gm;
res = data.matchAll(REG_LINKID_FILEPATH);
while (!(parts = res.next()).done) {
const embeddedFile = new EmbeddedFile(
this.plugin,
null,
parts.value[2],
);
this.setFile(parts.value[1] as FileId, embeddedFile);
}
@@ -606,17 +649,19 @@ export class ExcalidrawData {
newText: string,
newOriginalText: string,
forceUpdate: boolean = false,
containerType?: string,
) {
if (forceUpdate || newText != sceneTextElement.text) {
const measure = _measureText(
newText,
sceneTextElement.fontSize,
sceneTextElement.fontFamily,
sceneTextElement.lineHeight??getDefaultLineHeight(sceneTextElement.fontFamily),
);
sceneTextElement.text = newText;
sceneTextElement.originalText = newOriginalText;
if (!sceneTextElement.containerId) {
if (!sceneTextElement.containerId || containerType==="arrow") {
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/376
//I leave the setting of text width to excalidraw, when text is in a container
//because text width is fixed to the container width
@@ -638,21 +683,30 @@ export class ExcalidrawData {
//first get scene text elements
const texts = this.scene.elements?.filter((el: any) => el.type === "text");
for (const te of texts) {
const container = getContainerElement(te,this.scene);
const originalText =
(await this.getText(te.id, false)) ?? te.originalText ?? te.text;
(await this.getText(te.id)) ?? te.originalText ?? te.text;
const wrapAt = this.textElements.get(te.id)?.wrapAt;
this.updateTextElement(
te,
wrap(originalText, wrapAt),
originalText,
forceupdate,
); //(await this.getText(te.id))??te.text serves the case when the whole #Text Elements section is deleted by accident
try { //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1062
this.updateTextElement(
te,
wrapAt ? wrapText(
originalText,
getFontString({fontSize: te.fontSize, fontFamily: te.fontFamily}),
getMaxContainerWidth(container)
) : originalText,
originalText,
forceupdate,
container?.type,
); //(await this.getText(te.id))??te.text serves the case when the whole #Text Elements section is deleted by accident
} catch(e) {
debug({where: "ExcalidrawData.updateSceneTextElements", fn: this.updateSceneTextElements, textElement: te});
}
}
}
private async getText(
id: string,
wrapResult: boolean = true,
): Promise<string> {
const text = this.textElements.get(id);
if (!text) {
@@ -667,13 +721,14 @@ export class ExcalidrawData {
});
}
//console.log("parsed",this.textElements.get(id).parsed);
return wrapResult ? wrap(text.parsed, text.wrapAt) : text.parsed;
return text.parsed;
}
//console.log("raw",this.textElements.get(id).raw);
return text.raw;
}
private findNewElementLinksInScene(): boolean {
let result = false;
const elements = this.scene.elements?.filter((el: any) => {
return (
el.type !== "text" &&
@@ -683,25 +738,27 @@ export class ExcalidrawData {
);
});
if (elements.length === 0) {
return false;
return result;
}
let jsonString = JSON.stringify(this.scene);
let id: string; //will be used to hold the new 8 char long ID for textelements that don't yet appear under # Text Elements
for (const el of elements) {
id = el.id;
//replacing Excalidraw element IDs with my own nanoid, because default IDs may contain
//characters not recognized by Obsidian block references
//also Excalidraw IDs are inconveniently long
if (el.id.length > 8) {
result = true;
id = nanoid();
jsonString = jsonString.replaceAll(el.id, id); //brute force approach to replace all occurances (e.g. links, groups,etc.)
}
this.elementLinks.set(id, el.link);
}
this.scene = JSON.parse(jsonString);
return true;
return result;
}
/**
@@ -794,7 +851,7 @@ export class ExcalidrawData {
if (el.length === 0) {
this.textElements.delete(key); //if no longer in the scene, delete the text element
} else {
const text = await this.getText(key, false);
const text = await this.getText(key);
const raw = this.scene.prevTextMode === TextMode.parsed
? el[0].rawText
: (el[0].originalText ?? el[0].text);
@@ -887,7 +944,7 @@ export class ExcalidrawData {
}
outString +=
text.substring(position, parts.value.index) +
wrapText(
wrapTextAtCharLength(
contents,
REGEX_LINK.getWrapLength(
parts,
@@ -1032,11 +1089,16 @@ export class ExcalidrawData {
for (const key of this.files.keys()) {
const PATHREG = /(^[^#\|]*)/;
const ef = this.files.get(key);
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/829
const path = ef.file
? ef.linkParts.original.replace(PATHREG,app.metadataCache.fileToLinktext(ef.file,this.file.path))
: ef.linkParts.original;
outString += `${key}: [[${path}]]\n`;
if(ef.isHyperlink) {
outString += `${key}: ${ef.hyperlink}\n`;
} else {
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/829
const path = ef.file
? ef.linkParts.original.replace(PATHREG,app.metadataCache.fileToLinktext(ef.file,this.file.path))
: ef.linkParts.original;
const colorMap = ef.colorMap ? " " + JSON.stringify(ef.colorMap) : "";
outString += `${key}: [[${path}]]${colorMap}\n`;
}
}
}
outString += this.equations.size > 0 || this.files.size > 0 ? "\n" : "";
@@ -1058,6 +1120,54 @@ export class ExcalidrawData {
);
}
public async saveDataURLtoVault(dataURL: DataURL, mimeType: MimeType, key: FileId) {
const scene = this.scene as SceneDataWithFiles;
let fname = `Pasted Image ${window
.moment()
.format("YYYYMMDDHHmmss_SSS")}`;
switch (mimeType) {
case "image/png":
fname += ".png";
break;
case "image/jpeg":
fname += ".jpg";
break;
case "image/svg+xml":
fname += ".svg";
break;
case "image/gif":
fname += ".gif";
break;
default:
fname += ".png";
}
const filepath = (
await getAttachmentsFolderAndFilePath(this.app, this.file.path, fname)
).filepath;
const file = await this.app.vault.createBinary(
filepath,
getBinaryFileFromDataURL(dataURL),
);
const embeddedFile = new EmbeddedFile(
this.plugin,
this.file.path,
filepath,
);
embeddedFile.setImage(
dataURL,
mimeType,
{ height: 0, width: 0 },
scene.appState?.theme === "dark",
mimeType === "image/svg+xml", //this treat all SVGs as if they had embedded images REF:addIMAGE
);
this.setFile(key as FileId, embeddedFile);
return file;
}
/**
* deletes fileIds from Excalidraw data for files no longer in the scene
* @returns
@@ -1103,7 +1213,7 @@ export class ExcalidrawData {
const equation = this.getEquation(fileId);
//const equation = this.equations.get(fileId as FileId);
//images should have a single reference, but equations and markdown embeds should have as many as instances of the file in the scene
if(file && file.file && (file.file.extension !== "md" || this.plugin.isExcalidrawFile(file.file))) {
if(file && (file.isHyperlink || (file.file && (file.file.extension !== "md" || this.plugin.isExcalidrawFile(file.file))))) {
return;
}
const newId = fileid();
@@ -1127,47 +1237,11 @@ export class ExcalidrawData {
for (const key of Object.keys(scene.files)) {
if (!(this.hasFile(key as FileId) || this.hasEquation(key as FileId))) {
dirty = true;
let fname = `Pasted Image ${window
.moment()
.format("YYYYMMDDHHmmss_SSS")}`;
const mimeType = scene.files[key].mimeType;
switch (mimeType) {
case "image/png":
fname += ".png";
break;
case "image/jpeg":
fname += ".jpg";
break;
case "image/svg+xml":
fname += ".svg";
break;
case "image/gif":
fname += ".gif";
break;
default:
fname += ".png";
}
const filepath = (
await getAttachmentsFolderAndFilePath(this.app, this.file.path, fname)
).filepath;
const dataURL = scene.files[key].dataURL;
await this.app.vault.createBinary(
filepath,
getBinaryFileFromDataURL(dataURL),
await this.saveDataURLtoVault(
scene.files[key].dataURL,
scene.files[key].mimeType,
key as FileId
);
const embeddedFile = new EmbeddedFile(
this.plugin,
this.file.path,
filepath,
);
embeddedFile.setImage(
dataURL,
mimeType,
{ height: 0, width: 0 },
scene.appState?.theme === "dark",
mimeType === "image/svg+xml", //this treat all SVGs as if they had embedded images REF:addIMAGE
);
this.setFile(key as FileId, embeddedFile);
}
}
@@ -1310,7 +1384,9 @@ export class ExcalidrawData {
public getOpenMode(): { viewModeEnabled: boolean; zenModeEnabled: boolean } {
const fileCache = this.app.metadataCache.getFileCache(this.file);
let mode = this.plugin.settings.defaultMode;
let mode = this.plugin.settings.defaultMode === "view-mobile"
? (DEVICE.isPhone ? "view" : "normal")
: this.plugin.settings.defaultMode;
if (
fileCache?.frontmatter &&
fileCache.frontmatter[FRONTMATTER_KEY_DEFAULT_MODE] != null
@@ -1428,17 +1504,29 @@ export class ExcalidrawData {
}
this.files.set(fileId, data);
if(data.isHyperlink) {
this.plugin.filesMaster.set(fileId, {
isHyperlink: true,
path: data.hyperlink,
blockrefData: null,
hasSVGwithBitmap: data.isSVGwithBitmap
});
return;
}
if (!data.file) {
return;
}
const parts = data.linkParts.original.split("#");
this.plugin.filesMaster.set(fileId, {
path:data.file.path,
isHyperlink: false,
path:data.file.path + (data.shouldScale()?"":"|100%"),
blockrefData: parts.length === 1
? null
: parts[1],
hasSVGwithBitmap: data.isSVGwithBitmap,
colorMapJSON: data.colorMap ? JSON.stringify(data.colorMap) : null,
});
}
@@ -1479,16 +1567,26 @@ export class ExcalidrawData {
}
if (this.plugin.filesMaster.has(fileId)) {
const masterFile = this.plugin.filesMaster.get(fileId);
if (!this.app.vault.getAbstractFileByPath(masterFile.path)) {
if(masterFile.isHyperlink) {
this.files.set(
fileId,
new EmbeddedFile(this.plugin,this.file.path,masterFile.path)
);
return true;
}
const path = masterFile.path.split("|")[0].split("#")[0];
if (!this.app.vault.getAbstractFileByPath(path)) {
this.plugin.filesMaster.delete(fileId);
return true;
} // the file no longer exists
const fixScale = masterFile.path.endsWith("100%");
const embeddedFile = new EmbeddedFile(
this.plugin,
this.file.path,
masterFile.blockrefData
? masterFile.path + "#" + masterFile.blockrefData
: masterFile.path
(masterFile.blockrefData
? path + "#" + masterFile.blockrefData
: path) + (fixScale?"|100%":""),
masterFile.colorMapJSON
);
this.files.set(fileId, embeddedFile);
return true;

File diff suppressed because it is too large Load Diff

View File

@@ -95,6 +95,9 @@ export async function mathjaxSVG(
const eq = plugin.mathjax.tex2svg(tex, { display: true, scale: 4 });
const svg = eq.querySelector("svg");
if (svg) {
if(svg.width.baseVal.valueInSpecifiedUnits < 2) {
svg.width.baseVal.valueAsString = `${(svg.width.baseVal.valueInSpecifiedUnits+1).toFixed(3)}ex`;
}
const dataURL = svgToBase64(svg.outerHTML);
return {
mimeType: "image/svg+xml",

View File

@@ -4,7 +4,7 @@ import {
TFile,
Vault,
} from "obsidian";
import { CTRL_OR_CMD, RERENDER_EVENT } from "./Constants";
import { RERENDER_EVENT } from "./Constants";
import { EmbeddedFilesLoader } from "./EmbeddedFileLoader";
import { createPNG, createSVG } from "./ExcalidrawAutomate";
import { ExportSettings } from "./ExcalidrawView";
@@ -21,6 +21,7 @@ import {
svgToBase64,
} from "./utils/Utils";
import { isObsidianThemeDark } from "./utils/ObsidianUtils";
import { linkClickModifierType } from "./utils/ModifierkeyHelper";
interface imgElementAttributes {
file?: TFile;
@@ -55,6 +56,7 @@ export const initializeMarkdownPostProcessor = (p: ExcalidrawPlugin) => {
*/
const getIMG = async (
imgAttributes: imgElementAttributes,
onCanvas: boolean = false,
): Promise<HTMLElement> => {
let file = imgAttributes.file;
if (!imgAttributes.file) {
@@ -79,13 +81,14 @@ const getIMG = async (
withTheme: forceTheme ? true : plugin.settings.exportWithTheme,
};
const img = createEl("img");
let style = `max-width:${imgAttributes.fwidth}px !important; width:100%;`;
let style = `max-width:${imgAttributes.fwidth}${imgAttributes.fwidth.match(/\d$/) ? "px":""}; `; //width:100%;`; //removed !important https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/886
if (imgAttributes.fheight) {
style += `height:${imgAttributes.fheight}px;`;
}
img.setAttribute("style", style);
if(!onCanvas) img.setAttribute("style", style);
img.addClass(imgAttributes.style);
img.addClass("excalidraw-embedded-img");
const theme =
forceTheme ??
(plugin.settings.previewMatchObsidianTheme
@@ -179,60 +182,97 @@ const getIMG = async (
return null;
}
svg = embedFontsInSVG(svg, plugin);
//need to remove width and height attributes to support area= embeds
svg.removeAttribute("width");
svg.removeAttribute("height");
img.setAttribute("src", svgToBase64(svg.outerHTML));
return img;
};
const createImgElement = async (
attr: imgElementAttributes,
onCanvas: boolean = false,
) :Promise<HTMLElement> => {
const img = await getIMG(attr,onCanvas);
img.setAttribute("fileSource", attr.fname);
if (attr.fwidth) {
img.setAttribute("w", attr.fwidth);
}
if (attr.fheight) {
img.setAttribute("h", attr.fheight);
}
img.setAttribute("draggable","false");
img.setAttribute("onCanvas",onCanvas?"true":"false");
let timer:NodeJS.Timeout;
const clickEvent = (ev:PointerEvent) => {
if (
ev.target instanceof Element &&
ev.target.tagName.toLowerCase() != "img"
) {
return;
}
const src = img.getAttribute("fileSource");
if (src) {
const srcParts = src.match(/([^#]*)(.*)/);
if(!srcParts) return;
plugin.openDrawing(
vault.getAbstractFileByPath(srcParts[1]) as TFile,
linkClickModifierType(ev),
true,
srcParts[2],
);
} //.ctrlKey||ev.metaKey);
};
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1003
let pointerDownEvent:any;
img.addEventListener("pointermove",(ev)=>{
if(!timer) return;
if(Math.abs(ev.screenX-pointerDownEvent.screenX)>10 || Math.abs(ev.screenY-pointerDownEvent.screenY)>10) {
clearTimeout(timer);
timer = null;
}
});
img.addEventListener("pointerdown",(ev)=>{
if(img?.parentElement?.hasClass("canvas-node-content")) return;
timer = setTimeout(()=>clickEvent(ev),500);
pointerDownEvent = ev;
});
img.addEventListener("pointerup",()=>{
if(timer) clearTimeout(timer);
timer = null;
})
img.addEventListener("dblclick",clickEvent);
img.addEventListener(RERENDER_EVENT, async (e) => {
e.stopPropagation();
const parent = img.parentElement;
const imgMaxWidth = img.style.maxWidth;
const imgMaxHeigth = img.style.maxHeight;
const fileSource = img.getAttribute("fileSource");
const onCanvas = img.getAttribute("onCanvas") === "true";
const newImg = await createImgElement({
fname: fileSource,
fwidth: img.getAttribute("w"),
fheight: img.getAttribute("h"),
style: img.getAttribute("class"),
}, onCanvas);
parent.empty();
if(!onCanvas) {
newImg.style.maxHeight = imgMaxHeigth;
newImg.style.maxWidth = imgMaxWidth;
}
newImg.setAttribute("fileSource",fileSource);
parent.append(newImg);
});
return img;
}
const createImageDiv = async (
attr: imgElementAttributes,
onCanvas: boolean = false
): Promise<HTMLDivElement> => {
const img = await getIMG(attr);
return createDiv(attr.style, (el) => {
el.append(img);
el.setAttribute("src", attr.fname);
if (attr.fwidth) {
el.setAttribute("w", attr.fwidth);
}
if (attr.fheight) {
el.setAttribute("h", attr.fheight);
}
el.onClickEvent((ev) => {
if (
ev.target instanceof Element &&
ev.target.tagName.toLowerCase() != "img"
) {
return;
}
const src = el.getAttribute("src");
if (src) {
const srcParts = src.match(/([^#]*)(.*)/);
if(!srcParts) return;
plugin.openDrawing(
vault.getAbstractFileByPath(srcParts[1]) as TFile,
ev[CTRL_OR_CMD]
? "new-pane"
: (ev.metaKey && !app.isMobile)
? "popout-window"
: "active-pane",
true,
srcParts[2],
);
} //.ctrlKey||ev.metaKey);
});
el.addEventListener(RERENDER_EVENT, async (e) => {
e.stopPropagation();
el.empty();
const img = await getIMG({
fname: el.getAttribute("src"),
fwidth: el.getAttribute("w"),
fheight: el.getAttribute("h"),
style: el.getAttribute("class"),
});
el.append(img);
});
});
const img = await createImgElement(attr, onCanvas);
return createDiv(attr.style, (el) => el.append(img));
};
const processReadingMode = async (
@@ -279,6 +319,13 @@ const processInternalEmbed = async (internalEmbedEl: Element, file: TFile ):Prom
const src = internalEmbedEl.getAttribute("src");
if(!src) return;
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1059
internalEmbedEl.removeClass("markdown-embed");
internalEmbedEl.removeClass("inline-embed");
internalEmbedEl.addClass("media-embed");
internalEmbedEl.addClass("image-embed");
attr.fwidth = internalEmbedEl.getAttribute("width")
? internalEmbedEl.getAttribute("width")
: getDefaultWidth(plugin);
@@ -336,101 +383,109 @@ const tmpObsidianWYSIWYG = async (
return;
}
//The timeout gives time for Obsidian to attach el to the displayed document
//Once the element is attached, I can traverse up the dom tree to find .internal-embed
//If internal embed is not found, it means the that the excalidraw.md file
//is being rendered in "reading" mode. In that case, the image with the default width
//specified in setting should be displayed
//if .internal-embed is found, then contents is replaced with the image using the
//internal-embed: Excalidraw is embedded into a markdown document
//markdown-reading-view: we are processing the markdown reading view of an actual Excalidraw file
//markdown-embed: we are processing the hover preview of a markdown file
//alt, width, and height attributes of .internal-embed to size and style the image
setTimeout(async () => {
//wait for el to be attached to the displayed document
let counter = 0;
while(!el.parentElement && counter++<=50) await sleep(50);
if(!el.parentElement) return;
let internalEmbedDiv: HTMLElement = el;
while (
!internalEmbedDiv.hasClass("dataview") &&
!internalEmbedDiv.hasClass("cm-preview-code-block") &&
!internalEmbedDiv.hasClass("cm-embed-block") &&
!internalEmbedDiv.hasClass("internal-embed") &&
internalEmbedDiv.parentElement
) {
internalEmbedDiv = internalEmbedDiv.parentElement;
}
if(
internalEmbedDiv.hasClass("dataview") ||
internalEmbedDiv.hasClass("cm-preview-code-block") ||
internalEmbedDiv.hasClass("cm-embed-block")
) {
return; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/835
}
const attr: imgElementAttributes = {
fname: ctx.sourcePath,
fheight: "",
fwidth: getDefaultWidth(plugin),
style: "excalidraw-svg",
};
attr.file = file;
//@ts-ignore
const containerEl = ctx.containerEl;
let internalEmbedDiv: HTMLElement = containerEl;
while (
!internalEmbedDiv.hasClass("dataview") &&
!internalEmbedDiv.hasClass("cm-preview-code-block") &&
!internalEmbedDiv.hasClass("cm-embed-block") &&
!internalEmbedDiv.hasClass("internal-embed") &&
!internalEmbedDiv.hasClass("markdown-reading-view") &&
!internalEmbedDiv.hasClass("markdown-embed") &&
internalEmbedDiv.parentElement
) {
internalEmbedDiv = internalEmbedDiv.parentElement;
}
if(
internalEmbedDiv.hasClass("dataview") ||
internalEmbedDiv.hasClass("cm-preview-code-block") ||
internalEmbedDiv.hasClass("cm-embed-block")
) {
return; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/835
}
if (!internalEmbedDiv.hasClass("internal-embed")) {
//We are processing the markdown preview of an actual Excalidraw file
//This could be in a hover preview of the file
//Or the file could be in markdown mode and the user switched markdown
//view of the drawing to reading mode
el.empty();
const mdPreviewSection = el.parentElement;
if(!mdPreviewSection.hasClass("markdown-preview-section")) return;
if(mdPreviewSection.hasAttribute("ready")) {
mdPreviewSection.removeChild(el);
return;
}
mdPreviewSection.setAttribute("ready","");
const imgDiv = await createImageDiv(attr);
el.appendChild(imgDiv);
return;
}
if(isTextOnlyEmbed(internalEmbedDiv)) {
//legacy reference to a block or section as text
//should be embedded as legacy text
return;
}
const attr: imgElementAttributes = {
fname: ctx.sourcePath,
fheight: "",
fwidth: getDefaultWidth(plugin),
style: "excalidraw-svg",
};
attr.file = file;
const markdownEmbed = internalEmbedDiv.hasClass("markdown-embed");
const markdownReadingView = internalEmbedDiv.hasClass("markdown-reading-view");
if (!internalEmbedDiv.hasClass("internal-embed") && (markdownEmbed || markdownReadingView)) {
//We are processing the markdown preview of an actual Excalidraw file
//the excalidraw file in markdown preview mode
const isFrontmatterDiv = Boolean(el.querySelector(".frontmatter"));
el.empty();
if(internalEmbedDiv.hasAttribute("ready")) {
if(!isFrontmatterDiv) {
if(el.parentElement === containerEl) containerEl.removeChild(el);
return;
}
internalEmbedDiv.setAttribute("ready","");
internalEmbedDiv.empty();
const imgDiv = await processInternalEmbed(internalEmbedDiv,file);
const onCanvas = internalEmbedDiv.hasClass("canvas-node-content");
const imgDiv = await createImageDiv(attr, onCanvas);
if(markdownEmbed) {
//display image on canvas without markdown frame
internalEmbedDiv.removeClass("markdown-embed");
internalEmbedDiv.removeClass("inline-embed");
internalEmbedDiv.addClass("media-embed");
internalEmbedDiv.addClass("image-embed");
if(!onCanvas && imgDiv.firstChild instanceof HTMLElement) {
imgDiv.firstChild.style.maxHeight = "100%";
imgDiv.firstChild.style.maxWidth = null;
}
internalEmbedDiv.appendChild(imgDiv.firstChild);
return;
}
internalEmbedDiv.appendChild(imgDiv);
return;
}
//timer to avoid the image flickering when the user is typing
let timer: NodeJS.Timeout = null;
const observer = new MutationObserver((m) => {
if (!["alt", "width", "height"].contains(m[0]?.attributeName)) {
return;
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(async () => {
timer = null;
internalEmbedDiv.empty();
const imgDiv = await processInternalEmbed(internalEmbedDiv,file);
internalEmbedDiv.appendChild(imgDiv);
}, 500);
});
observer.observe(internalEmbedDiv, {
attributes: true, //configure it to listen to attribute changes
});
if(isTextOnlyEmbed(internalEmbedDiv)) {
//legacy reference to a block or section as text
//should be embedded as legacy text
return;
}
el.empty();
if(internalEmbedDiv.hasAttribute("ready")) {
return;
}
internalEmbedDiv.setAttribute("ready","");
internalEmbedDiv.empty();
const imgDiv = await processInternalEmbed(internalEmbedDiv,file);
internalEmbedDiv.appendChild(imgDiv);
//timer to avoid the image flickering when the user is typing
let timer: NodeJS.Timeout = null;
const observer = new MutationObserver((m) => {
if (!["alt", "width", "height"].contains(m[0]?.attributeName)) {
return;
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(async () => {
timer = null;
internalEmbedDiv.empty();
const imgDiv = await processInternalEmbed(internalEmbedDiv,file);
internalEmbedDiv.appendChild(imgDiv);
}, 500);
});
observer.observe(internalEmbedDiv, {
attributes: true, //configure it to listen to attribute changes
});
};
@@ -550,11 +605,7 @@ export const observer = new MutationObserver(async (m) => {
if (src) {
plugin.openDrawing(
vault.getAbstractFileByPath(src) as TFile,
ev[CTRL_OR_CMD]
? "new-pane"
: (ev.metaKey && !app.isMobile)
? "popout-window"
: "active-pane",
linkClickModifierType(ev)
);
} //.ctrlKey||ev.metaKey);
});

39
src/PenTypes.ts Normal file
View File

@@ -0,0 +1,39 @@
export interface StrokeOptions {
thinning: number;
smoothing: number;
streamline: number;
easing: string;
simulatePressure?: boolean;
start: {
cap: boolean;
taper: number | boolean;
easing: string;
};
end: {
cap: boolean;
taper: number | boolean;
easing: string;
};
}
export interface PenOptions {
highlighter: boolean;
constantPressure: boolean;
hasOutline: boolean;
outlineWidth: number;
options: StrokeOptions;
}
export declare type ExtendedFillStyle = "dots"|"zigzag"|"zigzag-line"|"dashed"|"hachure"|"cross-hatch"|"solid"|"";
export declare type PenType = "default" | "highlighter" | "finetip" | "fountain" | "marker" | "thick-thin" | "thin-thick-thin";
export interface PenStyle {
type: PenType;
freedrawOnly: boolean;
strokeColor?: string;
backgroundColor?: string;
fillStyle: ExtendedFillStyle;
strokeWidth: number;
roughness: number;
penOptions: PenOptions;
}

View File

@@ -8,12 +8,12 @@ import {
import { PLUGIN_ID, VIEW_TYPE_EXCALIDRAW } from "./Constants";
import ExcalidrawView from "./ExcalidrawView";
import ExcalidrawPlugin from "./main";
import { GenericInputPrompt, GenericSuggester } from "./dialogs/Prompt";
import { ButtonDefinition, GenericInputPrompt, GenericSuggester } from "./dialogs/Prompt";
import { getIMGFilename } from "./utils/FileUtils";
import { splitFolderAndFilename } from "./utils/FileUtils";
export type ScriptIconMap = {
[key: string]: { name: string; svgString: string };
[key: string]: { name: string; group: string; svgString: string };
};
export class ScriptEngine {
@@ -147,7 +147,8 @@ export class ScriptEngine {
this.scriptIconMap = {
...this.scriptIconMap,
};
this.scriptIconMap[scriptPath] = { name, svgString };
const splitname = splitFolderAndFilename(name)
this.scriptIconMap[scriptPath] = { name:splitname.filename, group: splitname.folderpath === "/" ? "" : splitname.folderpath, svgString };
this.updateToolPannels();
}
@@ -169,7 +170,7 @@ export class ScriptEngine {
(async()=>{
const script = await app.vault.read(f);
if(script) {
this.executeScript(view, script, scriptName);
this.executeScript(view, script, scriptName,f);
}
})()
return true;
@@ -205,7 +206,7 @@ export class ScriptEngine {
delete app.commands.commands[commandId];
}
async executeScript(view: ExcalidrawView, script: string, title: string) {
async executeScript(view: ExcalidrawView, script: string, title: string, file: TFile) {
if (!view || !script || !title) {
return;
}
@@ -223,14 +224,24 @@ export class ScriptEngine {
header: string,
placeholder?: string,
value?: string,
buttons?: [{ caption: string; action: Function }],
buttons?: ButtonDefinition[],
lines?: number,
displayEditorButtons?: boolean,
customComponents?: (container: HTMLElement) => void,
blockPointerInputOutsideModal?: boolean,
) =>
ScriptEngine.inputPrompt(
view,
this.plugin,
app,
header,
placeholder,
value,
buttons,
lines,
displayEditorButtons,
customComponents,
blockPointerInputOutsideModal,
),
suggester: (
displayItems: string[],
@@ -245,6 +256,7 @@ export class ScriptEngine {
hint,
instructions,
),
scriptFile: file
});
/*} catch (e) {
new Notice(t("SCRIPT_EXECUTION_ERROR"), 4000);
@@ -266,19 +278,31 @@ export class ScriptEngine {
}
public static async inputPrompt(
view: ExcalidrawView,
plugin: ExcalidrawPlugin,
app: App,
header: string,
placeholder?: string,
value?: string,
buttons?: [{ caption: string; action: Function }],
buttons?: ButtonDefinition[],
lines?: number,
displayEditorButtons?: boolean,
customComponents?: (container: HTMLElement) => void,
blockPointerInputOutsideModal?: boolean,
) {
try {
return await GenericInputPrompt.Prompt(
view,
plugin,
app,
header,
placeholder,
value,
buttons,
lines,
displayEditorButtons,
customComponents,
blockPointerInputOutsideModal,
);
} catch {
return undefined;

View File

@@ -1,10 +1,32 @@
import { customAlphabet } from "nanoid";
//This is only for backward compatibility because an early version of obsidian included an encoding to avoid fantom links from littering Obsidian graph view
declare const PLUGIN_VERSION:string;
export function JSON_parse(x: string): any {
return JSON.parse(x.replaceAll("&#91;", "["));
}
export const isDarwin = /Mac|iPod|iPhone|iPad/.test(window.navigator.platform);
export const CTRL_OR_CMD = isDarwin ? "metaKey" : "ctrlKey";
export const DEVICE: {
isDesktop: boolean,
isPhone: boolean,
isTablet: boolean,
isMobile: boolean,
isLinux: boolean,
isMacOS: boolean,
isWindows: boolean,
isIOS: boolean,
isAndroid: boolean
} = {
isDesktop: !document.body.hasClass("is-tablet") && !document.body.hasClass("is-mobile"),
isPhone: document.body.hasClass("is-phone"),
isTablet: document.body.hasClass("is-tablet"),
isMobile: document.body.hasClass("is-mobile"), //running Obsidian Mobile, need to also check isTablet
isLinux: document.body.hasClass("mod-linux") && ! document.body.hasClass("is-android"),
isMacOS: document.body.hasClass("mod-macos") && ! document.body.hasClass("is-ios"),
isWindows: document.body.hasClass("mod-windows"),
isIOS: document.body.hasClass("is-ios"),
isAndroid: document.body.hasClass("is-android")
};
export const nanoid = customAlphabet(
"1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
8,
@@ -12,6 +34,13 @@ export const nanoid = customAlphabet(
export const KEYCODE = {
ESC: 27,
};
export const ROUNDNESS = { //should at one point publish @zsviczian/excalidraw/types/constants
LEGACY: 1,
PROPORTIONAL_RADIUS: 2,
ADAPTIVE_RADIUS: 3,
} as const;
export const GITHUB_RELEASES = "https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/";
export const URLFETCHTIMEOUT = 1000;
export const PLUGIN_ID = "obsidian-excalidraw-plugin";
export const SCRIPT_INSTALL_CODEBLOCK = "excalidraw-script-install";
export const SCRIPT_INSTALL_FOLDER = "Downloaded";
@@ -41,16 +70,15 @@ export const FRONTMATTER_KEY_FONTCOLOR = "excalidraw-font-color";
export const FRONTMATTER_KEY_BORDERCOLOR = "excalidraw-border-color";
export const FRONTMATTER_KEY_MD_STYLE = "excalidraw-css";
export const FRONTMATTER_KEY_AUTOEXPORT = "excalidraw-autoexport"
export const LOCAL_PROTOCOL = "md://";
export const VIEW_TYPE_EXCALIDRAW = "excalidraw";
export const ICON_NAME = "excalidraw-icon";
export const MAX_COLORS = 5;
export const COLOR_FREQ = 6;
export const RERENDER_EVENT = "excalidraw-embed-rerender";
export const BLANK_DRAWING =
'{"type":"excalidraw","version":2,"source":"https://excalidraw.com","elements":[],"appState":{"gridSize":null,"viewBackgroundColor":"#ffffff"}}';
`{"type":"excalidraw","version":2,"source":"${GITHUB_RELEASES+PLUGIN_VERSION}","elements":[],"appState":{"gridSize":null,"viewBackgroundColor":"#ffffff"}}`;
export const DARK_BLANK_DRAWING =
'{"type":"excalidraw","version":2,"source":"https://excalidraw.com","elements":[],"appState":{"theme":"dark","gridSize":null,"viewBackgroundColor":"#ffffff"}}';
`{"type":"excalidraw","version":2,"source":"${GITHUB_RELEASES+PLUGIN_VERSION}","elements":[],"appState":{"theme":"dark","gridSize":null,"viewBackgroundColor":"#ffffff"}}`;
export const FRONTMATTER = [
"---",
"",
@@ -210,10 +238,9 @@ COLOR_NAMES.set("white", "#ffffff");
COLOR_NAMES.set("whitesmoke", "#f5f5f5");
COLOR_NAMES.set("yellow", "#ffff00");
COLOR_NAMES.set("yellowgreen", "#9acd32");
export const DEFAULT_MD_EMBED_CSS = `.excalidraw-md-host{padding:0px 10px}.excalidraw-md-footer{height:5px}foreignObject{background-color:transparent}p{display:block;margin-block-start:1em;margin-block-end:1em;margin-inline-start:0px;margin-inline-end:0px;color:inherit}table,tr,th,td{color:inherit;border:1px solid;border-collapse:collapse;padding:3px}th{font-weight:bold;border-bottom:double;background-color:silver}.copy-code-button{display:none}code[class*=language-],pre[class*=language-]{color:#393a34;font-family:"Consolas","Bitstream Vera Sans Mono","Courier New",Courier,monospace;direction:ltr;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;font-size:.9em;line-height:1.2em;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}pre>code[class*=language-]{font-size:1em}pre[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection,code[class*=language-]::-moz-selection,code[class*=language-] ::-moz-selection{background:#C1DEF1}pre[class*=language-]::selection,pre[class*=language-] ::selection,code[class*=language-]::selection,code[class*=language-] ::selection{background:#C1DEF1}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto;background-color:#0000001a}:not(pre)>code[class*=language-]{padding:.2em;padding-top:1px;padding-bottom:1px;background:#f8f8f8;border:1px solid #dddddd}.token.comment,.token.prolog,.token.doctype,.token.cdata{color:green;font-style:italic}.token.namespace{opacity:.7}.token.string{color:#a31515}.token.punctuation,.token.operator{color:#393a34}.token.url,.token.symbol,.token.number,.token.boolean,.token.variable,.token.constant,.token.inserted{color:#36acaa}.token.atrule,.token.keyword,.token.attr-value,.language-autohotkey .token.selector,.language-json .token.boolean,.language-json .token.number,code[class*=language-css]{color:#00f}.token.function{color:#393a34}.token.deleted,.language-autohotkey .token.tag{color:#9a050f}.token.selector,.language-autohotkey .token.keyword{color:#00009f}.token.important{color:#e90}.token.important,.token.bold{font-weight:bold}.token.italic{font-style:italic}.token.class-name,.language-json .token.property{color:#2b91af}.token.tag,.token.selector{color:maroon}.token.attr-name,.token.property,.token.regex,.token.entity{color:red}.token.directive.tag .tag{background:#ffff00;color:#393a34}.line-numbers.line-numbers .line-numbers-rows{border-right-color:#a5a5a5}.line-numbers .line-numbers-rows>span:before{color:#2b91af}.line-highlight.line-highlight{background:rgba(193,222,241,.2);background:-webkit-linear-gradient(left,rgba(193,222,241,.2) 70%,rgba(221,222,241,0));background:linear-gradient(to right,rgba(193,222,241,.2) 70%,rgba(221,222,241,0))}blockquote{ font-style:italic;background-color:rgb(46,43,42,0.1);margin:0;margin-left:1em;border-radius:0 4px 4px 0;border:1px solid hsl(0,80%,32%);border-left-width:8px;border-top-width:0px;border-right-width:0px;border-bottom-width:0px;padding:10px 20px;margin-inline-start:30px;margin-inline-end:30px;}`;
export const DEFAULT_MD_EMBED_CSS = `.snw-reference{display: none;}.excalidraw-md-host{padding:0px 10px}.excalidraw-md-footer{height:5px}foreignObject{background-color:transparent}p{display:block;margin-block-start:1em;margin-block-end:1em;margin-inline-start:0px;margin-inline-end:0px;color:inherit}table,tr,th,td{color:inherit;border:1px solid;border-collapse:collapse;padding:3px}th{font-weight:bold;border-bottom:double;background-color:silver}.copy-code-button{display:none}code[class*=language-],pre[class*=language-]{color:#393a34;font-family:"Consolas","Bitstream Vera Sans Mono","Courier New",Courier,monospace;direction:ltr;text-align:left;white-space:pre;word-spacing:normal;word-break:normal;font-size:.9em;line-height:1.2em;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-hyphens:none;-moz-hyphens:none;-ms-hyphens:none;hyphens:none}pre>code[class*=language-]{font-size:1em}pre[class*=language-]::-moz-selection,pre[class*=language-] ::-moz-selection,code[class*=language-]::-moz-selection,code[class*=language-] ::-moz-selection{background:#C1DEF1}pre[class*=language-]::selection,pre[class*=language-] ::selection,code[class*=language-]::selection,code[class*=language-] ::selection{background:#C1DEF1}pre[class*=language-]{padding:1em;margin:.5em 0;overflow:auto;background-color:#0000001a}:not(pre)>code[class*=language-]{padding:.2em;padding-top:1px;padding-bottom:1px;background:#f8f8f8;border:1px solid #dddddd}.token.comment,.token.prolog,.token.doctype,.token.cdata{color:green;font-style:italic}.token.namespace{opacity:.7}.token.string{color:#a31515}.token.punctuation,.token.operator{color:#393a34}.token.url,.token.symbol,.token.number,.token.boolean,.token.variable,.token.constant,.token.inserted{color:#36acaa}.token.atrule,.token.keyword,.token.attr-value,.language-autohotkey .token.selector,.language-json .token.boolean,.language-json .token.number,code[class*=language-css]{color:#00f}.token.function{color:#393a34}.token.deleted,.language-autohotkey .token.tag{color:#9a050f}.token.selector,.language-autohotkey .token.keyword{color:#00009f}.token.important{color:#e90}.token.important,.token.bold{font-weight:bold}.token.italic{font-style:italic}.token.class-name,.language-json .token.property{color:#2b91af}.token.tag,.token.selector{color:maroon}.token.attr-name,.token.property,.token.regex,.token.entity{color:red}.token.directive.tag .tag{background:#ffff00;color:#393a34}.line-numbers.line-numbers .line-numbers-rows{border-right-color:#a5a5a5}.line-numbers .line-numbers-rows>span:before{color:#2b91af}.line-highlight.line-highlight{background:rgba(193,222,241,.2);background:-webkit-linear-gradient(left,rgba(193,222,241,.2) 70%,rgba(221,222,241,0));background:linear-gradient(to right,rgba(193,222,241,.2) 70%,rgba(221,222,241,0))}blockquote{ font-style:italic;background-color:rgb(46,43,42,0.1);margin:0;margin-left:1em;border-radius:0 4px 4px 0;border:1px solid hsl(0,80%,32%);border-left-width:8px;border-top-width:0px;border-right-width:0px;border-bottom-width:0px;padding:10px 20px;margin-inline-start:30px;margin-inline-end:30px;}`;
export const SCRIPTENGINE_ICON = `<g transform="translate(-8,-8)"><path d="M24.318 37.983c-1.234-1.232-8.433-3.903-7.401-7.387 1.057-3.484 9.893-12.443 13.669-13.517 3.776-1.074 6.142 6.523 9.012 7.073 2.87.55 6.797-1.572 8.207-3.694 1.384-2.148-3.147-7.413.15-9.168 3.298-1.755 16.389-2.646 19.611-1.284 3.247 1.363-1.611 7.335-.151 9.483 1.46 2.148 6.067 3.746 8.836 3.38 2.769-.368 4.154-6.733 7.728-5.633 3.575 1.1 12.36 8.828 13.67 12.233 1.308 3.406-5.186 5.423-5.79 8.2-.58 2.75-.026 6.705 2.265 8.355 2.266 1.65 9.642-1.78 11.404 1.598 1.762 3.38 1.007 15.35-.806 18.651-1.787 3.353-7.753-.367-9.969 1.31-2.215 1.65-3.901 5.92-3.373 8.67.504 2.777 7.754 4.48 6.445 7.885C96.49 87.543 87.15 95.454 83.5 96.685c-3.65 1.231-4.96-4.741-7.577-5.16-2.593-.393-6.57.707-8.03 2.75-1.436 2.017 2.668 7.806-.63 9.483-3.323 1.676-15.759 2.226-19.157.655-3.373-1.598.554-7.964-1.108-10.138-1.687-2.174-6.394-3.431-9.012-2.907-2.643.55-3.273 7.282-6.747 6.103-3.499-1.126-12.788-9.535-14.172-13.019-1.36-3.484 5.437-5.108 5.966-7.858.529-2.777-.68-7.073-2.744-8.697-2.064-1.624-7.93 2.41-9.642-1.126-1.737-3.537-2.441-16.765-.654-20.118 1.787-3.3 9.062 1.598 11.429.183 2.366-1.44 2.316-7.282 2.769-8.749m.126-.104c-1.234-1.232-8.433-3.903-7.401-7.387 1.057-3.484 9.893-12.443 13.669-13.517 3.776-1.074 6.142 6.523 9.012 7.073 2.87.55 6.797-1.572 8.207-3.694 1.384-2.148-3.147-7.413.15-9.168 3.298-1.755 16.389-2.646 19.611-1.284 3.247 1.363-1.611 7.335-.151 9.483 1.46 2.148 6.067 3.746 8.836 3.38 2.769-.368 4.154-6.733 7.728-5.633 3.575 1.1 12.36 8.828 13.67 12.233 1.308 3.406-5.186 5.423-5.79 8.2-.58 2.75-.026 6.705 2.265 8.355 2.266 1.65 9.642-1.78 11.404 1.598 1.762 3.38 1.007 15.35-.806 18.651-1.787 3.353-7.753-.367-9.969 1.31-2.215 1.65-3.901 5.92-3.373 8.67.504 2.777 7.754 4.48 6.445 7.885C96.49 87.543 87.15 95.454 83.5 96.685c-3.65 1.231-4.96-4.741-7.577-5.16-2.593-.393-6.57.707-8.03 2.75-1.436 2.017 2.668 7.806-.63 9.483-3.323 1.676-15.759 2.226-19.157.655-3.373-1.598.554-7.964-1.108-10.138-1.687-2.174-6.394-3.431-9.012-2.907-2.643.55-3.273 7.282-6.747 6.103-3.499-1.126-12.788-9.535-14.172-13.019-1.36-3.484 5.437-5.108 5.966-7.858.529-2.777-.68-7.073-2.744-8.697-2.064-1.624-7.93 2.41-9.642-1.126-1.737-3.537-2.441-16.765-.654-20.118 1.787-3.3 9.062 1.598 11.429.183 2.366-1.44 2.316-7.282 2.769-8.749" fill="none" stroke-width="2" stroke-linecap="round" stroke="currentColor"/><path d="M81.235 56.502a23.3 23.3 0 0 1-1.46 8.068 20.785 20.785 0 0 1-1.762 3.72 24.068 24.068 0 0 1-5.337 6.26 22.575 22.575 0 0 1-3.449 2.358 23.726 23.726 0 0 1-7.803 2.803 24.719 24.719 0 0 1-8.333 0 24.102 24.102 0 0 1-4.028-1.074 23.71 23.71 0 0 1-3.776-1.729 23.259 23.259 0 0 1-6.369-5.265 23.775 23.775 0 0 1-2.416-3.353 24.935 24.935 0 0 1-1.762-3.72 23.765 23.765 0 0 1-1.083-3.981 23.454 23.454 0 0 1 0-8.173c.252-1.336.604-2.698 1.083-3.956a24.935 24.935 0 0 1 1.762-3.72 22.587 22.587 0 0 1 2.416-3.378c.881-1.048 1.888-2.017 2.946-2.908a24.38 24.38 0 0 1 3.423-2.357 23.71 23.71 0 0 1 3.776-1.73 21.74 21.74 0 0 1 4.028-1.047 23.437 23.437 0 0 1 8.333 0 24.282 24.282 0 0 1 7.803 2.777 26.198 26.198 0 0 1 3.45 2.357 24.62 24.62 0 0 1 5.336 6.287 20.785 20.785 0 0 1 1.762 3.72 21.32 21.32 0 0 1 1.083 3.955c.251 1.336.302 3.405.377 4.086.05.681.05-.68 0 0" fill="none" stroke-width="4" stroke-linecap="round" stroke="currentColor"/><path d="M69.404 56.633c-6.596-3.3-13.216-6.6-19.51-9.744m19.51 9.744c-6.747-3.379-13.493-6.758-19.51-9.744m0 0v19.489m0-19.49v19.49m0 0c4.355-2.148 8.71-4.322 19.51-9.745m-19.51 9.745c3.978-1.965 7.93-3.956 19.51-9.745m0 0h0m0 0h0" fill="currentColor" stroke-linecap="round" stroke="currentColor" stroke-width="4"/></g>`;
export const DISK_ICON_NAME = "disk";
export const DISK_ICON = `<path fill="none" stroke="currentColor" fill="#fff" d="M0 0h100v100H0z"/><path fill="none" stroke="currentColor" d="M20.832 4.168c21.824.145 43.645.289 74.68.5m-74.68-.5c17.09.113 34.176.227 74.68.5m0 0c.094 27.3.191 54.602.32 91.164m-.32-91.164c.113 32.633.23 65.27.32 91.164m0 0H4.168m91.664 0H4.168m0 0v-75m0 75v-75m0 0L20.832 4.168M4.168 20.832L20.832 4.168M20.832 4.168h58.336m-58.336 0h58.336m0 0v25m0-25v25m0 0H20.832m58.336 0H20.832m0 0v-25m0 25v-25" stroke-width="1.66668" /><path fill="none" stroke="currentColor" d="M29.168 4.168h16.664v16.664H29.168"/><path fill="none" stroke="currentColor" d="M29.168 4.168h16.664m-16.664 0h16.664m0 0v16.664m0-16.664v16.664m0 0H29.168m16.664 0H29.168m0 0V4.168m0 16.664V4.168M12.5 54.168h75m-75 0h75m0 0v41.664m0-41.664v41.664m0 0h-75m75 0h-75m0 0V54.168m0 41.664V54.168M20.832 62.5c20.11-.18 40.219-.36 55.68-.5m-55.68.5c14.656-.133 29.313-.262 55.68-.5M20.832 71.332c13.098-.117 26.2-.234 55.68-.5m-55.68.5l55.68-.5M21.117 79.582c20.645-.184 41.285-.371 55.68-.5m-55.68.5c18.153-.16 36.301-.324 55.68-.5" stroke-width="1.66668"/>`;
export const DISK_ICON_NAME = "save";
export const PNG_ICON_NAME = "save-png";
export const PNG_ICON = `<defs><symbol overflow="visible" id="aa"><path fill="currentColor" stroke="currentColor" d="M6.578-10.984h8.188c2.03 0 3.64-.594 5.046-1.844 1.563-1.422 2.25-3.094 2.25-5.469 0-4.875-2.906-7.61-8.046-7.61H3.25V0h3.328zm0-2.907v-9.093h6.938c3.171 0 5.078 1.703 5.078 4.547 0 2.843-1.907 4.546-5.078 4.546zm0 0"></path></symbol><symbol overflow="visible" id="bb"><path fill="currentColor" stroke="currentColor" d="M23.094-25.906h-3.14V-4.72L6.327-25.906h-3.61V0H5.86v-21L19.344 0h3.75zm0 0"></path></symbol><symbol overflow="visible" id="cc"><path fill="currentColor" stroke="currentColor" d="M25.344-13.672h-10.86v2.906h7.938v.704c0 4.624-3.438 7.968-8.188 7.968-2.656 0-5.046-.969-6.578-2.625-1.718-1.86-2.765-4.953-2.765-8.14 0-6.36 3.656-10.563 9.156-10.563 3.969 0 6.828 2.031 7.547 5.375h3.39c-.922-5.265-4.922-8.281-10.906-8.281-3.172 0-5.75.812-7.781 2.484-3.047 2.485-4.719 6.5-4.719 11.157 0 7.968 4.89 13.5 11.938 13.5 3.53 0 6.328-1.313 8.906-4.11l.812 3.438h2.11zm0 0"></path></symbol></defs><path fill="none" stroke="currentColor" d="M-.003.003v59.999m0-60v60m0 0h220.006m-220.006 0h220.006m0 0v-60m0 60v-60" transform="matrix(.40833 0 0 .40574 4.083 68.975)" stroke-width="4"></path><use xlink:href="#aa" x="11.023" y="86.651"></use><use xlink:href="#bb" x="33.944" y="86.651"></use><use xlink:href="#cc" x="59.724" y="86.651"></use><path fill="currentColor" stroke="currentColor" d="M40.832 4.059h16.336v32.457h8.164L49 52.746l-16.332-16.23h8.164V4.059" fill-rule="evenodd"></path><path fill="currentColor" stroke="currentColor" d="M-.003.003h40.006m-40.006 0h40.006m0 0v79.995m0-79.995v79.995m0 0h19.994m-19.994 0h19.994m0 0C51.55 88.451 43.093 96.904 20 120m39.997-40.002A196001.962 196001.962 0 0120 120m0 0C8.406 108.41-3.18 96.817-19.997 79.998M20 120C9.43 109.43-1.142 98.858-19.997 79.998m0 0H-.003m-19.994 0H-.003m0 0V.003m0 79.995V.003m0 0h0m0 0h0" transform="matrix(.40833 0 0 .40574 40.833 4.057)" stroke-width="4"></path>`;
export const SVG_ICON_NAME = "save-svg";

211
src/dialogs/ExportDialog.ts Normal file
View File

@@ -0,0 +1,211 @@
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/types";
import { Modal, Setting, SliderComponent, TFile } from "obsidian";
import { getEA } from "src";
import { DEVICE } from "src/Constants";
import { ExcalidrawAutomate } from "src/ExcalidrawAutomate";
import ExcalidrawView from "src/ExcalidrawView";
import ExcalidrawPlugin from "src/main";
import { fragWithHTML, getExportPadding, getExportTheme, getPNGScale, getWithBackground } from "src/utils/Utils";
export class ExportDialog extends Modal {
private ea: ExcalidrawAutomate;
private api: ExcalidrawImperativeAPI;
public padding: number;
public scale: number;
public theme: string;
public transparent: boolean;
public saveSettings: boolean;
public dirty: boolean = false;
private selectedOnlySetting: Setting;
private hasSelectedElements: boolean = false;
private boundingBox: {
topX: number;
topY: number;
width: number;
height: number;
};
public embedScene: boolean;
public exportSelectedOnly: boolean;
public saveToVault: boolean;
constructor(
private plugin: ExcalidrawPlugin,
private view: ExcalidrawView,
private file: TFile,
) {
super(app);
this.ea = getEA(this.view);
this.api = this.ea.getExcalidrawAPI() as ExcalidrawImperativeAPI;
this.padding = getExportPadding(this.plugin,this.file);
this.scale = getPNGScale(this.plugin,this.file)
this.theme = getExportTheme(this.plugin, this.file, (this.api).getAppState().theme)
this.boundingBox = this.ea.getBoundingBox(this.ea.getViewElements());
this.embedScene = false;
this.exportSelectedOnly = false;
this.saveToVault = true;
this.transparent = !getWithBackground(this.plugin, this.file);
this.saveSettings = false;
}
onOpen(): void {
this.containerEl.classList.add("excalidraw-release");
this.titleEl.setText(`Export Image`);
this.hasSelectedElements = this.view.getViewSelectedElements().length > 0;
//@ts-ignore
this.selectedOnlySetting.setVisibility(this.hasSelectedElements);
}
async onClose() {
this.dirty = this.saveSettings;
}
async createForm() {
let scaleSetting:Setting;
let paddingSetting: Setting;
this.contentEl.createEl("h1",{text: "Image settings"});
this.contentEl.createEl("p",{text: "Transparency only affects PNGs. Excalidraw files can only be exported outside the Vault. PNGs copied to clipboard may not include the scene."})
const size = ():DocumentFragment => {
const width = Math.round(this.scale*this.boundingBox.width + this.padding*2);
const height = Math.round(this.scale*this.boundingBox.height + this.padding*2);
return fragWithHTML(`The lager the scale, the larger the image.<br>Scale: <b>${this.scale}</b><br>Image size: <b>${width}x${height}</b>`);
}
const padding = ():DocumentFragment => {
return fragWithHTML(`Current image padding is <b>${this.padding}</b>`);
}
paddingSetting = new Setting(this.contentEl)
.setName("Image padding")
.setDesc(padding())
.addSlider(slider => {
slider
.setLimits(0,50,1)
.setValue(this.padding)
.onChange(value => {
this.padding = value;
scaleSetting.setDesc(size());
paddingSetting.setDesc(padding());
})
})
scaleSetting = new Setting(this.contentEl)
.setName("PNG Scale")
.setDesc(size())
.addSlider(slider =>
slider
.setLimits(0.5,5,0.5)
.setValue(this.scale)
.onChange(value => {
this.scale = value;
scaleSetting.setDesc(size());
})
)
new Setting(this.contentEl)
.setName("Export theme")
.addDropdown(dropdown =>
dropdown
.addOption("light","Light")
.addOption("dark","Dark")
.setValue(this.theme)
.onChange(value => {
this.theme = value;
})
)
new Setting(this.contentEl)
.setName("Background color")
.addDropdown(dropdown =>
dropdown
.addOption("transparent","Transparent")
.addOption("with-color","Use scene background color")
.setValue(this.transparent?"transparent":"with-color")
.onChange(value => {
this.transparent = value === "transparent";
})
)
new Setting(this.contentEl)
.setName("Save or one-time settings?")
.addDropdown(dropdown =>
dropdown
.addOption("save","Save these settings as the preset for this image")
.addOption("one-time","These are one-time settings")
.setValue(this.saveSettings?"save":"one-time")
.onChange(value => {
this.saveSettings = value === "save";
})
)
this.contentEl.createEl("h1",{text:"Export settings"});
new Setting(this.contentEl)
.setName("Embed the Excalidraw scene in the exported file?")
.addDropdown(dropdown =>
dropdown
.addOption("embed","Embed scene")
.addOption("no-embed","Do not embed scene")
.setValue(this.embedScene?"embed":"no-embed")
.onChange(value => {
this.embedScene = value === "embed";
})
)
if(DEVICE.isDesktop) {
new Setting(this.contentEl)
.setName("Where to save the image?")
.addDropdown(dropdown =>
dropdown
.addOption("vault","Save image to your Vault")
.addOption("outside","Export image outside your Vault")
.setValue(this.saveToVault?"vault":"outside")
.onChange(value => {
this.saveToVault = value === "vault";
})
)
}
this.selectedOnlySetting = new Setting(this.contentEl)
.setName("Export entire scene or just selected elements?")
.addDropdown(dropdown =>
dropdown
.addOption("all","Export entire scene")
.addOption("selected","Export selected elements")
.setValue(this.exportSelectedOnly?"selected":"all")
.onChange(value => {
this.exportSelectedOnly = value === "selected";
})
)
const div = this.contentEl.createDiv({cls: "excalidraw-prompt-buttons-div"});
const bPNG = div.createEl("button", { text: "PNG to File", cls: "excalidraw-prompt-button"});
bPNG.onclick = () => {
this.saveToVault
? this.view.savePNG(this.view.getScene(this.hasSelectedElements && this.exportSelectedOnly))
: this.view.exportPNG(this.embedScene,this.hasSelectedElements && this.exportSelectedOnly);
this.close();
};
const bSVG = div.createEl("button", { text: "SVG to File", cls: "excalidraw-prompt-button" });
bSVG.onclick = () => {
this.saveToVault
? this.view.saveSVG(this.view.getScene(this.hasSelectedElements && this.exportSelectedOnly))
: this.view.exportSVG(this.embedScene,this.hasSelectedElements && this.exportSelectedOnly);
this.close();
};
const bExcalidraw = div.createEl("button", { text: "Excalidraw", cls: "excalidraw-prompt-button" });
bExcalidraw.onclick = () => {
this.view.exportExcalidraw(this.hasSelectedElements && this.exportSelectedOnly);
this.close();
};
if(DEVICE.isDesktop) {
const bPNGClipboard = div.createEl("button", { text: "PNG to Clipboard", cls: "excalidraw-prompt-button" });
bPNGClipboard.onclick = () => {
this.view.exportPNGToClipboard(this.embedScene, this.hasSelectedElements && this.exportSelectedOnly);
this.close();
};
}
}
}

View File

@@ -476,3 +476,91 @@ export class FolderSuggestionModal extends SuggestionModal<TFolder> {
return this.folders;
}
}
export class FileSuggestionModal extends SuggestionModal<TFile> {
text: TextComponent;
cache: CachedMetadata;
files: TFile[];
file: TFile;
constructor(app: App, input: TextComponent, items: TFile[]) {
super(app, input.inputEl, items);
this.limit = 20;
this.files = [...items];
this.text = input;
this.inputEl.addEventListener("input", () => this.getFile());
}
getFile() {
const v = this.inputEl.value;
const file = this.app.vault.getAbstractFileByPath(v);
if (file === this.file) {
return;
}
if (!(file instanceof TFile)) {
return;
}
this.file = file;
this.onInputChanged();
}
getSelectedItem() {
return this.file;
}
getItemText(item: TFile) {
return item.path;
}
onChooseItem(item: TFile) {
this.file = item;
this.text.setValue(item.path);
this.text.onChanged();
}
selectSuggestion({ item }: FuzzyMatch<TFile>) {
this.file = item;
this.text.setValue(item.path);
this.onClose();
this.text.onChanged();
this.close();
}
renderSuggestion(result: FuzzyMatch<TFile>, el: HTMLElement) {
const { item, match: matches } = result || {};
const content = el.createDiv({
cls: "suggestion-content",
});
if (!item) {
content.setText(this.emptyStateText);
content.parentElement.addClass("is-selected");
return;
}
const pathLength = item.path.length - item.name.length;
const matchElements = matches.matches.map((m) => {
return createSpan("suggestion-highlight");
});
for (let i = pathLength; i < item.path.length; i++) {
const match = matches.matches.find((m) => m[0] === i);
if (match) {
const element = matchElements[matches.matches.indexOf(match)];
content.appendChild(element);
element.appendText(item.path.substring(match[0], match[1]));
i += match[1] - match[0] - 1;
continue;
}
content.appendText(item.path[i]);
}
el.createDiv({
cls: "suggestion-note",
text: item.path,
});
}
getItems() {
return this.files;
}
}

View File

@@ -1,6 +1,7 @@
import { App, FuzzySuggestModal, TFile } from "obsidian";
import { isALT, scaleToFullsizeModifier } from "src/utils/ModifierkeyHelper";
import { fileURLToPath } from "url";
import { IMAGE_TYPES, REG_LINKINDEX_INVALIDCHARS } from "../Constants";
import { DEVICE, IMAGE_TYPES, REG_LINKINDEX_INVALIDCHARS } from "../Constants";
import ExcalidrawView from "../ExcalidrawView";
import { t } from "../lang/helpers";
import ExcalidrawPlugin from "../main";
@@ -25,11 +26,15 @@ export class InsertImageDialog extends FuzzySuggestModal<TFile> {
this.emptyStateText = t("NO_MATCH");
this.inputEl.onkeyup = (e) => {
//@ts-ignore
if (e.key === "Enter" && e.altKey && this.chooser.values) {
if (e.key === "Enter" && scaleToFullsizeModifier(e) && this.chooser.values) {
this.onChooseItem(
//@ts-ignore
this.chooser.values[this.chooser.selectedItem].item,
new KeyboardEvent("keypress",{altKey: true})
new KeyboardEvent("keypress",{
shiftKey: true,
metaKey: !(DEVICE.isIOS || DEVICE.isMacOS),
ctrlKey: (DEVICE.isIOS || DEVICE.isMacOS),
})
);
this.close();
}
@@ -51,12 +56,11 @@ export class InsertImageDialog extends FuzzySuggestModal<TFile> {
}
onChooseItem(item: TFile, event: KeyboardEvent): void {
const ea = this.plugin.ea;
ea.reset();
ea.setView(this.view);
const ea = this.plugin.ea.getAPI(this.view);
ea.canvas.theme = this.view.excalidrawAPI.getAppState().theme;
const scaleToFullsize = scaleToFullsizeModifier(event);
(async () => {
await ea.addImage(0, 0, item, !event.altKey);
await ea.addImage(0, 0, item, !scaleToFullsize);
ea.addElementsToView(true, false, true);
})();
}

View File

@@ -0,0 +1,342 @@
import { ButtonComponent, TFile } from "obsidian";
import ExcalidrawView from "../ExcalidrawView";
import ExcalidrawPlugin from "../main";
import { getPDFDoc } from "src/utils/FileUtils";
import { Modal, Setting, TextComponent } from "obsidian";
import { FileSuggestionModal } from "./FolderSuggester";
import { getEA } from "src";
import { ExcalidrawAutomate } from "src/ExcalidrawAutomate";
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/types";
export class InsertPDFModal extends Modal {
private borderBox: boolean = true;
private gapSize:number = 20;
private numColumns: number = 1;
private lockAfterImport: boolean = true;
private pagesToImport:number[] = [];
private pageDimensions: {width: number, height: number} = {width: 0, height: 0};
private importScale = 0.3;
private imageSizeMessage: HTMLElement;
private pdfDoc: any;
private pdfFile: TFile;
private dirty: boolean = false;
constructor(
private plugin: ExcalidrawPlugin,
private view: ExcalidrawView,
) {
super(app);
}
open (file?: TFile) {
if(file && file.extension.toLowerCase() === "pdf") {
this.pdfFile = file;
}
super.open();
}
onOpen(): void {
this.containerEl.classList.add("excalidraw-release");
this.titleEl.setText(`Import PDF`);
this.createForm();
}
async onClose() {
if(this.dirty) {
this.plugin.settings.pdfImportScale = this.importScale;
this.plugin.settings.pdfBorderBox = this.borderBox;
this.plugin.settings.pdfGapSize = this.gapSize;
this.plugin.settings.pdfNumColumns = this.numColumns;
this.plugin.settings.pdfLockAfterImport = this.lockAfterImport;
this.plugin.saveSettings();
}
if(this.pdfDoc) {
this.pdfDoc.destroy();
this.pdfDoc = null;
}
}
private async getPageDimensions (pdfDoc: any) {
try {
const scale = this.plugin.settings.pdfScale;
const canvas = createEl("canvas");
const page = await pdfDoc.getPage(1);
// Set scale
const viewport = page.getViewport({ scale });
this.pageDimensions.height = viewport.height;
this.pageDimensions.width = viewport.width;
//https://github.com/excalidraw/excalidraw/issues/4036
canvas.width = 0;
canvas.height = 0;
this.setImageSizeMessage();
} catch(e) {
console.log(e);
}
}
/**
* Creates a list of numbers from page ranges representing the pages to import.
* sets the pagesToImport property.
* @param pageRanges A string representing the pages to import. e.g.: 1,3-5,7,9-10
* @returns A list of numbers representing the pages to import.
*/
private createPageListFromString(pageRanges:string):number[] {
const cleanNonDigits = (str:string) => str.replace(/\D/g, "");
this.pagesToImport = [];
const pageRangesArray:string[] = pageRanges.split(",");
pageRangesArray.forEach((pageRange) => {
const pageRangeArray = pageRange.split("-");
if(pageRangeArray.length === 1) {
const page = parseInt(cleanNonDigits(pageRangeArray[0]));
!isNaN(page) && this.pagesToImport.push(page);
} else if(pageRangeArray.length === 2) {
const start = parseInt(cleanNonDigits(pageRangeArray[0]));
const end = parseInt(cleanNonDigits(pageRangeArray[1]));
if(isNaN(start) || isNaN(end)) return;
for(let i = start; i <= end; i++) {
this.pagesToImport.push(i);
}
}
});
return this.pagesToImport;
}
private setImageSizeMessage = () => this.imageSizeMessage.innerText = `${Math.round(this.pageDimensions.width*this.importScale)} x ${Math.round(this.pageDimensions.height*this.importScale)}`;
async createForm() {
await this.plugin.loadSettings();
this.borderBox = this.plugin.settings.pdfBorderBox;
this.gapSize = this.plugin.settings.pdfGapSize;
this.numColumns = this.plugin.settings.pdfNumColumns;
this.lockAfterImport = this.plugin.settings.pdfLockAfterImport;
this.importScale = this.plugin.settings.pdfImportScale;
const ce = this.contentEl;
let numPagesMessage: HTMLParagraphElement;
let numPages: number;
let importButton: ButtonComponent;
let importMessage: HTMLElement;
const importButtonMessages = () => {
if(!this.pdfDoc) {
importMessage.innerText = "Please select a PDF file";
importButton.buttonEl.style.display="none";
return;
}
if(this.pagesToImport.length === 0) {
importButton.buttonEl.style.display="none";
importMessage.innerText = "Please select pages to import";
return
}
if(Math.max(...this.pagesToImport) <= this.pdfDoc.numPages) {
importButton.buttonEl.style.display="block";
importMessage.innerText = "";
return;
}
else {
importButton.buttonEl.style.display="none";
importMessage.innerText = `The selected document has ${this.pdfDoc.numPages} pages. Please select pages between 1 and ${this.pdfDoc.numPages}`;
return
}
}
const numPagesMessages = () => {
if(numPages === 0) {
numPagesMessage.innerText = "Please select a PDF file";
return;
}
numPagesMessage.innerHTML = `There are <b>${numPages}</b> pages in the selected document.`;
}
const setFile = async (file: TFile) => {
if(this.pdfDoc) await this.pdfDoc.destroy();
this.pdfDoc = null;
if(file) {
this.pdfDoc = await getPDFDoc(file);
this.pdfFile = file;
if(this.pdfDoc) {
numPages = this.pdfDoc.numPages;
importButtonMessages();
numPagesMessages();
this.getPageDimensions(this.pdfDoc);
} else {
importButton.setDisabled(true);
}
}
}
const search = new TextComponent(ce);
search.inputEl.style.width = "100%";
const suggester = new FileSuggestionModal(this.app, search,app.vault.getFiles().filter((f: TFile) => f.extension.toLowerCase() === "pdf"));
search.onChange(async () => {
const file = suggester.getSelectedItem();
await setFile(file);
});
numPagesMessage = ce.createEl("p", {text: ""});
numPagesMessages();
let importPagesMessage: HTMLParagraphElement;
let pageRangesTextComponent: TextComponent
new Setting(ce)
.setName("Pages to import")
.addText(text => {
pageRangesTextComponent = text;
text
.setPlaceholder("e.g.: 1,3-5,7,9-10")
.onChange((value) => {
const pages = this.createPageListFromString(value);
if(pages.length > 15) {
importPagesMessage.innerHTML = `You are importing <b>${pages.length}</b> pages. ⚠️ This may take a while. ⚠️`;
} else {
importPagesMessage.innerHTML = `You are importing <b>${pages.length}</b> pages.`;
}
importButtonMessages();
})
text.inputEl.style.width = "100%";
})
importPagesMessage = ce.createEl("p", {text: ""});
new Setting(ce)
.setName("Add border box")
.addToggle(toggle => toggle
.setValue(this.borderBox)
.onChange((value) => {
this.borderBox = value;
this.dirty = true;
}))
new Setting(ce)
.setName("Lock pages on canvas after import")
.addToggle(toggle => toggle
.setValue(this.lockAfterImport)
.onChange((value) => {
this.lockAfterImport = value
this.dirty = true;
}))
let columnsText: HTMLDivElement;
new Setting(ce)
.setName("Number of columns")
.addSlider(slider => slider
.setLimits(1, 100, 1)
.setValue(this.numColumns)
.onChange(value => {
this.numColumns = value;
columnsText.innerText = ` ${value.toString()}`;
this.dirty = true;
}))
.settingEl.createDiv("", (el) => {
columnsText = el;
el.style.minWidth = "2.3em";
el.style.textAlign = "right";
el.innerText = ` ${this.numColumns.toString()}`;
});
let gapSizeText: HTMLDivElement;
new Setting(ce)
.setName("Size of gap between pages")
.addSlider(slider => slider
.setLimits(10, 200, 10)
.setValue(this.gapSize)
.onChange(value => {
this.gapSize = value;
gapSizeText.innerText = ` ${value.toString()}`;
this.dirty = true;
}))
.settingEl.createDiv("", (el) => {
gapSizeText = el;
el.style.minWidth = "2.3em";
el.style.textAlign = "right";
el.innerText = ` ${this.gapSize.toString()}`;
});
const importSizeSetting = new Setting(ce)
.setName("Imported page size")
.setDesc(`${this.pageDimensions.width*this.importScale} x ${this.pageDimensions.height*this.importScale}`)
.addSlider(slider => slider
.setLimits(0.1, 1.5, 0.1)
.setValue(this.importScale)
.onChange(value => {
this.importScale = value;
this.dirty = true;
this.setImageSizeMessage();
}))
this.imageSizeMessage = importSizeSetting.descEl;
const actionButton = new Setting(ce)
.setDesc("Select a document first")
.addButton(button => {
button
.setButtonText("Import PDF")
.setCta()
.onClick(async () => {
const ea = getEA(this.view) as ExcalidrawAutomate;
let column = 0;
let row = 0;
const imgWidth = Math.round(this.pageDimensions.width*this.importScale);
const imgHeight = Math.round(this.pageDimensions.height*this.importScale);
for(let i = 0; i < this.pagesToImport.length; i++) {
const page = this.pagesToImport[i];
importMessage.innerText = `Importing page ${page} (${i+1} of ${this.pagesToImport.length})`;
const topX = Math.round(this.pageDimensions.width*this.importScale*column + this.gapSize*column);
const topY = Math.round(this.pageDimensions.height*this.importScale*row + this.gapSize*row);
ea.style.strokeColor = this.borderBox ? "#000000" : "transparent";
const boxID = ea.addRect(
topX,
topY,
imgWidth,
imgHeight
);
const boxEl = ea.getElement(boxID) as any;
if(this.lockAfterImport) boxEl.locked = true;
const imageID = await ea.addImage(
topX,
topY,
this.pdfFile.path + `#page=${page}`,
false);
const imgEl = ea.getElement(imageID) as any;
imgEl.width = imgWidth;
imgEl.height = imgHeight;
if(this.lockAfterImport) imgEl.locked = true;
ea.addToGroup([boxID,imageID]);
column = (column + 1) % this.numColumns;
if(column === 0) row++;
}
await ea.addElementsToView(true,true,false);
const api = ea.getExcalidrawAPI() as ExcalidrawImperativeAPI;
const ids = ea.getElements().map(el => el.id);
const viewElements = ea.getViewElements().filter(el => ids.includes(el.id));
api.selectElements(viewElements);
api.zoomToFit(viewElements);
this.close();
})
importButton = button;
importButton.buttonEl.style.display = "none";
});
importMessage = actionButton.descEl;
importMessage.addClass("mod-warning");
if(this.pdfFile) {
search.setValue(this.pdfFile.path);
await setFile(this.pdfFile); //on drop if opened with a file
suggester.close();
pageRangesTextComponent.inputEl.focus();
} else {
search.inputEl.focus();
}
importButtonMessages();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,612 @@
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/types";
import { ColorComponent, Modal, Setting, SliderComponent, TextComponent, ToggleComponent } from "obsidian";
import { COLOR_NAMES, VIEW_TYPE_EXCALIDRAW } from "src/Constants";
import ExcalidrawView from "src/ExcalidrawView";
import ExcalidrawPlugin from "src/main";
import { setPen } from "src/menu/ObsidianMenu";
import { ExtendedFillStyle, PenStyle, PenType } from "src/PenTypes";
import { PENS } from "src/utils/Pens";
import { fragWithHTML, getExportPadding, getExportTheme, getPNGScale, getWithBackground } from "src/utils/Utils";
import { __values } from "tslib";
const EASINGFUNCTIONS: Record<string,string> = {
linear: "linear",
easeInQuad: "easeInQuad",
easeOutQuad: "easeOutQuad",
easeInOutQuad: "easeInOutQuad",
easeInCubic: "easeInCubic",
easeOutCubic: "easeOutCubic",
easeInOutCubic: "easeInOutCubic",
easeInQuart: "easeInQuart",
easeOutQuart: "easeOutQuart",
easeInOutQuart: "easeInOutQuart",
easeInQuint: "easeInQuint",
easeOutQuint: "easeOutQuint",
easeInOutQuint: "easeInOutQuint",
easeInSine: "easeInSine",
easeOutSine: "easeOutSine",
easeInOutSine: "easeInOutSine",
easeInExpo: "easeInExpo",
easeOutExpo: "easeOutExpo",
easeInOutExpo: "easeInOutExpo",
easeInCirc: "easeInCirc",
easeOutCirc: "easeOutCirc",
easeInOutCirc: "easeInOutCirc",
easeInBack: "easeInBack",
easeOutBack: "easeOutBack",
easeInOutBack: "easeInOutBack",
easeInElastic: "easeInElastic",
easeOutElastic: "easeOutElastic",
easeInOutElastic: "easeInOutElastic",
easeInBounce: "easeInBounce",
easeOutBounce: "easeOutBounce",
easeInOutBounce: "easeInOutBounce",
};
export class PenSettingsModal extends Modal {
private api: ExcalidrawImperativeAPI;
private dirty: boolean = false;
constructor(
private plugin: ExcalidrawPlugin,
private view: ExcalidrawView,
private pen: number,
) {
super(app);
this.api = view.excalidrawAPI;
}
onOpen(): void {
this.containerEl.classList.add("excalidraw-release");
this.titleEl.setText(`Pen Settings`);
this.createForm();
}
async onClose() {
if(this.dirty) {
app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW).forEach(v=> {
if (v.view instanceof ExcalidrawView) v.view.updatePinnedCustomPens()
})
this.plugin.saveSettings();
const pen = this.plugin.settings.customPens[this.pen]
const api = this.view.excalidrawAPI;
setPen(pen,api);
api.setActiveTool({type:"freedraw"});
}
}
async createForm() {
const hexColor = (color:string):[string,string] => {
let opacity = "";
if(COLOR_NAMES.has(color)) {
return [COLOR_NAMES.get(color),opacity];
}
const style = new Option().style;
style.color = color;
if(!!style.color) {
const digits = style.color.match(/^[^\d]*(\d*)[^\d]*(\d*)[^\d]*(\d*)[^\d]*([\d\.]*)?/);
if(!digits) {
return [null,opacity]
}
opacity = digits[4]
? (Math.round(parseFloat(digits[4])*255)<<0).toString(16).padStart(2,"0")
: "";
return [`#${
(parseInt(digits[1])<<0).toString(16).padStart(2,"0")}${
(parseInt(digits[2])<<0).toString(16).padStart(2,"0")}${
(parseInt(digits[3])<<0).toString(16).padStart(2,"0")}`,opacity]
}
return [null,opacity]
}
const ps = this.plugin.settings.customPens[this.pen]
const ce = this.contentEl;
ce.createEl("h1",{text: "Pen settings"});
new Setting(ce)
.setName("Pen type")
.setDesc("Select type of pen")
.addDropdown(dropdown => {
dropdown
.addOption("default", "Excalidraw Default")
.addOption("highlighter", "Highlighter")
.addOption("finetip", "Fine tip pen")
.addOption("fountain", "Fountain pen")
.addOption("marker", "Marker with Outline")
.addOption("thick-thin", "Mindmap Thick-Thin")
.addOption("thin-thick-thin", "Mindmap Thin-Thick-Thin")
.setValue(ps.type)
.onChange((value:PenType) => {
this.dirty = true;
ps.type = value;
})
})
.addButton(button =>
button
.setButtonText("Apply")
.onClick(()=> {
this.dirty = true;
ps.strokeColor = PENS[ps.type].strokeColor;
ps.backgroundColor = PENS[ps.type].backgroundColor;
ps.fillStyle = PENS[ps.type].fillStyle;
ps.strokeWidth = PENS[ps.type].strokeWidth;
ps.roughness = PENS[ps.type].roughness;
ps.penOptions = {...PENS[ps.type].penOptions};
ce.empty();
this.createForm();
})
)
let scopeSetting: Setting;
scopeSetting = new Setting(ce)
.setName(fragWithHTML(ps.freedrawOnly?"Stroke & fill applies to: <b>Freedraw only</b>":"Stroke & fill applies to: <b>All shapes</b>"))
.setDesc(fragWithHTML(`<b>"All shapes"</b> means that if for example, you select a blue pen with dashed fill and then switch to a different tool (e.g. to a line, a circle, an arrow - i.e. not the freedraw tool), those will all have the same blue line and dashed fill.<br><b>"Only applies to the freedraw line"</b> means that if for example you are writing black text, and you select a custom pen (e.g. a yellow highlighter), then after using the highlighter you switch to another tool, the previous settings (e.g. black stroke color) will apply to the new shape.`))
.addToggle(toggle =>
toggle
.setValue(ps.freedrawOnly)
.onChange(value => {
this.dirty = true;
scopeSetting.setName(fragWithHTML(value?"Stroke & fill applies to: <b>Freedraw only</b>":"Stroke & fill applies to: <b>All shapes</b>"))
ps.freedrawOnly = value;
})
)
let scSetting: Setting;
let sccpComponent: ColorComponent;
let sctComponent: TextComponent;
let strokeSetting: Setting;
let [sHex, sOpacity] = hexColor(ps.strokeColor);
let sChangeBounce:boolean = false;
strokeSetting = new Setting(ce)
.setName(fragWithHTML(!Boolean(ps.strokeColor) ? "Stroke color: <b>Current</b>" : "Stroke color: <b>Preset color</b>"))
.setDesc(fragWithHTML("Use <b>current</b> stroke color of the canvas, or set a specific <b>preset color</b> for the pen"))
.addToggle(toggle =>
toggle
.setValue(!Boolean(ps.strokeColor))
.onChange(value=> {
this.dirty = true;
scSetting.settingEl.style.display = value ? "none" : "";
strokeSetting.setName(fragWithHTML(value ? "Stroke color: <b>Current</b>" : "Stroke color: <b>Preset color</b>"))
if(value) {
delete ps.strokeColor;
} else {
if(!sctComponent.getValue()) {
[sHex,sOpacity] = hexColor("black");
sccpComponent.setValue(sHex)
sctComponent.setValue("black");
}
ps.strokeColor = sctComponent.getValue();
}
})
)
scSetting = new Setting(ce)
.setName("Select stroke color")
.addButton(button=>
button
.setButtonText("Use Canvas Current")
.onClick(()=>{
const st = this.api.getAppState();
const color = st.resetCustomPen?.currentItemStrokeColor ?? st.currentItemStrokeColor;
[sHex,sOpacity] = hexColor(color);
ps.strokeColor = color;
this.dirty = true;
sctComponent.setValue(color);
sChangeBounce = true;
sccpComponent.setValue(sHex);
})
)
.addText(text => {
sctComponent = text;
text
.setValue(ps.strokeColor)
.onChange(value=> {
sChangeBounce = true;
this.dirty = true;
ps.strokeColor = value;
[sHex,sOpacity] = hexColor(value);
if(sHex) sccpComponent.setValue(sHex);
})
})
.addColorPicker(colorpicker => {
sccpComponent = colorpicker;
colorpicker
.setValue(sHex ?? "#000000")
.onChange(value => {
if(sChangeBounce) {
sChangeBounce = false;
return;
}
this.dirty = true;
ps.strokeColor = value + sOpacity;
sctComponent.setValue(value + sOpacity);
})
}
)
scSetting.settingEl.style.display = !Boolean(ps.strokeColor) ? "none" : "";
let bgSetting: Setting;
let bgcSetting: Setting;
let bgctSetting: Setting;
let bgcpComponent: ColorComponent;
let bgctComponent: TextComponent;
let bgtComponent: ToggleComponent;
let fsSetting: Setting;
let [bgHex, bgOpacity] = hexColor(ps.backgroundColor);
bgSetting = new Setting(ce)
.setName(fragWithHTML(!Boolean(ps.backgroundColor) ? "Background color: <b>Current</b>" : "Background color: <b>Preset color</b>"))
.setDesc(fragWithHTML("Toggle to use the <b>current background color</b> of the canvas; or a <b>preset color</b>"))
.addToggle(toggle =>
toggle
.setValue(!Boolean(ps.backgroundColor))
.onChange(value=> {
this.dirty = true;
bgSetting.setName(fragWithHTML(value ? "Background color: <b>Current</b>" : "Background color: <b>Preset color</b>"))
bgctSetting.settingEl.style.display = value ? "none" : "";
bgcSetting.settingEl.style.display = (value || ps.backgroundColor==="transparent") ? "none" : "";
if(value) {
delete ps.backgroundColor;
} else {
if(!bgctComponent.getValue()) {
[bgHex, bgOpacity] = hexColor("black");
bgcpComponent.setValue(bgHex);
bgctComponent.setValue("black");
}
bgtComponent.setValue(false);
}
})
)
bgctSetting = new Setting(ce)
.setName(fragWithHTML(ps.backgroundColor==="transparent" ? "Background: <b>Transparent</b>" : "Color: <b>Preset color</b>"))
.setDesc("Background has color or is transparent")
.addToggle(toggle => {
bgtComponent = toggle;
toggle
.setValue(ps.backgroundColor==="transparent")
.onChange(value => {
this.dirty = true;
bgcSetting.settingEl.style.display = value ? "none" : "";
fsSetting.settingEl.style.display = value ? "none" : "";
bgctSetting.setName(fragWithHTML(value ? "Background: <b>Transparent</b>" : "Color: <b>Preset color</b>"))
ps.backgroundColor = value ? "transparent" : bgcpComponent.getValue();
})
}
)
bgctSetting.settingEl.style.display = !Boolean(ps.backgroundColor) ? "none" : "";
let bgChangeBounce:boolean = false;
bgcSetting = new Setting(ce)
.setName("Background color")
.addButton(button=>
button
.setButtonText("Use Canvas Current")
.onClick(()=>{
const st = this.api.getAppState();
const color = st.resetCustomPen?.currentItemBackgroundColor ?? st.currentItemBackgroundColor;
[bgHex,bgOpacity] = hexColor(color);
ps.backgroundColor = color;
this.dirty = true;
bgctComponent.setValue(color);
bgChangeBounce = true;
bgcpComponent.setValue(bgHex);
})
)
.addText(text => {
bgctComponent = text;
text
.setValue(ps.backgroundColor)
.onChange(value=> {
bgChangeBounce = true;
this.dirty = true;
ps.backgroundColor = value;
[bgHex,bgOpacity] = hexColor(value);
if(bgHex) bgcpComponent.setValue(bgHex);
})
})
.addColorPicker(colorpicker => {
bgcpComponent = colorpicker;
colorpicker
.setValue(bgHex ?? "#000000")
.onChange(value => {
if(bgChangeBounce) {
bgChangeBounce = false;
return;
}
this.dirty = true;
ps.backgroundColor = value+bgOpacity;
bgctComponent.setValue(value+bgOpacity)
})
})
bgcSetting.settingEl.style.display = (!Boolean(ps.backgroundColor) || ps.backgroundColor==="transparent") ? "none" : "";
fsSetting = new Setting(ce)
.setName("Fill Style")
.addDropdown(dropdown =>
dropdown
.addOption("","Unset")
.addOption("dots","Dots (⚠ VERY SLOW performance on large objects!)")
.addOption("zigzag","Zigzag")
.addOption("zigzag-line","Zigzag-line")
.addOption("dashed","Dashed")
.addOption("hachure","Hachure")
.addOption("cross-hatch","Cross-hatch")
.addOption("solid","Solid")
.setValue(ps.fillStyle)
.onChange((value: ExtendedFillStyle) => {
this.dirty = true;
ps.fillStyle = value;
})
)
fsSetting.settingEl.style.display = (!Boolean(ps.backgroundColor) || ps.backgroundColor==="transparent") ? "none" : "";
let rSetting: Setting;
rSetting = new Setting(ce)
.setName(fragWithHTML(`Sloppiness: <b>${ps.roughness === null ? "Not Set" : (ps.roughness<=0.5 ? "Architect (" : (ps.roughness <= 1.5 ? "Artist (" : "Cartoonist ("))}${ps.roughness === null ? "":`${ps.roughness})`}</b>`))
.setDesc("Line sloppiness of the shape fill pattern")
.addSlider(slider =>
slider
.setLimits(-0.5,3,0.5)
.setValue(ps.roughness === null ? -0.5 : ps.roughness)
.onChange(value => {
this.dirty = true;
ps.roughness = value === -0.5 ? null : value;
rSetting.setName(fragWithHTML(`Sloppiness: <b>${ps.roughness === null ? "Not Set" : (ps.roughness<=0.5 ? "Architect (" : (ps.roughness <= 1.5 ? "Artist (" : "Cartoonist ("))}${ps.roughness === null ? "":`${ps.roughness})`}</b>`));
})
)
let swSetting: Setting;
swSetting = new Setting(ce)
.setName(fragWithHTML(`Stroke Width <b>${ps.strokeWidth === 0 ? "Not Set" : ps.strokeWidth}</b>`))
.addSlider(slider =>
slider
.setLimits(0,5,0.5)
.setValue(ps.strokeWidth)
.onChange(value => {
this.dirty = true;
ps.strokeWidth = value;
swSetting.setName(fragWithHTML(`Stroke Width <b>${ps.strokeWidth === 0 ? "Not Set" : ps.strokeWidth}</b>`));
})
)
new Setting(ce)
.setName("Highlighter pen?")
.addToggle(toggle =>
toggle
.setValue(ps.penOptions.highlighter)
.onChange(value => {
this.dirty = true;
ps.penOptions.highlighter = value;
})
)
let spSetting: Setting;
new Setting(ce)
.setName("Pressure sensitve pen?")
.setDesc(fragWithHTML(`<b>toggle on</b>: pressure sensitive<br><b>toggle off</b>: constant pressure`))
.addToggle(toggle =>
toggle
.setValue(!ps.penOptions.constantPressure)
.onChange(value => {
this.dirty = true;
ps.penOptions.constantPressure = !value;
spSetting.settingEl.style.display = ps.penOptions.constantPressure ? "none" : "";
})
)
if(ps.penOptions.hasOutline && ps.penOptions.outlineWidth === 0) {
ps.penOptions.outlineWidth = 0.5;
this.dirty = true;
}
if(!ps.penOptions.hasOutline && ps.penOptions.outlineWidth > 0) {
ps.penOptions.outlineWidth = 0;
this.dirty = true;
}
let owSetting: Setting;
owSetting = new Setting(ce)
.setName(fragWithHTML(ps.penOptions.outlineWidth === 0 ? `No outline` : `Outline width <b>${ps.penOptions.outlineWidth}</b>`))
.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)
.setValue(ps.penOptions.outlineWidth)
.onChange(value => {
this.dirty = true;
ps.penOptions.outlineWidth = value;
ps.penOptions.hasOutline = value > 0;
owSetting.setName(fragWithHTML(ps.penOptions.outlineWidth === 0 ? `No outline` : `Outline width <b>${ps.penOptions.outlineWidth}</b>`));
})
)
ce.createEl("h2",{text: "Perfect Freehand settings"});
const p = ce.createEl("p");
p.innerHTML = `Read the Perfect Freehand documentation following <a href="https://github.com/steveruizok/perfect-freehand#documentation" target="_blank">this link</a>.`;
let tSetting: Setting;
tSetting = new Setting(ce)
.setName(fragWithHTML(`Thinnning <b>${ps.penOptions.options.thinning}</b>`))
.setDesc(fragWithHTML(`The effect of pressure on the stroke's size.<br>To create a stroke with a steady line, set the thinning option to 0.<br>To create a stroke that gets thinner with pressure instead of thicker, use a negative number for the thinning option.`))
.addSlider(slider =>
slider
.setLimits(-1,1,0.05)
.setValue(ps.penOptions.options.thinning)
.onChange(value=> {
this.dirty;
tSetting.setName(fragWithHTML(`Thinnning <b>${value}</b>`));
ps.penOptions.options.thinning = value;
})
)
let sSetting: Setting;
sSetting = new Setting(ce)
.setName(fragWithHTML(`Smoothing <b>${ps.penOptions.options.smoothing}</b>`))
.setDesc(fragWithHTML(`How much to soften the stroke's edges.`))
.addSlider(slider =>
slider
.setLimits(0,1,0.05)
.setValue(ps.penOptions.options.smoothing)
.onChange(value=> {
this.dirty;
sSetting.setName(fragWithHTML(`Smoothing <b>${value}</b>`));
ps.penOptions.options.smoothing = value;
})
)
let slSetting: Setting;
slSetting = new Setting(ce)
.setName(fragWithHTML(`Streamline <b>${ps.penOptions.options.streamline}</b>`))
.setDesc(fragWithHTML(` How much to streamline the stroke.`))
.addSlider(slider =>
slider
.setLimits(0,1,0.05)
.setValue(ps.penOptions.options.streamline)
.onChange(value=> {
this.dirty;
slSetting.setName(fragWithHTML(`Streamline <b>${value}</b>`));
ps.penOptions.options.streamline = value;
})
)
new Setting(ce)
.setName("Easing function")
.setDesc(fragWithHTML(`An easing function for the tapering effect. For more info <a href="https://easings.net/#" target="_blank">click here</a>`))
.addDropdown(dropdown =>
dropdown
.addOptions(EASINGFUNCTIONS)
.setValue(ps.penOptions.options.easing)
.onChange(value => {
this.dirty = true;
ps.penOptions.options.easing = value;
})
)
spSetting = new Setting(ce)
.setName("Simulate Pressure")
.setDesc("Whether to simulate pressure based on velocity.")
.addDropdown(dropdown =>
dropdown
.addOption("true","Always")
.addOption("false","Never")
.addOption("","Yes for mouse, No for pen")
.setValue(
ps.penOptions.options.simulatePressure === true
? "true"
: (ps.penOptions.options.simulatePressure === false
? "false"
: "")
)
.onChange(value=>{
this.dirty = true;
switch(value) {
case "true": ps.penOptions.options.simulatePressure = true; break;
case "false": ps.penOptions.options.simulatePressure = false; break;
default: delete ps.penOptions.options.simulatePressure;
}
})
)
spSetting.settingEl.style.display = ps.penOptions.constantPressure ? "none" : "";
ce.createEl("h3",{text: "Start"});
ce.createEl("p",{text: "Tapering options for the start of the line."})
new Setting(ce)
.setName("Cap Start")
.setDesc("Whether to draw a cap")
.addToggle(toggle=>
toggle
.setValue(ps.penOptions.options.start.cap)
.onChange(value=> {
this.dirty = true;
ps.penOptions.options.start.cap = value;
})
)
let stSetting: Setting;
stSetting = new Setting(ce)
.setName(fragWithHTML(`Taper: <b>${ps.penOptions.options.start.taper === true ? "true" : ps.penOptions.options.start.taper}</b>`))
.setDesc("The distance to taper. If set to true, the taper will be the total length of the stroke.")
.addSlider(slider=>
slider
.setLimits(0,151,1)
.setValue(typeof ps.penOptions.options.start.taper === "boolean" ? 151 : ps.penOptions.options.start.taper)
.onChange(value => {
this.dirty;
ps.penOptions.options.start.taper = value === 151 ? true : value;
stSetting.setName(fragWithHTML(`Taper: <b>${ps.penOptions.options.start.taper === true ? "true" : ps.penOptions.options.start.taper}</b>`));
})
)
new Setting(ce)
.setName("Easing function")
.setDesc(fragWithHTML(`An easing function for the tapering effect. For more info <a href="https://easings.net/#" target="_blank">click here</a>`))
.addDropdown(dropdown =>
dropdown
.addOptions(EASINGFUNCTIONS)
.setValue(ps.penOptions.options.start.easing)
.onChange(value => {
this.dirty = true;
ps.penOptions.options.start.easing = value;
})
)
ce.createEl("h3",{text: "End"});
ce.createEl("p",{text: "Tapering options for the end of the line."})
new Setting(ce)
.setName("Cap End")
.setDesc("Whether to draw a cap")
.addToggle(toggle=>
toggle
.setValue(ps.penOptions.options.end.cap)
.onChange(value=> {
this.dirty = true;
ps.penOptions.options.end.cap = value;
})
)
let etSetting: Setting;
etSetting = new Setting(ce)
.setName(fragWithHTML(`Taper: <b>${ps.penOptions.options.end.taper === true ? "true" : ps.penOptions.options.end.taper}</b>`))
.setDesc("The distance to taper. If set to true, the taper will be the total length of the stroke.")
.addSlider(slider=>
slider
.setLimits(0,151,1)
.setValue(typeof ps.penOptions.options.end.taper === "boolean" ? 151 : ps.penOptions.options.end.taper)
.onChange(value => {
this.dirty;
ps.penOptions.options.end.taper = value === 151 ? true : value;
etSetting.setName(fragWithHTML(`Taper: <b>${ps.penOptions.options.end.taper === true ? "true" : ps.penOptions.options.end.taper}</b>`));
})
)
new Setting(ce)
.setName("Easing function")
.setDesc(fragWithHTML(`An easing function for the tapering effect. For more info <a href="https://easings.net/#" target="_blank">click here</a>`))
.addDropdown(dropdown =>
dropdown
.addOptions(EASINGFUNCTIONS)
.setValue(ps.penOptions.options.end.easing)
.onChange(value => {
this.dirty = true;
ps.penOptions.options.end.easing = value;
})
)
}
}

View File

@@ -2,18 +2,21 @@ import {
App,
ButtonComponent,
Modal,
TextComponent,
FuzzyMatch,
FuzzySuggestModal,
Instruction,
TFile,
Notice,
TextAreaComponent,
} from "obsidian";
import ExcalidrawView from "../ExcalidrawView";
import ExcalidrawPlugin from "../main";
import { sleep } from "../utils/Utils";
import { getNewOrAdjacentLeaf } from "../utils/ObsidianUtils";
import { getLeaf } from "../utils/ObsidianUtils";
import { checkAndCreateFolder, splitFolderAndFilename } from "src/utils/FileUtils";
import { KeyEvent, isCTRL } from "src/utils/ModifierkeyHelper";
export type ButtonDefinition = { caption: string; tooltip?:string; action: Function };
export class Prompt extends Modal {
private promptEl: HTMLInputElement;
@@ -72,43 +75,75 @@ export class Prompt extends Modal {
export class GenericInputPrompt extends Modal {
public waitForClose: Promise<string>;
private view: ExcalidrawView;
private plugin: ExcalidrawPlugin;
private resolvePromise: (input: string) => void;
private rejectPromise: (reason?: any) => void;
private didSubmit: boolean = false;
private inputComponent: TextComponent;
private inputComponent: TextAreaComponent;
private input: string;
private buttons: [{ caption: string; action: Function }];
private buttons: ButtonDefinition[];
private lines: number = 1;
private displayEditorButtons: boolean = false;
private readonly placeholder: string;
private selectionStart: number = 0;
private selectionEnd: number = 0;
private selectionUpdateTimer: number = 0;
private customComponents: (container: HTMLElement) => void;
private blockPointerInputOutsideModal: boolean = false;
public static Prompt(
view: ExcalidrawView,
plugin: ExcalidrawPlugin,
app: App,
header: string,
placeholder?: string,
value?: string,
buttons?: [{ caption: string; action: Function }],
buttons?: ButtonDefinition[],
lines?: number,
displayEditorButtons?: boolean,
customComponents?: (container: HTMLElement) => void,
blockPointerInputOutsideModal?: boolean,
): Promise<string> {
const newPromptModal = new GenericInputPrompt(
view,
plugin,
app,
header,
placeholder,
value,
buttons,
lines,
displayEditorButtons,
customComponents,
blockPointerInputOutsideModal,
);
return newPromptModal.waitForClose;
}
protected constructor(
view: ExcalidrawView,
plugin: ExcalidrawPlugin,
app: App,
private header: string,
placeholder?: string,
value?: string,
buttons?: [{ caption: string; action: Function }],
buttons?: { caption: string; action: Function }[],
lines?: number,
displayEditorButtons?: boolean,
customComponents?: (container: HTMLElement) => void,
blockPointerInputOutsideModal?: boolean,
) {
super(app);
this.view = view;
this.plugin = plugin;
this.placeholder = placeholder;
this.input = value;
this.buttons = buttons;
this.lines = lines ?? 1;
this.displayEditorButtons = this.lines > 1 ? (displayEditorButtons ?? false) : false;
this.customComponents = customComponents;
this.blockPointerInputOutsideModal = blockPointerInputOutsideModal ?? false;
this.waitForClose = new Promise<string>((resolve, reject) => {
this.resolvePromise = resolve;
@@ -116,19 +151,27 @@ export class GenericInputPrompt extends Modal {
});
this.display();
this.inputComponent.inputEl.focus();
this.open();
}
private display() {
this.contentEl.empty();
if(this.blockPointerInputOutsideModal) {
//@ts-ignore
const bgEl = this.bgEl;
bgEl.style.pointerEvents = this.blockPointerInputOutsideModal ? "none" : "auto";
}
this.titleEl.textContent = this.header;
const mainContentContainer: HTMLDivElement = this.contentEl.createDiv();
this.inputComponent = this.createInputField(
mainContentContainer,
this.placeholder,
this.input,
this.input
);
this.customComponents?.(mainContentContainer);
this.createButtonBar(mainContentContainer);
}
@@ -137,15 +180,39 @@ export class GenericInputPrompt extends Modal {
placeholder?: string,
value?: string,
) {
const textComponent = new TextComponent(container);
const textComponent = new TextAreaComponent(container);
textComponent.inputEl.style.width = "100%";
textComponent.inputEl.style.height = `${this.lines*2}em`;
if(this.lines === 1) {
textComponent.inputEl.style.resize = "none";
textComponent.inputEl.style.overflow = "hidden";
}
textComponent
.setPlaceholder(placeholder ?? "")
.setValue(value ?? "")
.onChange((value) => (this.input = value))
.inputEl.addEventListener("keydown", this.submitEnterCallback);
.onChange((value) => (this.input = value));
let i = 0;
const checkcaret = () => {
//timer is implemented because on iPad with pencil the button click generates an event on the textarea
this.selectionUpdateTimer = this.view.ownerWindow.setTimeout(() => {
this.selectionStart = this.inputComponent.inputEl.selectionStart;
this.selectionEnd = this.inputComponent.inputEl.selectionEnd;
}, 30);
}
textComponent.inputEl.addEventListener("keydown", this.keyDownCallback);
textComponent.inputEl.addEventListener('keyup', checkcaret); // Every character written
textComponent.inputEl.addEventListener('pointerup', checkcaret); // Click down
textComponent.inputEl.addEventListener('touchend', checkcaret); // Click down
textComponent.inputEl.addEventListener('input', checkcaret); // Other input events
textComponent.inputEl.addEventListener('paste', checkcaret); // Clipboard actions
textComponent.inputEl.addEventListener('cut', checkcaret);
textComponent.inputEl.addEventListener('select', checkcaret); // Some browsers support this event
textComponent.inputEl.addEventListener('selectionchange', checkcaret);// Some browsers support this event
return textComponent;
}
@@ -153,18 +220,33 @@ export class GenericInputPrompt extends Modal {
container: HTMLElement,
text: string,
callback: (evt: MouseEvent) => any,
tooltip: string = "",
margin: string = "5px",
) {
const btn = new ButtonComponent(container);
btn.buttonEl.style.padding = "0.5em";
btn.buttonEl.style.marginLeft = margin;
btn.setTooltip(tooltip);
btn.setButtonText(text).onClick(callback);
return btn;
}
private createButtonBar(mainContentContainer: HTMLDivElement) {
const buttonBarContainer: HTMLDivElement = mainContentContainer.createDiv();
buttonBarContainer.style.display = "flex";
buttonBarContainer.style.justifyContent = "space-between";
buttonBarContainer.style.marginTop = "1rem";
const editorButtonContainer: HTMLDivElement = buttonBarContainer.createDiv();
const actionButtonContainer: HTMLDivElement = buttonBarContainer.createDiv();
if (this.buttons && this.buttons.length > 0) {
let b = null;
for (const button of this.buttons) {
const btn = new ButtonComponent(buttonBarContainer);
const btn = new ButtonComponent(actionButtonContainer);
btn.buttonEl.style.marginLeft="5px";
if(button.tooltip) btn.setTooltip(button.tooltip);
btn.setButtonText(button.caption).onClick((evt: MouseEvent) => {
const res = button.action(this.input);
if (res) {
@@ -175,31 +257,95 @@ export class GenericInputPrompt extends Modal {
b = b ?? btn;
}
if (b) {
b.setCta().buttonEl.style.marginRight = "0";
b.setCta();
b.buttonEl.style.marginRight = "0";
}
} else {
this.createButton(
buttonBarContainer,
"Ok",
actionButtonContainer,
"",
this.submitClickCallback,
).setCta().buttonEl.style.marginRight = "0";
}
this.createButton(buttonBarContainer, "Cancel", this.cancelClickCallback);
this.createButton(actionButtonContainer, "", this.cancelClickCallback, "Cancel");
if(this.displayEditorButtons) {
this.createButton(editorButtonContainer, "⏎", ()=>this.insertStringBtnClickCallback("\n"), "Insert new line", "0");
this.createButton(editorButtonContainer, "⌫", this.delBtnClickCallback, "Delete");
this.createButton(editorButtonContainer, "⎵", ()=>this.insertStringBtnClickCallback(" "), "Insert space");
if(this.view) {
this.createButton(editorButtonContainer, "🔗", this.linkBtnClickCallback, "Insert markdown link to file");
}
this.createButton(editorButtonContainer, "🔠", this.uppercaseBtnClickCallback, "Uppercase");
}
}
buttonBarContainer.style.display = "flex";
buttonBarContainer.style.flexDirection = "row-reverse";
buttonBarContainer.style.justifyContent = "flex-start";
buttonBarContainer.style.marginTop = "1rem";
private linkBtnClickCallback = () => {
this.view.ownerWindow.clearTimeout(this.selectionUpdateTimer); //timer is implemented because on iPad with pencil the button click generates an event on the textarea
const addText = (text: string) => {
const v = this.inputComponent.inputEl.value;
if(this.selectionStart>0 && v.slice(this.selectionStart-1, this.selectionStart) !== " ") text = " "+text;
if(this.selectionStart<v.length && v.slice(this.selectionStart, this.selectionStart+1) !== " ") text = text+" ";
const newVal = this.inputComponent.inputEl.value.slice(0, this.selectionStart) + text + this.inputComponent.inputEl.value.slice(this.selectionStart);
this.inputComponent.inputEl.value = newVal;
this.input = this.inputComponent.inputEl.value;
this.inputComponent.inputEl.focus();
this.selectionStart = this.selectionStart+text.length;
this.selectionEnd = this.selectionStart+text.length;
this.inputComponent.inputEl.setSelectionRange(this.selectionStart, this.selectionStart);
}
this.plugin.insertLinkDialog.start(this.view.file.path, addText);
}
private insertStringBtnClickCallback = (s: string) => {
this.view.ownerWindow.clearTimeout(this.selectionUpdateTimer); //timer is implemented because on iPad with pencil the button click generates an event on the textarea
const newVal = this.inputComponent.inputEl.value.slice(0, this.selectionStart) + s + this.inputComponent.inputEl.value.slice(this.selectionStart);
this.inputComponent.inputEl.value = newVal;
this.input = this.inputComponent.inputEl.value;
this.inputComponent.inputEl.focus();
this.selectionStart = this.selectionStart+1;
this.selectionEnd = this.selectionStart;
this.inputComponent.inputEl.setSelectionRange(this.selectionStart, this.selectionEnd);
}
private delBtnClickCallback = () => {
this.view.ownerWindow.clearTimeout(this.selectionUpdateTimer); //timer is implemented because on iPad with pencil the button click generates an event on the textarea
if(this.input.length === 0) return;
const delStart = this.selectionEnd > this.selectionStart
? this.selectionStart
: this.selectionStart > 0 ? this.selectionStart-1 : 0;
const delEnd = this.selectionEnd;
const newVal = this.inputComponent.inputEl.value.slice(0, delStart ) + this.inputComponent.inputEl.value.slice(delEnd);
this.inputComponent.inputEl.value = newVal;
this.input = this.inputComponent.inputEl.value;
this.inputComponent.inputEl.focus();
this.selectionStart = delStart;
this.selectionEnd = delStart;
this.inputComponent.inputEl.setSelectionRange(delStart, delStart);
}
private uppercaseBtnClickCallback = () => {
this.view.ownerWindow.clearTimeout(this.selectionUpdateTimer); //timer is implemented because on iPad with pencil the button click generates an event on the textarea
if(this.selectionEnd === this.selectionStart) return;
const newVal = this.inputComponent.inputEl.value.slice(0, this.selectionStart) + this.inputComponent.inputEl.value.slice(this.selectionStart, this.selectionEnd).toUpperCase() + this.inputComponent.inputEl.value.slice(this.selectionEnd);
this.inputComponent.inputEl.value = newVal;
this.input = this.inputComponent.inputEl.value;
this.inputComponent.inputEl.focus();
this.inputComponent.inputEl.setSelectionRange(this.selectionStart, this.selectionEnd);
}
private submitClickCallback = () => this.submit();
private cancelClickCallback = () => this.cancel();
private submitEnterCallback = (evt: KeyboardEvent) => {
if (evt.key === "Enter") {
private keyDownCallback = (evt: KeyboardEvent) => {
if ((evt.key === "Enter" && this.lines === 1) || (isCTRL(evt) && evt.key === "Enter")) {
evt.preventDefault();
this.submit();
}
if (this.displayEditorButtons && evt.key === "k" && isCTRL(evt)) {
evt.preventDefault();
this.linkBtnClickCallback();
}
};
private submit() {
@@ -222,13 +368,12 @@ export class GenericInputPrompt extends Modal {
private removeInputListener() {
this.inputComponent?.inputEl?.removeEventListener(
"keydown",
this.submitEnterCallback,
this.keyDownCallback,
);
}
onOpen() {
super.onOpen();
this.inputComponent.inputEl.focus();
this.inputComponent.inputEl.select();
}
@@ -370,8 +515,7 @@ export class NewFileActions extends Modal {
constructor(
private plugin: ExcalidrawPlugin,
private path: string,
private newPane: boolean,
private newWindow: boolean,
private keys: KeyEvent,
private view: ExcalidrawView,
) {
super(plugin.app);
@@ -387,14 +531,8 @@ export class NewFileActions extends Modal {
if (!file) {
return;
}
const leaf = this.newWindow
//@ts-ignore
? app.workspace.openPopoutLeaf()
: this.newPane
? getNewOrAdjacentLeaf(this.plugin, this.view.leaf)
: this.view.leaf;
const leaf = getLeaf(this.plugin,this.view.leaf,this.keys)
leaf.openFile(file, {active:true});
//this.app.workspace.setActiveLeaf(leaf, true, true);
}
createForm(): void {

View File

@@ -35,7 +35,7 @@ export class ReleaseNotes extends Modal {
const message = this.version
? Object.keys(RELEASE_NOTES)
.filter((key) => key === "Intro" || isVersionNewerThanOther(key,prevRelease))
.map((key: string) => `# ${key}\n${RELEASE_NOTES[key]}`)
.map((key: string) => `${key==="Intro" ? "" : `# ${key}\n`}${RELEASE_NOTES[key]}`)
.slice(0, 10)
.join("\n\n---\n")
: FIRST_RUN;

View File

@@ -73,9 +73,9 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
after: "",
},
{
field: "style.strokeSharpness",
code: "[string]",
desc: "'round' | 'sharp'",
field: "style.roundness",
code: "[null | { type: RoundnessType; value?: number };]",
desc: "set to null for 'sharp', else the stroke will be 'round'<br>type: 1==LEGACY,<br>2==PROPORTIONAL RADIUS,<br>3==ADAPTIVE RADIUS, value: adaptive factor defaults to 32",
after: "",
},
{
@@ -132,6 +132,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: null,
after: "",
},
{
field: "setStrokeSharpness",
code: "setStrokeSharpness(sharpness: number): void;",
desc: "Set ea.style.roundness. 0: is the legacy value, 3: is the current default value, null is sharp",
after: "",
},
{
field: "addToGroup",
code: "addToGroup(objectIds: []): string;",
@@ -139,7 +145,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
after: "",
},
{
field: "toCliboard",
field: "toClipboard",
code: "toClipboard(templatePath?: string): void;",
desc: "Copies current elements using template to clipboard, ready to be pasted into an excalidraw canvas",
after: "",
@@ -204,9 +210,15 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: null,
after: "",
},
{
field: "refreshTextElementSize",
code: 'refreshTextElementSize(id: string);',
desc: "Refreshes the size of the text element. Intended to be used when you copyViewElementsToEAforEditing() and then change the text in a text element and want to update the size of the text element to fit the modifid contents.",
after: "",
},
{
field: "addText",
code: 'addText(topX: number, topY: number, text: string, formatting?: {wrapAt?: number; width?: number; height?: number; textAlign?: string; box?: boolean | "box" | "blob" | "ellipse" | "diamond"; boxPadding?: number;}, id?: string,): string;',
code: 'addText(topX: number, topY: number, text: string, formatting?: {wrapAt?: number; width?: number; height?: number; textAlign?: "left" | "center" | "right"; textVerticalAlign: "top" | "middle" | "bottom"; box?: boolean | "box" | "blob" | "ellipse" | "diamond"; boxPadding?: number; boxStrokeColor?: string;}, id?: string,): string;',
desc: "If box is !null, then text will be boxed\nThe function returns the id of the TextElement. If the text element is boxed i.e. it is a sticky note, then the id of the container object",
after: "",
},
@@ -224,8 +236,8 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "addImage",
code: "addImage(topX: number, topY: number, imageFile: TFile): Promise<string>;",
desc: null,
code: "addImage(topX: number, topY: number, imageFile: TFile, scale: boolean): Promise<string>;",
desc: "set scale to false if you want to embed the image at 100% of its original size. Default is true which will insert a scaled image",
after: "",
},
{
@@ -486,14 +498,41 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "Converts a CSS color name to its HEX color equivalent. 'White' to #FFFFFF",
after: "",
},
{
field: "obsidian",
code: "obsidian",
desc: "Access functions and objects available on the <a onclick='window.open(\"https://github.com/obsidianmd/obsidian-api/blob/master/obsidian.d.ts\")'>Obsidian Module</a>",
after: "",
},
{
field: "setViewModeEnabled",
code: "setViewModeEnabled(enabled: boolean): void;",
desc: "Sets Excalidraw in the targetView to view-mode",
after: "",
},
{
field: "viewUpdateScene",
code: "viewUpdateScene(scene:{elements?:ExcalidrawElement[],appState?: AppState,files?: BinaryFileData,commitToHistory?: boolean,},restore:boolean=false):void",
desc: "Calls the ExcalidrawAPI updateScene function for the targetView. When restore=true, excalidraw will try to correct errors in the scene such as setting default values to missing element properties.",
after: "",
},
{
field: "viewZoomToElements",
code: "viewZoomToElements(selectElements: boolean,elements: ExcalidrawElement[]):void",
desc: "Zoom tarteView to fit elements provided as input. elements === [] will zoom to fit the entire scene. SelectElements toggles whether the elements should be in a selected state at the end of the operation.",
after: "",
},
];
export const EXCALIDRAW_SCRIPTENGINE_INFO: SuggesterInfo[] = [
{
field: "inputPrompt",
code: "inputPrompt: (header: string, placeholder?: string, value?: string, buttons?: [{caption:string, action:Function}]);",
code: "inputPrompt: (header: string, placeholder?: string, value?: string, buttons?: {caption:string, tooltip?:string, action:Function}[], lines?: number, displayEditorButtons?: boolean, customComponents?: (container: HTMLElement) => void, blockPointerInputOutsideModal?: boolean);",
desc:
"Opens a prompt that asks for an input.\nReturns a string with the input.\nYou need to await the result of inputPrompt.\n" +
"Editor buttons are text editing buttons like delete, enter, allcaps - these are only displayed if lines is greater than 1 \n" +
"Custom components are components that you can add to the prompt. These will be displayed between the text input area and the buttons.\n" +
"blockPointerInputOutsideModal will block pointer input outside the modal. This is useful if you want to prevent the user accidently closing the modal or interacting with the excalidraw canvas while the prompt is open.\n" +
"buttons.action(input: string) => string\nThe button action function will receive the actual input string. If action returns null, input will be unchanged. If action returns a string, input will receive that value when the promise is resolved. " +
"example:\n<code>let fileType = '';\nconst filename = await utils.inputPrompt (\n 'Filename',\n '',\n '',\n, [\n {\n caption: 'Markdown',\n action: ()=>{fileType='md';return;}\n },\n {\n caption: 'Excalidraw',\n action: ()=>{fileType='ex';return;}\n }\n ]\n);</code>",
after: "",
@@ -504,6 +543,12 @@ export const EXCALIDRAW_SCRIPTENGINE_INFO: SuggesterInfo[] = [
desc: "Opens a suggester. Displays the displayItems and returns the corresponding item from items[]\nYou need to await the result of suggester.\nIf the user cancels (ESC), suggester will return undefined\nHint and instructions are optional\n\n<code>interface Instruction {command: string;purpose: string;}</code>",
after: "",
},
{
field: "scriptFile",
code: "scriptFile: TFile",
desc: "The TFile of the currently running script",
after: "",
},
];
export const FRONTMATTER_KEYS_INFO: SuggesterInfo[] = [

View File

@@ -1,7 +1,7 @@
import "obsidian";
//import { ExcalidrawAutomate } from "./ExcalidrawAutomate";
export {ExcalidrawAutomateInterface} from "./types";
export type { ExcalidrawBindableElement, ExcalidrawElement, FileId, FillStyle, StrokeSharpness, StrokeStyle } from "@zsviczian/excalidraw/types/element/types";
export type { ExcalidrawBindableElement, ExcalidrawElement, FileId, FillStyle, StrokeRoundness, StrokeStyle } from "@zsviczian/excalidraw/types/element/types";
export type { Point } from "@zsviczian/excalidraw/types/types";
export const getEA = (view?:any): any => {
try {

View File

@@ -1,48 +1,55 @@
import {
DEVICE,
FRONTMATTER_KEY_CUSTOM_LINK_BRACKETS,
FRONTMATTER_KEY_CUSTOM_PREFIX,
FRONTMATTER_KEY_CUSTOM_URL_PREFIX,
} from "src/Constants";
import { labelALT, labelCTRL, labelMETA, labelSHIFT } from "src/utils/ModifierkeyHelper";
// English
export default {
// main.ts
INSTALL_SCRIPT: "Install this script",
UPDATE_SCRIPT: "An update is available - Click to install",
INSTALL_SCRIPT: "Install the script",
UPDATE_SCRIPT: "Update available - Click to install",
CHECKING_SCRIPT:
"Checking if a newer version is available - Click to reinstall now",
"Checking for newer version - Click to reinstall",
UNABLETOCHECK_SCRIPT:
"Update check was unsuccessful - Click to reinstall now",
"Update check failed - Click to reinstall",
UPTODATE_SCRIPT:
"Script is installed and up to date - Click to reinstall now",
"Script is up to date - Click to reinstall",
OPEN_AS_EXCALIDRAW: "Open as Excalidraw Drawing",
TOGGLE_MODE: "Toggle between Excalidraw and Markdown mode",
CONVERT_NOTE_TO_EXCALIDRAW: "Convert empty note to Excalidraw Drawing",
CONVERT_EXCALIDRAW: "Convert *.excalidraw to *.md files",
CREATE_NEW: "New Excalidraw drawing",
CREATE_NEW: "Create new drawing",
CONVERT_FILE_KEEP_EXT: "*.excalidraw => *.excalidraw.md",
CONVERT_FILE_REPLACE_EXT: "*.excalidraw => *.md (Logseq compatibility)",
DOWNLOAD_LIBRARY: "Export stencil library as an *.excalidrawlib file",
OPEN_EXISTING_NEW_PANE: "Open an existing drawing - IN A NEW PANE",
OPEN_EXISTING_NEW_PANE: "Open existing drawing - IN A NEW PANE",
OPEN_EXISTING_ACTIVE_PANE:
"Open an existing drawing - IN THE CURRENT ACTIVE PANE",
TRANSCLUDE: "Transclude (embed) a drawing",
TRANSCLUDE_MOST_RECENT: "Transclude (embed) the most recently edited drawing",
"Open existing drawing - IN THE CURRENT ACTIVE PANE",
TRANSCLUDE: "Embed a drawing",
TRANSCLUDE_MOST_RECENT: "Embed the most recently edited drawing",
TOGGLE_LEFTHANDED_MODE: "Toggle left-handed mode",
NEW_IN_NEW_PANE: "Create a new drawing - IN A NEW PANE",
NEW_IN_ACTIVE_PANE: "Create a new drawing - IN THE CURRENT ACTIVE PANE",
NEW_IN_POPOUT_WINDOW: "Create a new drawing - IN A POPOUT WINDOW",
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",
NEW_IN_POPOUT_WINDOW: "Create new drawing - IN A POPOUT WINDOW",
NEW_IN_NEW_PANE_EMBED:
"Create a new drawing - IN A NEW PANE - and embed into active document",
"Create new drawing - IN AN ADJACENT WINDOW - and embed into active document",
NEW_IN_NEW_TAB_EMBED:
"Create new drawing - IN A NEW TAB - and embed into active document",
NEW_IN_ACTIVE_PANE_EMBED:
"Create a new drawing - IN THE CURRENT ACTIVE PANE - and embed into active document",
NEW_IN_POPOUT_WINDOW_EMBED: "Create a new drawing - IN A POPOUT WINDOW - and embed into active document",
EXPORT_SVG: "Save as SVG next to the current file",
EXPORT_PNG: "Save as PNG next to the current file",
TOGGLE_LOCK: "Toggle Text Element edit RAW/PREVIEW",
DELETE_FILE: "Delete selected Image or Markdown file from Obsidian Vault",
"Create new drawing - IN THE CURRENT ACTIVE WINDOW - and embed into active document",
NEW_IN_POPOUT_WINDOW_EMBED: "Create new drawing - IN A POPOUT WINDOW - and embed into active document",
EXPORT_SVG: "Save as SVG next to current file",
EXPORT_PNG: "Save as PNG next to current file",
EXPORT_SVG_WITH_SCENE: "Save as SVG with embedded Excalidraw Scene next to current file",
EXPORT_PNG_WITH_SCENE: "Save as PNG with embedded Excalidraw Scene next to current file",
TOGGLE_LOCK: "Toggle Text Element between edit RAW and PREVIEW",
DELETE_FILE: "Delete selected image or Markdown file from Obsidian Vault",
INSERT_LINK_TO_ELEMENT:
"Copy markdown link for selected element to clipboard. CTRL/CMD+Click to copy group link. SHIFT+click to copy an area link.",
`Copy markdown link for selected element to clipboard. ${labelCTRL()}+CLICK to copy 'group=' link. ${labelSHIFT()}+CLICK to copy an 'area=' link. ${labelALT()}+CLICK to watch a help video.`,
INSERT_LINK_TO_ELEMENT_GROUP:
"Copy 'group=' markdown link for selected element to clipboard.",
INSERT_LINK_TO_ELEMENT_AREA:
@@ -55,10 +62,12 @@ export default {
INSERT_IMAGE: "Insert image or Excalidraw drawing from your vault",
IMPORT_SVG: "Import an SVG file as Excalidraw strokes (limited SVG support, TEXT currently not supported)",
INSERT_MD: "Insert markdown file from vault",
INSERT_PDF: "Insert PDF file from vault",
INSERT_LATEX:
"Insert LaTeX formula (e.g. \\binom{n}{k} = \\frac{n!}{k!(n-k)!})",
`Insert LaTeX formula (e.g. \\binom{n}{k} = \\frac{n!}{k!(n-k)!}). ${labelALT()}+CLICK to watch a help video.`,
ENTER_LATEX: "Enter a valid LaTeX expression",
READ_RELEASE_NOTES: "Read latest release notes",
RUN_OCR: "OCR: Grab text from freedraw scribble and pictures to clipboard",
TRAY_MODE: "Toggle property-panel tray-mode",
SEARCH: "Search for text in drawing",
RESET_IMG_TO_100: "Set selected image element size to 100% of original",
@@ -68,18 +77,14 @@ export default {
//ExcalidrawView.ts
INSTALL_SCRIPT_BUTTON: "Install or update Excalidraw Scripts",
OPEN_AS_MD: "Open as Markdown",
SAVE_AS_PNG: "Save as PNG into Vault (CTRL/CMD+CLICK to export)",
SAVE_AS_SVG: "Save as SVG into Vault (CTRL/CMD+CLICK to export)",
SAVE_AS_PNG: `Save as PNG into Vault (${labelCTRL()}+CLICK to export; SHIFT to embed scene)`,
SAVE_AS_SVG: `Save as SVG into Vault (${labelCTRL()}+CLICK to export; SHIFT to embed scene)`,
OPEN_LINK: "Open selected text as link\n(SHIFT+CLICK to open in a new pane)",
EXPORT_EXCALIDRAW: "Export to an .Excalidraw file",
LINK_BUTTON_CLICK_NO_TEXT:
"Select a an ImageElement, or select a TextElement that contains an internal or external link.\n" +
"SHIFT CLICK this button to open the link in a new pane.\n" +
"CTRL/CMD CLICK the Image or TextElement on the canvas has the same effect!",
"Select a ImageElement, or select a TextElement that contains an internal or external link.\n",
FILENAME_INVALID_CHARS:
'File name cannot contain any of the following characters: * " \\ < > : | ? #',
FILE_DOES_NOT_EXIST:
"File does not exist. Hold down ALT (or ALT+SHIFT) and CLICK link button to create a new file.",
FORCE_SAVE:
"Save (will also update transclusions)",
RAW: "Change to PREVIEW mode (only effects text-elements with links or transclusions)",
@@ -97,7 +102,7 @@ export default {
"<b>Toggle OFF:</b> Silent mode. You can still read release notes on <a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/releases'>GitHub</a>.",
NEWVERSION_NOTIFICATION_NAME: "Plugin update notification",
NEWVERSION_NOTIFICATION_DESC:
"<b>Toggle ON:</b> Show a notification when a new version of the plugin is avaiable.<br>" +
"<b>Toggle ON:</b> Show a notification when a new version of the plugin is available.<br>" +
"<b>Toggle OFF:</b> Silent mode. You need to check for plugin updates in Community Plugins.",
FOLDER_NAME: "Excalidraw folder",
@@ -108,11 +113,11 @@ export default {
FOLDER_EMBED_DESC:
"Define which folder to place the newly inserted drawing into " +
"when using the command palette action: 'Create a new drawing and embed into active document'.<br>" +
"<b>Toggle ON:</b> Use Excalidraw folder<br><b>Toggle OFF:</b> use the attachments folder defined in Obsidian settings.",
"<b>Toggle ON:</b> Use Excalidraw folder<br><b>Toggle OFF:</b> Use the attachments folder defined in Obsidian settings.",
TEMPLATE_NAME: "Excalidraw template file",
TEMPLATE_DESC:
"Full filepath to the Excalidraw template. " +
"E.g.: If your template is in the default Excalidraw folder and it's name is " +
"E.g.: If your template is in the default Excalidraw folder and its name is " +
"Template.md, the setting would be: Excalidraw/Template.md (or just Excalidraw/Template - you may omit the .md file extension). " +
"If you are using Excalidraw in compatibility mode, then your template must be a legacy Excalidraw file as well " +
"such as Excalidraw/Template.excalidraw.",
@@ -122,6 +127,7 @@ export default {
"You can access your scripts from Excalidraw via the Obsidian Command Palette. Assign " +
"hotkeys to your favorite scripts just like to any other Obsidian command. " +
"The folder may not be the root folder of your Vault. ",
SAVING_HEAD: "Saving",
COMPRESS_NAME: "Compress Excalidraw JSON in Markdown",
COMPRESS_DESC:
"By enabling this feature Excalidraw will store the drawing JSON in a Base64 compressed " +
@@ -133,15 +139,18 @@ export default {
"once you switch back to Excalidraw view. " +
"The setting only has effect 'point forward', meaning, existing drawings will not be effected by the setting " +
"until you open them and save them.<br><b>Toggle ON:</b> Compress drawing JSON<br><b>Toggle OFF:</b> Leave drawing JSON uncompressed",
AUTOSAVE_NAME: "Enable Autosave",
AUTOSAVE_DESC:
"Automatically save the active drawing, in case there are changes, every 15, 30 seconds, or 1, 2, 3, 4, or 5 minute. Save normally happens when you close Excalidraw or Obsidian, or move " +
"focus to another pane. I created this feature with mobile " +
"phones and tablets in mind, where 'swiping out Obsidian to close it' led to some data loss.",
AUTOSAVE_INTERVAL_NAME: "Interval for autosave",
AUTOSAVE_INTERVAL_DESC:
"The time interval between saves. Autosave will skip if there are no changes in the drawing.",
FILENAME_HEAD: "Filename",
AUTOSAVE_INTERVAL_DESKTOP_NAME: "Interval for autosave on Desktop",
AUTOSAVE_INTERVAL_DESKTOP_DESC:
"The time interval between saves. Autosave will skip if there are no changes in the drawing. " +
"Excalidraw will also save the file when closing a workspace tab or navigating within Obsidian, but away from the active Excalidraw tab (i.e. clicking on the Obsidian ribbon or checking backlinks, etc.). " +
"Excalidraw will not be able to save your work when terminating Obsidian directly either by killing the Obsidian process, or clicking to close Obsidian altogether.",
AUTOSAVE_INTERVAL_MOBILE_NAME: "Interval for autosave on Mobile",
AUTOSAVE_INTERVAL_MOBILE_DESC:
"I recommend a more frequent interval for Mobiles. " +
"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_DESC:
"<p>Click this link for the <a href='https://momentjs.com/docs/#/displaying/format/'>" +
"date and time format reference</a>.</p>",
@@ -158,7 +167,7 @@ export default {
FILENAME_POSTFIX_NAME:
"Custom text after markdown Note's name when embedding",
FILENAME_POSTFIX_DESC:
"Effects filename only when embedding into a markdown document. This is text will be inserted after the note's name, but before the date.",
"Effects filename only when embedding into a markdown document. This text will be inserted after the note's name, but before the date.",
FILENAME_DATE_NAME: "Filename Date",
FILENAME_DATE_DESC:
"The last part of the filename. Leave empty if you do not want a date.",
@@ -167,6 +176,9 @@ export default {
"This setting does not apply if you use Excalidraw in compatibility mode, " +
"i.e. you are not using Excalidraw markdown files.<br><b>Toggle ON:</b> filename ends with .excalidraw.md<br><b>Toggle OFF:</b> filename ends with .md",
DISPLAY_HEAD: "Display",
DYNAMICSTYLE_NAME: "Dynamic styling",
DYNAMICSTYLE_DESC:
"Change Excalidraw UI colors to match the canvas color",
LEFTHANDED_MODE_NAME: "Left-handed mode",
LEFTHANDED_MODE_DESC:
"Currently only has effect in tray-mode. If turned on, the tray will be on the right side." +
@@ -175,7 +187,7 @@ export default {
MATCH_THEME_DESC:
"If theme is dark, new drawing will be created in dark mode. This does not apply when you use a template for new drawings. " +
"Also this will not effect when you open an existing drawing. Those will follow the theme of the template/drawing respectively." +
"<br><b>Toggle ON:</b> Follow Obsidian Theme<br><b>Toggle OFF:</b>Follow theme defined in your template",
"<br><b>Toggle ON:</b> Follow Obsidian Theme<br><b>Toggle OFF:</b> Follow theme defined in your template",
MATCH_THEME_ALWAYS_NAME: "Existing drawings to match Obsidian theme",
MATCH_THEME_ALWAYS_DESC:
"If theme is dark, drawings will be opened in dark mode. If your theme is light, they will be opened in light mode. " +
@@ -187,19 +199,32 @@ export default {
DEFAULT_OPEN_MODE_NAME: "Default mode when opening Excalidraw",
DEFAULT_OPEN_MODE_DESC:
"Specifies the mode how Excalidraw opens: Normal, Zen, or View mode. You may also set this behavior on a file level by " +
"adding the excalidraw-default-mode frontmatter key with a value of: normal,view, or zen to your document.",
"adding the excalidraw-default-mode frontmatter key with a value of: normal, view, or zen to your document.",
DEFAULT_PEN_MODE_NAME: "Pen mode",
DEFAULT_PEN_MODE_DESC:
"Should pen mode be automatically enabled when opening Excalidraw?",
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>" +
"<b>Toggle on: </b>Enable pinch zoom in pen mode<br><b>Toggle off: </b>Disable pinch zoom in pen mode",
DEFAULT_WHEELZOOM_NAME: "Mouse wheel to zoom by default",
DEFAULT_WHEELZOOM_DESC:
`<b>Toggle on: </b>Mouse wheel to zoom; ${labelCTRL()} + mouse wheel to scroll</br><b>Toggle off: </b>${labelCTRL()} + mouse wheel to zoom; Mouse wheel to scroll`,
ZOOM_TO_FIT_NAME: "Zoom to fit on view resize",
ZOOM_TO_FIT_DESC: "Zoom to fit drawing when the pane is resized" +
"<br><b>Toggle ON:</b> Zoom to fit<br><b>Toggle OFF:</b> Auto zoom disabled",
ZOOM_TO_FIT_ONOPEN_NAME: "Zoom to fit on file open",
ZOOM_TO_FIT_ONOPEN_DESC: "Zoom to fit drawing when the drawing is first opened" +
"<br><b>Toggle ON:</b> Zoom to fit<br><b>Toggle OFF:</b> Auto zoom disabled",
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%).",
LINKS_HEAD: "Links and transclusion",
LINKS_DESC:
"CTRL/CMD + CLICK on <code>[[Text Elements]]</code> to open them as links. " +
`${labelCTRL()}+CLICK on <code>[[Text Elements]]</code> to open them as links. ` +
"If the selected text has more than one <code>[[valid Obsidian links]]</code>, only the first will be opened. " +
"If the text starts as a valid web link (i.e. <code>https://</code> or <code>http://</code>), then " +
"the plugin will open it in a browser. " +
@@ -207,13 +232,13 @@ export default {
"If you don't want text accidentally changing in your drawings use <code>[[links|with aliases]]</code>.",
ADJACENT_PANE_NAME: "Open in adjacent pane",
ADJACENT_PANE_DESC:
"When CTRL/CMD+SHIFT clicking a link in Excalidraw, by default the plugin will open the link in a new pane. " +
`When ${labelCTRL()}+${labelSHIFT()} clicking a link in Excalidraw, by default the plugin will open the link in a new pane. ` +
"Turning this setting on, Excalidraw will first look for an existing adjacent pane, and try to open the link there. " +
"Excalidraw will look for the adjacent pane based on your focus/navigation history, i.e. the workpane that was active before you " +
"activated Excalidraw.",
MAINWORKSPACE_PANE_NAME: "Open in main workspace",
MAINWORKSPACE_PANE_DESC:
"When CTRL/CMD+SHIFT clicking a link in Excalidraw, by default the plugin will open the link in a new pane in the current active window. " +
`When ${labelCTRL()}+${labelSHIFT()} clicking a link in Excalidraw, by default the plugin will open the link in a new pane in the current active window. ` +
"Turning this setting on, Excalidraw will open the link in an existing or new pane in the main workspace. ",
LINK_BRACKETS_NAME: "Show <code>[[brackets]]</code> around links",
LINK_BRACKETS_DESC: `${
@@ -236,16 +261,16 @@ export default {
TODO_DESC: "Icon to use for open TODO items",
DONE_NAME: "Completed TODO icon",
DONE_DESC: "Icon to use for completed TODO items",
HOVERPREVIEW_NAME: "Hover preview without CTRL/CMD key",
HOVERPREVIEW_NAME: `Hover preview without pressing the ${labelCTRL()} key`,
HOVERPREVIEW_DESC:
"<b>Toggle On</b>: In Exalidraw <u>view mode</u> the hover preview for [[wiki links]] will be shown immediately, without the need to hold the CTRL/CMD key. " +
`<b>Toggle On</b>: In Exalidraw <u>view mode</u> the hover preview for [[wiki links]] will be shown immediately, without the need to hold the ${labelCTRL()} key. ` +
"In Excalidraw <u>normal mode</u>, the preview will be shown immediately only when hovering the blue link icon in the top right of the element.<br> " +
"<b>Toggle Off</b>: Hover preview is shown only when you hold the CTRL/CMD key while hovering the link.",
`<b>Toggle Off</b>: Hover preview is shown only when you hold the ${labelCTRL()} key while hovering the link.`,
LINKOPACITY_NAME: "Opacity of link icon",
LINKOPACITY_DESC:
"Opacity of the link indicator icon in the top right corner of an element. 1 is opaque, 0 is transparent.",
LINK_CTRL_CLICK_NAME:
"CTRL/CMD + CLICK on text with [[links]] or [](links) to open them",
`${labelCTRL()}+CLICK on text with [[links]] or [](links) to open them`,
LINK_CTRL_CLICK_DESC:
"You can turn this feature off if it interferes with default Excalidraw features you want to use. If " +
"this is turned off, only the link button in the title bar of the drawing pane will open links.",
@@ -256,7 +281,7 @@ export default {
"text (i.e. no overflow), or OFF to soft-wrap text (at the nearest whitespace).",
TRANSCLUSION_DEFAULT_WRAP_NAME: "Transclusion word wrap default",
TRANSCLUSION_DEFAULT_WRAP_DESC:
"You can set manually set/override word wrapping length using the `![[page#^block]]{NUMBER}` format. " +
"You can manually set/override word wrapping length using the `![[page#^block]]{NUMBER}` format. " +
"Normally you will not want to set a default, because if you transclude text inside a sticky note, then Excalidraw will automatically take care of word wrapping. " +
"Set this value to `0` if you do not want to set a default. ",
PAGE_TRANSCLUSION_CHARCOUNT_NAME: "Page transclusion max char count",
@@ -264,14 +289,14 @@ export default {
"The maximum number of characters to display from the page when transcluding an entire page with the " +
"![[markdown page]] format.",
QUOTE_TRANSCLUSION_REMOVE_NAME: "Quote translusion: remove leading '> ' from each line",
QUOTE_TRANSCLUSION_REMOVE_DESC: "Remove the leading '> ' from each line of the transclusion. This will improve readibility of quotes in text only transclusions<br>" +
QUOTE_TRANSCLUSION_REMOVE_DESC: "Remove the leading '> ' from each line of the transclusion. This will improve readability of quotes in text only transclusions<br>" +
"<b>Toggle ON:</b> Remove leading '> '<br><b>Toggle OFF:</b> Do not remove leading '> ' (note it will still be removed from the first row due to Obsidian API functionality)",
GET_URL_TITLE_NAME: "Use iframely to resolve page title",
GET_URL_TITLE_DESC:
"Use the <code>http://iframely.server.crestify.com/iframely?url=</code> to get title of page when dropping a link into Excalidraw",
MD_HEAD: "Markdown-embed settings",
MD_HEAD_DESC:
"You can transclude formatted markdown documents into drawings as images CTRL(Shift on Mac) drop from the file explorer or using " +
`You can transclude formatted markdown documents into drawings as images ${labelSHIFT()} drop from the file explorer or using ` +
"the command palette action.",
MD_TRANSCLUDE_WIDTH_NAME: "Default width of a transcluded markdown document",
MD_TRANSCLUDE_WIDTH_DESC:
@@ -303,7 +328,7 @@ export default {
MD_CSS_DESC:
"The filename of the CSS to apply to markdown embeds. Provide the filename with extension (e.g. 'md-embed.css'). The css file may also be a plain " +
"markdown file (e.g. 'md-embed-css.md'), just make sure the content is written using valid css syntax. " +
"If you need to look at the HTML code you are applying the CSS to, then open Obsidian Developer Console (CTRL+SHIFT+i) and type in the following command: " +
`If you need to look at the HTML code you are applying the CSS to, then open Obsidian Developer Console (${DEVICE.isIOS || DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"}) and type in the following command: ` +
'"ExcalidrawAutomate.mostRecentMarkdownSVG". This will display the most recent SVG generated by Excalidraw. ' +
"Setting the font-family in the css is has limitations. By default only your operating system's standard fonts are available (see README for details). " +
"You can add one custom font beyond that using the setting above. " +
@@ -320,7 +345,7 @@ export default {
EMBED_PREVIEW_SVG_NAME: "Display SVG in markdown preview",
EMBED_PREVIEW_SVG_DESC:
"<b>Toggle ON</b>: Embed drawing as an <a href='https://en.wikipedia.org/wiki/Scalable_Vector_Graphics' target='_blank'>SVG</a> image into the markdown preview.<br>" +
"<b>Toggle OFF</b>: Embedd drawing as a <a href='' target='_blank'>PNG</a> image. Note, that some of the <a href='https://www.youtube.com/watch?v=yZQoJg2RCKI&t=633s' target='_blank'>image block referencing features</a> do not work with PNG embeds.",
"<b>Toggle OFF</b>: Embed drawing as a <a href='' target='_blank'>PNG</a> image. Note, that some of the <a href='https://www.youtube.com/watch?v=yZQoJg2RCKI&t=633s' target='_blank'>image block referencing features</a> do not work with PNG embeds.",
PREVIEW_MATCH_OBSIDIAN_NAME: "Excalidraw preview to match Obsidian theme",
PREVIEW_MATCH_OBSIDIAN_DESC:
"Image preview in documents should match the Obsidian theme. If enabled, when Obsidian is in dark mode, Excalidraw images will render in dark mode. " +
@@ -353,7 +378,7 @@ export default {
EXPORT_THEME_DESC:
"Export the image matching the dark/light theme of your drawing. If turned off, " +
"drawings created in dark mode will appear as they would in light mode.",
EXPORT_HEAD: "Export Settings",
EXPORT_HEAD: "Auto-export Settings",
EXPORT_SYNC_NAME:
"Keep the .SVG and/or .PNG filenames in sync with the drawing file",
EXPORT_SYNC_DESC:
@@ -389,6 +414,12 @@ export default {
MATHJAX_DESC: "If you are using LaTeX equiations in Excalidraw then the plugin needs to load a javascript library for that. " +
"Some users are unable to access certain host servers. If you are experiencing issues try changing the host here. You may need to "+
"restart Obsidian after closing settings, for this change to take effect.",
LATEX_DEFAULT_NAME: "Default LaTeX formual for new equations",
LATEX_DEFAULT_DESC: "Leave empty if you don't want a default formula. You can add default formatting here such as <code>\\color{white}</code>.",
NONSTANDARD_HEAD: "Non-Excalidraw.com supported features",
NONSTANDARD_DESC: "These features are not available on excalidraw.com. When exporting the drawing to Excalidraw.com these features will appear different.",
CUSTOM_PEN_NAME: "Number of custom pens",
CUSTOM_PEN_DESC: "You will see these pens next to the Obsidian Menu on the canvas. You can customize the pens on the canvas by long-pressing the pen button.",
EXPERIMENTAL_HEAD: "Experimental features",
EXPERIMENTAL_DESC:
"Some of these setting will not take effect immediately, only when the File Explorer is refreshed, or Obsidian restarted.",
@@ -418,10 +449,22 @@ export default {
"Select a .ttf, .woff or .woff2 font file from your vault to use as the fourth font. " +
"If no file is selected, Excalidraw will use the Virgil font by default.",
SCRIPT_SETTINGS_HEAD: "Settings for installed Scripts",
TASKBONE_HEAD: "Taskbone Optical Character Recogntion",
TASKBONE_DESC: "This is an experimental integration of optical character recognition into Excalidraw. Please note, that taskbone is an independent external service not provided by Excalidraw, nor the Excalidraw-Obsidian plugin project. " +
"The OCR service will grab legible text from freedraw lines and embedded pictures on your canvas and place the recognized text in the frontmatter of your drawing as well as onto clipboard. " +
"Having the text in the frontmatter will enable you to search in Obsidian for the text contents of these. " +
"Note, that the process of extracting the text from the image is not done locally, but via an online API. The taskbone service stores the image on its servers only as long as necessary for the text extraction. However, if this is a dealbreaker, then please don't use this feature.",
TASKBONE_ENABLE_NAME: "Enable Taskbone",
TASKBONE_ENABLE_DESC: "By enabling this service your agree to the Taskbone <a href='https://www.taskbone.com/legal/terms/' target='_blank'>Terms and Conditions</a> and the " +
"<a href='https://www.taskbone.com/legal/privacy/' target='_blank'>Privacy Policy</a>.",
TASKBONE_APIKEY_NAME: "Taskbone API Key",
TASKBONE_APIKEY_DESC: "Taskbone offers a free service with a reasonable number of scans per month. If you want to use this feature more frequently, or you want to supoprt " +
"the developer of Taskbone (as you can imagine, there is no such thing as 'free', providing this awesome OCR service costs some money to the developer of Taskbone), you can " +
"purchase a paid API key from <a href='https://www.taskbone.com/' target='_blank'>taskbone.com</a>. In case you have purchased a key, simply overwrite this auto generated free-tier API-key with your paid key.",
//openDrawings.ts
SELECT_FILE: "Select a file then press enter.",
SELECT_FILE_WITH_OPTION_TO_SCALE: "Select a file then press ENTER, or ALT+ENTER to insert at 100% scale.",
SELECT_FILE_WITH_OPTION_TO_SCALE: `Select a file then press ENTER, or ${labelSHIFT()}+${labelMETA()}+ENTER to insert at 100% scale.`,
NO_MATCH: "No file matches your query.",
SELECT_FILE_TO_LINK: "Select the file you want to insert the link for.",
SELECT_DRAWING: "Select the image or drawing you want to insert",
@@ -430,6 +473,9 @@ export default {
"Select existing drawing or type name of a new drawing then press Enter.",
SELECT_TO_EMBED: "Select the drawing to insert into active document.",
SELECT_MD: "Select the markdown document you want to insert",
SELECT_PDF: "Select the PDF document you want to insert",
PDF_PAGES_HEADER: "Pages to load?",
PDF_PAGES_DESC: "Format: 1, 3-5, 7, 9-11",
//EmbeddedFileLoader.ts
INFINITE_LOOP_WARNING:
@@ -446,4 +492,7 @@ export default {
GOTO_FULLSCREEN: "Goto fullscreen mode",
EXIT_FULLSCREEN: "Exit fullscreen mode",
TOGGLE_FULLSCREEN: "Toggle fullscreen mode",
TOGGLE_DISABLEBINDING: "Toggle to invert default binding behavior",
OPEN_LINK_CLICK: "Navigate to selected element link",
OPEN_LINK_PROPS: "Open markdown-embed properties or open link in new window"
};

View File

@@ -1,20 +1,22 @@
import {
DEVICE,
FRONTMATTER_KEY_CUSTOM_LINK_BRACKETS,
FRONTMATTER_KEY_CUSTOM_PREFIX,
FRONTMATTER_KEY_CUSTOM_URL_PREFIX,
} from "src/Constants";
import { labelALT, labelCTRL, labelMETA, labelSHIFT } from "src/utils/ModifierkeyHelper";
// 简体中文
export default {
// main.ts
INSTALL_SCRIPT: "安装此脚本",
UPDATE_SCRIPT: "发现可用更新 - 点击安装",
UPDATE_SCRIPT: "可用更新 - 点击安装",
CHECKING_SCRIPT:
"检查脚本更新 - 点击重新安装",
"检查更新 - 点击重新安装",
UNABLETOCHECK_SCRIPT:
"检查更新失败 - 点击重新安装",
UPTODATE_SCRIPT:
"已安装最新脚本 - 点击重新安装",
"脚本已是最新 - 点击重新安装",
OPEN_AS_EXCALIDRAW: "打开为 Excalidraw 绘图",
TOGGLE_MODE: "在 Excalidraw 和 Markdown 模式之间切换",
CONVERT_NOTE_TO_EXCALIDRAW: "转换空白笔记为 Excalidraw 绘图",
@@ -30,60 +32,66 @@ export default {
TRANSCLUDE_MOST_RECENT: "嵌入最近编辑过的绘图(形如 ![[drawing]])到当前文档",
TOGGLE_LEFTHANDED_MODE: "切换为左手模式",
NEW_IN_NEW_PANE: "新建绘图 - 于新面板",
NEW_IN_NEW_TAB: "新建绘图 - 于新页签",
NEW_IN_ACTIVE_PANE: "新建绘图 - 于当前面板",
NEW_IN_POPOUT_WINDOW: "新建绘图 - 于新窗口",
NEW_IN_NEW_PANE_EMBED:
"新建绘图 - 于新面板 - 并将其嵌入(形如 ![[drawing]])到当前文档",
NEW_IN_NEW_TAB_EMBED:
"新建绘图 - 于新页签 - 并将其嵌入(形如 ![[drawing]])到当前文档",
NEW_IN_ACTIVE_PANE_EMBED:
"新建绘图 - 于当前面板 - 并将其嵌入(形如 ![[drawing]])到当前文档",
NEW_IN_POPOUT_WINDOW_EMBED: "新建绘图 - 于新窗口 - 并将其嵌入(形如 ![[drawing]])到当前文档",
EXPORT_SVG: "导出 SVG 文件到当前目录",
EXPORT_PNG: "导出 PNG 文件到当前目录",
TOGGLE_LOCK: "切换文本元素为原文模式RAW/预览模式PREVIEW",
EXPORT_SVG_WITH_SCENE: "导出 SVG 文件(包含 Scene到当前目录",
EXPORT_PNG_WITH_SCENE: "导出 PNG 文件(包含 Scene到当前目录",
TOGGLE_LOCK: "文本元素原文模式RAW⟺ 预览模式PREVIEW",
DELETE_FILE: "从库中删除所选图像(或 MD-Embed的源文件",
INSERT_LINK_TO_ELEMENT:
"复制所选元素的内部链接。按住 CTRL/CMD 可复制元素所在分组的内部链接。按住 SHIFT 可复制元素周围区域的内部链接。",
`复制所选元素的内部链接(形如 [[file#^elementID]])。\n按住 ${labelCTRL()} 可复制元素所在分组的内部链接(形如 [[file#^group=elementID]])。\n按住 ${labelSHIFT()} 可复制所选元素周围区域的内部链接(形如 [[file#^area=elementID]])。\n按住 ${labelALT()} 可观看视频演示。`,
INSERT_LINK_TO_ELEMENT_GROUP:
"复制所选元素所在分组的内部链接(形如 [[file#^group=elementID]]",
INSERT_LINK_TO_ELEMENT_AREA:
"复制所选元素周围区域的内部链接(形如 [[file#^area=elementID]]",
INSERT_LINK_TO_ELEMENT_NORMAL:
"复制所选元素的引用链接(形如 [[file#^elementID]]",
"复制所选元素的内部链接(形如 [[file#^elementID]]",
INSERT_LINK_TO_ELEMENT_ERROR: "未选择画布里的单个元素",
INSERT_LINK_TO_ELEMENT_READY: "链接已生成并复制到剪贴板",
INSERT_LINK: "插入文件的内部链接(形如 [[drawing]])到当前绘图",
INSERT_IMAGE: "插入图像(以图像形式嵌入)到当前绘图",
IMPORT_SVG: "插入 SVG 矢量图形到当前绘图(支持有限,尚不支持文本)",
INSERT_MD: "插入 Markdown 文档(以图像形式嵌入)到当前绘图",
INSERT_LATEX:
"插入 LaTeX 公式到当前绘图",
`插入 LaTeX 公式到当前绘图。按住 ${labelALT()} 可观看视频演示。`,
ENTER_LATEX: "输入 LaTeX 表达式",
READ_RELEASE_NOTES: "阅读本插件的最新发行版本说明",
TRAY_MODE: "切换绘图工具属性页为面板模式Panel/托盘模式Tray",
READ_RELEASE_NOTES: "阅读本插件的更新说明",
RUN_OCR: "OCR 识别涂鸦和图片里的文本并复制到剪贴板",
TRAY_MODE: "绘图工具属性页:面板模式 ⟺ 托盘模式",
SEARCH: "搜索文本",
RESET_IMG_TO_100: "重设图像元素的尺寸为 100%",
TEMPORARY_DISABLE_AUTOSAVE: "临时禁用自动保存功能,直到 Obsidian 退出(勿点,除非你清楚自己在干什么)",
TEMPORARY_ENABLE_AUTOSAVE: "恢复启用自动保存功能",
//ExcalidrawView.ts
INSTALL_SCRIPT_BUTTON: "安装或更新 Excalidraw 自动化脚本",
INSTALL_SCRIPT_BUTTON: "安装或更新 Excalidraw 脚本",
OPEN_AS_MD: "打开为 Markdown 文件",
SAVE_AS_PNG: "导出 PNG 到当前目录(按住 CTRL/CMD 设定导出路径)",
SAVE_AS_SVG: "导出 SVG 到当前目录(按住 CTRL/CMD 设定导出路径)",
SAVE_AS_PNG: `导出 PNG 到当前目录(按住 ${labelCTRL()} 设定导出路径;按住 SHIFT 在导出时包含 Scene`,
SAVE_AS_SVG: `导出 SVG 到当前目录(按住 ${labelCTRL()} 设定导出路径;按住 SHIFT 在导出时包含 Scene`,
OPEN_LINK: "打开所选元素里的链接 \n按住 SHIFT 在新面板打开)",
EXPORT_EXCALIDRAW: "导出为 .Excalidraw 文件",
LINK_BUTTON_CLICK_NO_TEXT:
"请选择一个含有链接的图形或文本元素。\n" +
"按住 SHIFT 并点击此按钮可在新面板中打开链接。\n" +
"您也可以直接在画布中按住 CTRL/CMD 并点击图形或文本元素来打开链接。",
"请选择一个含有链接的图形或文本元素。",
FILENAME_INVALID_CHARS:
'文件名不能含有以下符号: * " \\ < > : | ? #',
FILE_DOES_NOT_EXIST:
"文件不存在。按住 ALT或 ALT + SHIFT并点击链接来创建新文件。",
FORCE_SAVE:
"立刻保存绘图(并更新嵌入了该绘图的面板)。\n详见插件设置中的定期保存选项",
"保存绘图(并更新嵌入了该绘图的面板)",
RAW: "文本元素正以原文RAW模式显示链接。\n点击切换到预览PREVIEW模式",
PARSED:
"文本元素正以预览PREVIEW模式显示链接。\n点击切换到原文RAW模式",
NOFILE: "Excalidraw没有文件",
COMPATIBILITY_MODE:
"*.excalidraw 文件以兼容模式打开。转换为新格式以获得完整的插件功能。",
"*.excalidraw 文件以兼容模式打开。需要转换为新格式才能使用插件的全部功能。",
CONVERT_FILE: "转换为新格式",
//settings.ts
@@ -112,12 +120,13 @@ export default {
"Template.md则此项应设为 Excalidraw/Template.md也可省略 .md 扩展名,即 Excalidraw/Template。<br>" +
"如果您在兼容模式下使用 Excalidraw那么您的模板文件也必须是旧的 *.excalidraw 格式," +
"例如 Excalidraw/Template.excalidraw。",
SCRIPT_FOLDER_NAME: "Excalidraw 自动化脚本的文件夹",
SCRIPT_FOLDER_NAME: "Excalidraw 自动化脚本的文件夹(大小写敏感!)",
SCRIPT_FOLDER_DESC:
"此文件夹用于存放 Excalidraw 自动化脚本。" +
"您可以在 Obsidian 命令面板中执行这些脚本," +
"还可以为喜欢的脚本分配快捷键,就像为其他 Obsidian 命令分配快捷键一样。<br>" +
"该项不能设为库的根目录。",
SAVING_HEAD: "保存",
COMPRESS_NAME: "压缩 Excalidraw JSON",
COMPRESS_DESC:
"Excalidraw 绘图文件默认将元素记录为 JSON 格式。开启此项,可将元素的 JSON 数据以 BASE64 编码" +
@@ -129,15 +138,18 @@ export default {
"而当您切换回 Excalidraw 模式时,数据就会被再次编码。<br>" +
"开启此项后,对于之前已存在的未压缩的绘图文件," +
"需要重新打开并保存它们才能生效。",
AUTOSAVE_NAME: "定期保存",
AUTOSAVE_DESC:
"定期保存当前绘图。此功能专为移动设备设计 —— " +
"在桌面端,当您关闭 Excalidraw 或 Obsidian或者移动焦点到其他面板的时候软件是会自动保存的;" +
"但是在手机或平板上通过滑动手势退出 Obsidian 时,可能无法顺利触发自动保存。因此我添加了定期保存功能作为弥补。",
AUTOSAVE_INTERVAL_NAME: "定期保存时间间隔",
AUTOSAVE_INTERVAL_DESC:
"每隔多长时间执行一次保存。如果当前绘图没有发生改变,将不会触发保存。",
FILENAME_HEAD: "文件名",
AUTOSAVE_INTERVAL_DESKTOP_NAME: "桌面端定期保存时间间隔",
AUTOSAVE_INTERVAL_DESKTOP_DESC:
"每隔多长时间触发一次自动保存。但如果当前绘图没有发生改变,将不会触发自动保存。" +
"当 Obsidian 应用内的焦点离开活动文档(如关闭工作空间、点击菜单栏、切换到其他页签或面板等)的时候,会触发自动保存" +
"直接退出 Obsidian 应用(不管是终结进程还是点关闭按钮)不会触发自动保存。",
AUTOSAVE_INTERVAL_MOBILE_NAME: "移动端定期保存时间间隔",
AUTOSAVE_INTERVAL_MOBILE_DESC:
"建议在移动端设置更短的自动保存时间间隔。" +
"当 Obsidian 应用内的焦点离开活动文档(如关闭工作空间、点击菜单栏、切换到其他页签或面板等)的时候,会触发自动保存。" +
"直接退出 Obsidian 应用(在应用切换器中划掉)不会触发自动保存。此外,当您切换到其他应用时,有时候" +
"系统会自动清理 Obsidian 后台以释放资源。这种情况下Excalidraw 无法保存最新的变动。",
FILENAME_HEAD: "文件名",
FILENAME_DESC:
"<p>点击阅读" +
"<a href='https://momentjs.com/docs/#/displaying/format/'>日期和时间格式参考</a>。</p>",
@@ -187,15 +199,28 @@ export default {
DEFAULT_PEN_MODE_NAME: "触控笔模式Pen mode",
DEFAULT_PEN_MODE_DESC:
"打开绘图时,是否自动开启触控笔模式?",
ZOOM_TO_FIT_NAME: "自动缩放以适应面板调整",
ZOOM_TO_FIT_DESC: "调整面板大小时,自适应地缩放画布" +
DEFAULT_PINCHZOOM_NAME: "允许在触控笔模式下进行双指缩放",
DEFAULT_PINCHZOOM_DESC:
"在触控笔模式下使用自由画笔工具时,双指缩放可能造成干扰。<br>" +
"<b>开启: </b>允许在触控笔模式下进行双指缩放<br><b>关闭: </b>禁止在触控笔模式下进行双指缩放",
DEFAULT_WHEELZOOM_NAME: "鼠标滚轮缩放页面",
DEFAULT_WHEELZOOM_DESC:
`<b>开启:</b>鼠标滚轮为缩放页面,${labelCTRL()}+鼠标滚轮为滚动页面</br><b>关闭:</b>鼠标滚轮为滚动页面,${labelCTRL()}+鼠标滚轮为缩放页面`,
ZOOM_TO_FIT_NAME: "调节面板尺寸后自动缩放页面",
ZOOM_TO_FIT_DESC: "调节面板尺寸后,自适应地缩放页面" +
"<br><b>开启:</b>自动缩放。<br><b>关闭:</b>禁用自动缩放。",
ZOOM_TO_FIT_ONOPEN_NAME: "打开绘图时自动缩放页面",
ZOOM_TO_FIT_ONOPEN_DESC: "打开绘图文件时,自适应地缩放页面" +
"<br><b>开启:</b>自动缩放。<br><b>关闭:</b>禁用自动缩放。",
ZOOM_TO_FIT_MAX_LEVEL_NAME: "自动缩放的最高级别",
ZOOM_TO_FIT_MAX_LEVEL_DESC:
"自动缩放画布时,允许放大的最高级别。该值不能低于 0.550%)且不能超过 101000%)。",
LINKS_HEAD: "链接Links & 以文本形式嵌入到绘图中的文档Transclusion",
LINKS_DESC:
"按住 CTRL/CMD 并点击包含 <code>[[链接]]</code> 的文本元素可以打开其中的链接。<br>" +
`按住 ${labelCTRL()} 并点击包含 <code>[[链接]]</code> 的文本元素可以打开其中的链接。` +
"如果所选文本元素包含多个 <code>[[有效的内部链接]]</code> ,只会打开第一个链接;" +
"如果所选文本元素包含有效的 URL 链接 (如 <code>https://</code> 或 <code>http://</code>)" +
"插件会在浏览器中打开链接。<br>" +
@@ -203,45 +228,45 @@ export default {
"若您不愿绘图中的链接外观因此而变化,可使用 <code>[[内部链接|别名]]</code>。",
ADJACENT_PANE_NAME: "在相邻面板中打开",
ADJACENT_PANE_DESC:
"按住 CTRL/CMD + SHIFT 并点击绘图里的内部链接时,插件默认会在新面板中打开该链接。<br>" +
`按住 ${labelCTRL()}+${labelSHIFT()} 并点击绘图里的内部链接时,插件默认会在新面板中打开该链接。<br>` +
"若开启此项Excalidraw 会先尝试寻找已有的相邻面板(按照右侧、左侧、上方、下方的顺序)," +
"并在其中打开该链接。如果找不到," +
"再在新面板中打开。",
MAINWORKSPACE_PANE_NAME: "在主工作区中打开",
MAINWORKSPACE_PANE_DESC:
"按住 CTRL/CMD + SHIFT 并点击绘图里的内部链接时,插件默认会在当前窗口的新面板中打开该链接。<br>" +
`按住 ${labelCTRL()}+${labelSHIFT()} 并点击绘图里的内部链接时,插件默认会在当前窗口的新面板中打开该链接。<br>` +
"若开启此项Excalidraw 会在主工作区的面板中打开该链接。",
LINK_BRACKETS_NAME: "在链接的两侧显示 [[中括号]]",
LINK_BRACKETS_NAME: "在链接的两侧显示 <code>[[中括号]]</code>",
LINK_BRACKETS_DESC: `${
"文本元素处于预览模式时,在内部链接的两侧显示中括号。<br>" +
"文本元素处于预览PREVIEW模式时,在内部链接的两侧显示中括号。<br>" +
"您可为某个绘图单独设置此项,方法是在其 frontmatter 中添加形如 <code>"
}${FRONTMATTER_KEY_CUSTOM_LINK_BRACKETS}: true/false</code> 的键值对。`,
LINK_PREFIX_NAME: "内部链接的前缀",
LINK_PREFIX_DESC: `${
"文本元素处于预览模式时,如果其中包含链接,则添加此前缀。<br>" +
"文本元素处于预览PREVIEW模式时,如果其中包含链接,则添加此前缀。<br>" +
"您可为某个绘图单独设置此项,方法是在其 frontmatter 中添加形如 <code>"
}${FRONTMATTER_KEY_CUSTOM_PREFIX}: "📍 "</code> 的键值对。`,
URL_PREFIX_NAME: "外部链接的前缀",
URL_PREFIX_DESC: `${
"文本元素处于预览模式时,如果其中包含外部链接,则添加此前缀。<br>" +
"文本元素处于预览PREVIEW模式时,如果其中包含外部链接,则添加此前缀。<br>" +
"您可为某个绘图单独设置此项,方法是在其 frontmatter 中添加形如 <code>"
}${FRONTMATTER_KEY_CUSTOM_URL_PREFIX}: "🌐 "</code> 的键值对。`,
PARSE_TODO_NAME: "解析任务列表Todo",
PARSE_TODO_NAME: "待办任务Todo",
PARSE_TODO_DESC: "将文本元素中的 <code>- [ ]</code> 和 <code>- [x]</code> 前缀显示为方框。",
TODO_NAME: "未完成的 Todo 项目",
TODO_DESC: "未完成的 Todo 项目的符号",
DONE_NAME: "已完成的 Todo 项目",
DONE_DESC: "已完成的 Todo 项目的符号",
TODO_NAME: "未完成项目",
TODO_DESC: "未完成的待办项目的符号",
DONE_NAME: "已完成项目",
DONE_DESC: "已完成的待办项目的符号",
HOVERPREVIEW_NAME: "鼠标悬停预览内部链接",
HOVERPREVIEW_DESC:
"<b>开启:</b>在 Excalidraw <u>阅读模式View</u>下,鼠标悬停在 <code>[[内部链接]]</code> 上即可预览;" +
`<b>开启:</b>在 Excalidraw <u>阅读模式View</u>下,鼠标悬停在 <code>[[内部链接]]</code> 上即可预览;` +
"而在<u>普通模式Normal</u>下, 鼠标悬停在内部链接右上角的蓝色标识上即可预览。<br> " +
"<b>关闭:</b>鼠标悬停在 <code>[[内部链接]]</code> 上,并且按住 CTRL/CMD 时进行预览。",
`<b>关闭:</b>鼠标悬停在 <code>[[内部链接]]</code> 上,并且按住 ${labelCTRL()} 才能预览。`,
LINKOPACITY_NAME: "链接标识的透明度",
LINKOPACITY_DESC:
"含有链接的元素,其右上角的链接标识的透明度。介于 0全透明到 1不透明之间。",
LINK_CTRL_CLICK_NAME:
"按住 CTRL/CMD 并点击含有 [[链接]] 或 [别名](链接) 的文本来打开链接",
`按住 ${labelCTRL()} 并点击含有 [[链接]] 或 [别名](链接) 的文本来打开链接`,
LINK_CTRL_CLICK_DESC:
"如果此功能影响到您使用某些原版 Excalidraw 功能,可将其关闭。" +
"关闭后,您只能通过绘图面板标题栏中的链接按钮来打开链接。",
@@ -259,13 +284,16 @@ export default {
PAGE_TRANSCLUSION_CHARCOUNT_DESC:
"以 <code>![[内部链接]]</code> 或 <code>![](内部链接)</code> 的形式将文档以文本形式嵌入到绘图中时," +
"该文档在绘图中可显示的最大字符数量。",
QUOTE_TRANSCLUSION_REMOVE_NAME: "隐藏 Transclusion 行首的引用符号",
QUOTE_TRANSCLUSION_REMOVE_DESC: "不显示 Transclusion 中每一行行首的 > 符号,以提高纯文本 Transclusion 的可读性。<br>" +
"<b>开启:</b>隐藏 > 符号<br><b>关闭:</b>不隐藏 > 符号(注意,由于 Obsidian API 的原因,首行行首的 > 符号不会被隐藏)",
GET_URL_TITLE_NAME: "使用 iframly 获取页面标题",
GET_URL_TITLE_DESC:
"拖放链接到 Excalidraw 时,使用 <code>http://iframely.server.crestify.com/iframely?url=</code> 来获取页面的标题。",
MD_HEAD: "以图像形式嵌入到绘图中的 Markdown 文档MD-Embed",
MD_HEAD_DESC:
"您还可以将 Markdown 文档以图像形式(而非文本形式)嵌入到绘图中。" +
"方法是按住 CTRL/CMD 并从文件管理器中把文档拖入绘图,或者执行“以图像形式嵌入”系列命令。",
`方法是按住 ${labelCTRL()} 并从文件管理器中把文档拖入绘图,或者执行“以图像形式嵌入”系列命令。`,
MD_TRANSCLUDE_WIDTH_NAME: "MD-Embed 的默认宽度",
MD_TRANSCLUDE_WIDTH_DESC:
"MD-Embed 的宽度。该选项会影响到折行,以及图像元素的宽度。<br>" +
@@ -382,6 +410,10 @@ export default {
MATHJAX_DESC: "如果您在绘图中使用 LaTeX插件需要从服务器获取并加载一个 javascript 库。" +
"如果您的网络无法访问某些库服务器,可以尝试通过此选项更换库服务器。"+
"更改此选项后,您可能需要重启 Obsidian 来使其生效。",
NONSTANDARD_HEAD: "非 Excalidraw.com 官方支持的特性",
NONSTANDARD_DESC: "这些特性不受 Excalidraw.com 官方支持。当导出绘图到 Excalidraw.com 时,这些特性将会发生变化。",
CUSTOM_PEN_NAME: "自定义画笔的数量",
CUSTOM_PEN_DESC: "在画布上的 Obsidian 菜单旁边切换自定义画笔。长按画笔按钮可以修改其样式。",
EXPERIMENTAL_HEAD: "实验性功能",
EXPERIMENTAL_DESC:
"以下部分设置不会立即生效,需要刷新文件资源管理器或者重启 Obsidian 才会生效。",
@@ -411,9 +443,22 @@ export default {
"选择库文件夹中的一个 .ttf, .woff 或 .woff2 字体文件作为本地字体文件。" +
"若未选择文件,则使用默认的 Virgil 字体。",
SCRIPT_SETTINGS_HEAD: "已安装脚本的设置",
TASKBONE_HEAD: "Taskbone OCR光学符号识别",
TASKBONE_DESC: "这是一个将 OCR 融入 Excalidraw 的实验性功能。请注意Taskbone 是一项独立的外部服务,而不是由 Excalidraw 或 Obsidian-excalidraw-plugin 项目提供的。" +
"OCR 能够对画布上用自由画笔工具写下的涂鸦或者嵌入的图像进行文本识别,并将识别出来的文本写入绘图文件的 frontmatter同时复制到剪贴板。" +
"之所以要写入 frontmatter 是为了便于您在 Obsidian 中能够搜索到这些文本。" +
"注意,识别的过程不是在本地进行的,而是通过在线 API图像会被上传到 taskbone 的服务器(仅用于识别目的)。如果您对此敏感,请不要使用这个功能。",
TASKBONE_ENABLE_NAME: "启用 Taskbone",
TASKBONE_ENABLE_DESC: "启用这个功能意味着你同意 Taskbone <a href='https://www.taskbone.com/legal/terms/' target='_blank'>条款及细则</a> 以及 " +
"<a href='https://www.taskbone.com/legal/privacy/' target='_blank'>隐私政策</a>.",
TASKBONE_APIKEY_NAME: "Taskbone API Key",
TASKBONE_APIKEY_DESC: "Taskbone 的免费 API key 提供了一定数量的每月识别次数。如果您非常频繁地使用此功能,或者想要支持 " +
"Taskbone 的开发者您懂的没有人能用爱发电Taskbone 开发者也需要投入资金才能持续运行这项 OCR 服务)您可以" +
"到 <a href='https://www.taskbone.com/' target='_blank'>taskbone.com</a> 购买一个商用 API key。购买后请将它填写到旁边这个文本框里替换掉原本自动生成的免费 API key。",
//openDrawings.ts
SELECT_FILE: "选择一个文件后按回车。",
SELECT_FILE_WITH_OPTION_TO_SCALE: `选择一个文件后按回车,或者 ${labelSHIFT()}+${labelMETA()}+ENTER 以 100% 尺寸插入。`,
NO_MATCH: "查询不到匹配的文件。",
SELECT_FILE_TO_LINK: "选择要插入(链接)到当前绘图中的文件。",
SELECT_DRAWING: "选择要插入(以图像形式嵌入)到当前绘图中的图像。",
@@ -438,4 +483,6 @@ export default {
GOTO_FULLSCREEN: "进入全屏模式",
EXIT_FULLSCREEN: "退出全屏模式",
TOGGLE_FULLSCREEN: "切换全屏模式",
OPEN_LINK_CLICK: "打开所选的图形或文本元素里的链接",
OPEN_LINK_PROPS: "编辑所选 MD-Embed 的内部链接,或者打开所选的图形或文本元素里的链接"
};

View File

@@ -16,7 +16,7 @@ import {
request,
MetadataCache,
FrontMatterCache,
Command
Command,
} from "obsidian";
import {
BLANK_DRAWING,
@@ -25,8 +25,6 @@ import {
ICON_NAME,
SCRIPTENGINE_ICON,
SCRIPTENGINE_ICON_NAME,
DISK_ICON,
DISK_ICON_NAME,
PNG_ICON,
PNG_ICON_NAME,
SVG_ICON,
@@ -37,7 +35,6 @@ import {
JSON_parse,
nanoid,
DARK_BLANK_DRAWING,
CTRL_OR_CMD,
SCRIPT_INSTALL_CODEBLOCK,
SCRIPT_INSTALL_FOLDER,
VIRGIL_FONT,
@@ -54,7 +51,7 @@ import {
ExcalidrawSettings,
DEFAULT_SETTINGS,
ExcalidrawSettingTab,
} from "./Settings";
} from "./settings";
import { openDialogAction, OpenFileDialog } from "./dialogs/OpenDrawing";
import { InsertLinkDialog } from "./dialogs/InsertLinkDialog";
import { InsertImageDialog } from "./dialogs/InsertImageDialog";
@@ -98,14 +95,15 @@ import {
markdownPostProcessor,
observer,
} from "./MarkdownPostProcessor";
import { FieldSuggester } from "./dialogs/FieldSuggester";
import { ReleaseNotes } from "./dialogs/ReleaseNotes";
import { decompressFromBase64 } from "lz-string";
import { Packages } from "./types";
import * as React from "react";
import { ScriptInstallPrompt } from "./dialogs/ScriptInstallPrompt";
import { check } from "prettier";
import Taskbone from "./ocr/Taskbone";
import { emulateCTRLClickForLinks, linkClickModifierType, PaneTarget } from "./utils/ModifierkeyHelper";
import { InsertPDFModal } from "./dialogs/InsertPDFModal";
declare module "obsidian" {
interface App {
@@ -133,6 +131,7 @@ declare const excalidrawLib: any;
declare const PLUGIN_VERSION:string;
export default class ExcalidrawPlugin extends Plugin {
public taskbone: Taskbone;
private excalidrawFiles: Set<TFile> = new Set<TFile>();
public excalidrawFileModes: { [file: string]: string } = {};
private _loaded: boolean = false;
@@ -157,7 +156,7 @@ export default class ExcalidrawPlugin extends Plugin {
public opencount: number = 0;
public ea: ExcalidrawAutomate;
//A master list of fileIds to facilitate copy / paste
public filesMaster: Map<FileId, { path: string; hasSVGwithBitmap: boolean; blockrefData: string }> =
public filesMaster: Map<FileId, { isHyperlink: boolean; path: string; hasSVGwithBitmap: boolean; blockrefData: string, colorMapJSON?: string}> =
null; //fileId, path
public equationsMaster: Map<FileId, string> = null; //fileId, formula
public mathjax: any = null;
@@ -168,23 +167,12 @@ export default class ExcalidrawPlugin extends Plugin {
private packageMap: WeakMap<Window,Packages> = new WeakMap<Window,Packages>();
public leafChangeTimeout: NodeJS.Timeout = null;
private forceSaveCommand:Command;
public device: {
isDesktop: boolean,
isPhone: boolean,
isTablet: boolean,
isMobile: boolean,
isLinux: boolean,
isMacOS: boolean,
isWindows: boolean,
isIOS: boolean,
isAndroid: boolean
};
constructor(app: App, manifest: PluginManifest) {
super(app, manifest);
this.filesMaster = new Map<
FileId,
{ path: string; hasSVGwithBitmap: boolean; blockrefData: string }
{ isHyperlink: boolean; path: string; hasSVGwithBitmap: boolean; blockrefData: string; colorMapJSON?: string }
>();
this.equationsMaster = new Map<FileId, string>();
}
@@ -208,21 +196,8 @@ export default class ExcalidrawPlugin extends Plugin {
}
async onload() {
this.device = {
isDesktop: !document.body.hasClass("is-tablet") && !document.body.hasClass("is-mobile"),
isPhone: document.body.hasClass("is-phone"),
isTablet: document.body.hasClass("is-tablet"),
isMobile: document.body.hasClass("is-mobile"), //running Obsidian Mobile, need to also check isTablet
isLinux: document.body.hasClass("mod-linux") && ! document.body.hasClass("is-android"),
isMacOS: document.body.hasClass("mod-macos") && ! document.body.hasClass("is-ios"),
isWindows: document.body.hasClass("mod-windows"),
isIOS: document.body.hasClass("is-ios"),
isAndroid: document.body.hasClass("is-android")
}
addIcon(ICON_NAME, EXCALIDRAW_ICON);
addIcon(SCRIPTENGINE_ICON_NAME, SCRIPTENGINE_ICON);
addIcon(DISK_ICON_NAME, DISK_ICON);
addIcon(PNG_ICON_NAME, PNG_ICON);
addIcon(SVG_ICON_NAME, SVG_ICON);
@@ -255,8 +230,8 @@ export default class ExcalidrawPlugin extends Plugin {
// const patches = new OneOffs(this);
if (this.settings.showReleaseNotes) {
//I am repurposing imageElementNotice, if the value is true, this means the plugin was just newly installed to Obsidian.
const obsidianJustInstalled = this.settings.imageElementNotice;
const obsidianJustInstalled = this.settings.previousRelease === "0.0.0"
if (isVersionNewerThanOther(PLUGIN_VERSION, this.settings.previousRelease)) {
new ReleaseNotes(
this.app,
@@ -274,6 +249,7 @@ export default class ExcalidrawPlugin extends Plugin {
this.app.workspace.onLayoutReady(() => {
this.scriptEngine = new ScriptEngine(self);
});
this.taskbone = new Taskbone(this);
}
public initializeFourthFont() {
@@ -395,23 +371,12 @@ export default class ExcalidrawPlugin extends Plugin {
}
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (view) {
(async()=>{
if (view.semaphores.autosaving) {
return;
}
view.semaphores.forceSaving = true;
await view.save(false, true);
view.plugin.triggerEmbedUpdates();
view.loadSceneFiles();
view.semaphores.forceSaving = false;
new Notice("Save successful", 1000);
})();
view.forceSave();
return true;
}
return false;
}
private registerInstallCodeblockProcessor() {
const codeblockProcessor = async (source: string, el: HTMLElement) => {
//Button next to the "List of available scripts" at the top
@@ -428,7 +393,7 @@ export default class ExcalidrawPlugin extends Plugin {
link.style.paddingRight = "10px";
button2 = link.parentElement.createEl("button", null, (b) => {
b.setText(t("UPDATE_SCRIPT"));
b.addClass("mod-cta");
b.addClass("mod-muted");
b.style.backgroundColor = "var(--interactive-success)";
b.style.display = "none";
});
@@ -474,7 +439,7 @@ export default class ExcalidrawPlugin extends Plugin {
break;
}
};
button.addClass("mod-cta");
button.addClass("mod-muted");
let decodedURI = source;
try {
decodedURI = decodeURI(source);
@@ -488,9 +453,10 @@ export default class ExcalidrawPlugin extends Plugin {
}
const fname = decodedURI.substring(decodedURI.lastIndexOf("/") + 1);
const folder = `${this.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}`;
const scriptPath = `${folder}/${fname}`;
const downloaded = app.vault.getFiles().filter(f=>f.path.startsWith(folder) && f.name === fname).sort((a,b)=>a.path>b.path?1:-1);
let scriptFile = downloaded[0];
const scriptPath = scriptFile?.path ?? `${folder}/${fname}`;
const svgPath = getIMGFilename(scriptPath, "svg");
let scriptFile = this.app.vault.getAbstractFileByPath(scriptPath);
let svgFile = this.app.vault.getAbstractFileByPath(svgPath);
setButtonText(scriptFile ? "CHECKING" : "INSTALL");
button.onclick = async () => {
@@ -528,6 +494,9 @@ export default class ExcalidrawPlugin extends Plugin {
svgPath,
);
setButtonText("UPTODATE");
if(Object.keys(this.scriptEngine.scriptIconMap).length === 0) {
this.scriptEngine.loadScripts();
}
new Notice(`Installed: ${(scriptFile as TFile).basename}`);
} catch (e) {
new Notice(`Error installing script: ${fname}`);
@@ -720,8 +689,8 @@ export default class ExcalidrawPlugin extends Plugin {
this.addRibbonIcon(ICON_NAME, t("CREATE_NEW"), async (e) => {
this.createAndOpenDrawing(
getDrawingFilename(this.settings),
e[CTRL_OR_CMD]?"new-pane":"active-pane",
); //.ctrlKey||e.metaKey);
linkClickModifierType(emulateCTRLClickForLinks(e)),
);
});
const fileMenuHandlerCreateNew = (menu: Menu, file: TFile) => {
@@ -729,7 +698,7 @@ export default class ExcalidrawPlugin extends Plugin {
item
.setTitle(t("CREATE_NEW"))
.setIcon(ICON_NAME)
.onClick(() => {
.onClick((e) => {
let folderpath = file.path;
if (file instanceof TFile) {
folderpath = normalizePath(
@@ -738,7 +707,7 @@ export default class ExcalidrawPlugin extends Plugin {
}
this.createAndOpenDrawing(
getDrawingFilename(this.settings),
"active-pane",
linkClickModifierType(emulateCTRLClickForLinks(e)),
folderpath,
);
});
@@ -868,6 +837,14 @@ export default class ExcalidrawPlugin extends Plugin {
},
});
this.addCommand({
id: "excalidraw-autocreate-newtab",
name: t("NEW_IN_NEW_TAB"),
callback: () => {
this.createAndOpenDrawing(getDrawingFilename(this.settings), "new-tab");
},
});
this.addCommand({
id: "excalidraw-autocreate-on-current",
name: t("NEW_IN_ACTIVE_PANE"),
@@ -888,7 +865,7 @@ export default class ExcalidrawPlugin extends Plugin {
});
const insertDrawingToDoc = async (
location: "active-pane"|"new-pane"|"popout-window"
location: PaneTarget
) => {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!activeView) {
@@ -909,7 +886,7 @@ export default class ExcalidrawPlugin extends Plugin {
).folder;
const file = await this.createDrawing(filename, folder);
await this.embedDrawing(file);
this.openDrawing(file, location, true);
this.openDrawing(file, location, true, undefined, true);
};
this.addCommand({
@@ -924,6 +901,18 @@ export default class ExcalidrawPlugin extends Plugin {
},
});
this.addCommand({
id: "excalidraw-autocreate-and-embed-new-tab",
name: t("NEW_IN_NEW_TAB_EMBED"),
checkCallback: (checking: boolean) => {
if (checking) {
return Boolean(this.app.workspace.getActiveViewOfType(MarkdownView));
}
insertDrawingToDoc("new-tab");
return true;
},
});
this.addCommand({
id: "excalidraw-autocreate-and-embed-on-current",
name: t("NEW_IN_ACTIVE_PANE_EMBED"),
@@ -966,6 +955,46 @@ export default class ExcalidrawPlugin extends Plugin {
},
});
this.addCommand({
id: "export-svg-scene",
name: t("EXPORT_SVG_WITH_SCENE"),
checkCallback: (checking: boolean) => {
if (checking) {
return (
Boolean(this.app.workspace.getActiveViewOfType(ExcalidrawView))
);
}
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (view) {
view.saveSVG(undefined,true);
return true;
}
return false;
},
});
this.addCommand({
id: "run-ocr",
name: t("RUN_OCR"),
checkCallback: (checking: boolean) => {
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (checking) {
return (
Boolean(view)
);
}
if (view) {
if(!this.settings.taskboneEnabled) {
new Notice("Taskbone OCR is not enabled. Please go to plugins settings to enable it.",4000);
return true;
}
this.taskbone.getTextForView(view, false);
return true;
}
return false;
},
});
this.addCommand({
id: "search-text",
name: t("SEARCH"),
@@ -1006,6 +1035,24 @@ export default class ExcalidrawPlugin extends Plugin {
},
});
this.addCommand({
id: "disable-binding",
name: t("TOGGLE_DISABLEBINDING"),
checkCallback: (checking: boolean) => {
if (checking) {
return (
Boolean(this.app.workspace.getActiveViewOfType(ExcalidrawView))
);
}
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (view) {
view.toggleDisableBinding();
return true;
}
return false;
},
});
this.addCommand({
id: "export-png",
name: t("EXPORT_PNG"),
@@ -1024,6 +1071,24 @@ export default class ExcalidrawPlugin extends Plugin {
},
});
this.addCommand({
id: "export-png-scene",
name: t("EXPORT_PNG_WITH_SCENE"),
checkCallback: (checking: boolean) => {
if (checking) {
return (
Boolean(this.app.workspace.getActiveViewOfType(ExcalidrawView))
);
}
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (view) {
view.savePNG(undefined, true);
return true;
}
return false;
},
});
this.forceSaveCommand = this.addCommand({
id: "save",
hotkeys: [{modifiers: ["Ctrl"], key:"s"}], //See also Poposcope
@@ -1321,6 +1386,23 @@ export default class ExcalidrawPlugin extends Plugin {
},
});
this.addCommand({
id: "insert-pdf",
name: t("INSERT_PDF"),
checkCallback: (checking: boolean) => {
if (checking) {
return Boolean(this.app.workspace.getActiveViewOfType(ExcalidrawView))
}
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (view) {
const insertPDFModal = new InsertPDFModal(this, view);
insertPDFModal.open();
return true;
}
return false;
},
});
this.addCommand({
id: "insert-LaTeX-symbol",
name: t("INSERT_LATEX"),
@@ -1734,7 +1816,7 @@ export default class ExcalidrawPlugin extends Plugin {
if (previouslyActiveEV.leaf !== leaf) {
//if loading new view to same leaf then don't save. Excalidarw view will take care of saving anyway.
//avoid double saving
if(previouslyActiveEV.semaphores.dirty) {
if(previouslyActiveEV.semaphores.dirty && !previouslyActiveEV.semaphores.viewunload) {
await previouslyActiveEV.save(true); //this will update transclusions in the drawing
}
}
@@ -1787,7 +1869,19 @@ export default class ExcalidrawPlugin extends Plugin {
}
if (newActiveviewEV) {
const scope = self.app.keymap.getRootScope();
const handler = scope.register(["Mod"], "Enter", () => true);
const handler_ctrlEnter = scope.register(["Mod"], "Enter", () => true);
scope.keys.unshift(scope.keys.pop()); // Force our handler to the front of the list
const handler_ctrlK = scope.register(["Mod"], "k", () => {return true});
scope.keys.unshift(scope.keys.pop()); // Force our handler to the front of the list
const handler_ctrlF = scope.register(["Mod"], "f", () => {
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (view) {
search(view);
return true;
}
return false;
});
scope.keys.unshift(scope.keys.pop()); // Force our handler to the front of the list
const overridSaveShortcut = (
self.forceSaveCommand &&
self.forceSaveCommand.hotkeys[0].key === "s" &&
@@ -1796,9 +1890,13 @@ export default class ExcalidrawPlugin extends Plugin {
const saveHandler = overridSaveShortcut
? scope.register(["Ctrl"], "s", () => self.forceSaveActiveView(false))
: undefined;
scope.keys.unshift(scope.keys.pop()); // Force our handler to the front of the list
if(saveHandler) {
scope.keys.unshift(scope.keys.pop()); // Force our handler to the front of the list
}
self.popScope = () => {
scope.unregister(handler);
scope.unregister(handler_ctrlEnter);
scope.unregister(handler_ctrlK);
scope.unregister(handler_ctrlF);
Boolean(saveHandler) && scope.unregister(saveHandler);
}
}
@@ -2053,7 +2151,9 @@ export default class ExcalidrawPlugin extends Plugin {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
if(opts.applyLefthandedMode) setLeftHandedMode(this.settings.isLeftHanded);
if(opts.reEnableAutosave) this.settings.autosave = true;
this.settings.autosaveInterval = app.isMobile?10000:15000; //more frequent on mobile because Obsidian may be killed on context switching
this.settings.autosaveInterval = app.isMobile
? this.settings.autosaveIntervalMobile
: this.settings.autosaveIntervalDesktop;
}
async saveSettings() {
@@ -2086,8 +2186,8 @@ export default class ExcalidrawPlugin extends Plugin {
e.initEvent(RERENDER_EVENT, true, false);
ownerDocument
.querySelectorAll(
`div[class^='excalidraw-svg']${
filepath ? `[src='${filepath.replaceAll("'", "\\'")}']` : ""
`img[class^='excalidraw-svg']${
filepath ? `[fileSource='${filepath.replaceAll("'", "\\'")}']` : ""
}`,
)
.forEach((el) => el.dispatchEvent(e));
@@ -2096,16 +2196,22 @@ export default class ExcalidrawPlugin extends Plugin {
public openDrawing(
drawingFile: TFile,
location: "active-pane"|"new-pane"|"popout-window",
location: PaneTarget,
active: boolean = false,
subpath?: string
subpath?: string,
justCreated: boolean = false
) {
if(location === "md-properties") {
location = "new-tab";
}
let leaf: WorkspaceLeaf;
if(location === "popout-window") {
//@ts-ignore
leaf = app.workspace.openPopoutLeaf();
}
else {
if(location === "new-tab") {
leaf = app.workspace.getLeaf('tab');
}
if(!leaf) {
leaf = this.app.workspace.getLeaf(false);
if ((leaf.view.getViewType() !== 'empty') && (location === "new-pane")) {
leaf = getNewOrAdjacentLeaf(this, leaf)
@@ -2117,12 +2223,19 @@ export default class ExcalidrawPlugin extends Plugin {
!subpath || subpath === ""
? {active}
: { active, eState: { subpath } }
);
/* leaf.setViewState({
type: VIEW_TYPE_EXCALIDRAW,
state: { file: drawingFile.path, eState: {subpath}},
});*/
).then(()=>{
if(justCreated && this.ea.onFileCreateHook) {
try {
this.ea.onFileCreateHook({
ea: this.ea,
excalidrawFile: drawingFile,
view: leaf.view as ExcalidrawView,
});
} catch(e) {
console.error(e);
}
}
})
}
public async getBlankDrawing(): Promise<string> {
@@ -2223,12 +2336,12 @@ export default class ExcalidrawPlugin extends Plugin {
public async createAndOpenDrawing(
filename: string,
location: "active-pane"|"new-pane"|"popout-window",
location: PaneTarget,
foldername?: string,
initData?: string,
): Promise<string> {
const file = await this.createDrawing(filename, foldername, initData);
this.openDrawing(file, location, true);
this.openDrawing(file, location, true, undefined, true);
return file.path;
}
@@ -2259,7 +2372,8 @@ export default class ExcalidrawPlugin extends Plugin {
}
public isExcalidrawFile(f: TFile) {
if (f.extension == "excalidraw") {
if(!f) return false;
if (f.extension === "excalidraw") {
return true;
}
const fileCache = f ? this.app.metadataCache.getFileCache(f) : null;

View File

@@ -3,7 +3,8 @@ import ExcalidrawView from "../ExcalidrawView";
type ButtonProps = {
title: string;
action: Function;
action: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
longpress?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
icon: JSX.Element;
view: ExcalidrawView;
};
@@ -14,6 +15,7 @@ type ButtonState = {
export class ActionButton extends React.Component<ButtonProps, ButtonState> {
toastMessageTimeout: number = 0;
longpressTimeout: number = 0;
constructor(props: ButtonProps) {
super(props);
@@ -26,9 +28,9 @@ export class ActionButton extends React.Component<ButtonProps, ButtonState> {
return (
<button
style={{
width: "fit-content",
padding: "2px",
margin: "4px",
//width: "fit-content",
//padding: "2px",
//margin: "4px",
}}
className="ToolIcon_type_button ToolIcon_size_small ToolIcon_type_button--show ToolIcon"
title={this.props.title}
@@ -36,15 +38,32 @@ export class ActionButton extends React.Component<ButtonProps, ButtonState> {
if (this.toastMessageTimeout) {
window.clearTimeout(this.toastMessageTimeout);
this.toastMessageTimeout = 0;
this.props.action(event); //don't invoke the action on long press
}
if (this.longpressTimeout) {
window.clearTimeout(this.longpressTimeout);
this.longpressTimeout = 0;
}
this.props.action(event);
}}
onPointerDown={() => {
onPointerDown={(event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
this.toastMessageTimeout = window.setTimeout(
() =>
this.props.view.excalidrawAPI?.setToast({message:this.props.title}),
300,
() => {
this.props.view.excalidrawAPI?.setToast({message:this.props.title, duration: 3000, closable: true});
this.toastMessageTimeout = 0;
},
400,
);
this.longpressTimeout = window.setTimeout(
() => {
if(this.props.longpress) {
this.props.longpress(event);
} else {
this.props.view.excalidrawAPI?.setToast({message:"Cannot pin this action", duration: 3000, closable: true});
}
this.longpressTimeout = 0;
},
1500
)
}}
>
<div className="ToolIcon__icon" aria-hidden="true">

File diff suppressed because one or more lines are too long

21
src/menu/MenuLinks.tsx Normal file
View File

@@ -0,0 +1,21 @@
import { AppState } from "@zsviczian/excalidraw/types/types";
import clsx from "clsx";
import * as React from "react";
import ExcalidrawPlugin from "../main";
export class MenuLinks {
plugin: ExcalidrawPlugin;
ref: React.MutableRefObject<any>;
constructor(plugin: ExcalidrawPlugin, ref: React.MutableRefObject<any>) {
this.plugin = plugin;
this.ref = ref;
}
render = (isMobile: boolean, appState: AppState) => {
return (
<div>Hello</div>
);
}
}

View File

@@ -1,125 +1,262 @@
import { AppState } from "@zsviczian/excalidraw/types/types";
import { AppState, ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/types";
import clsx from "clsx";
import { TFile } from "obsidian";
import * as React from "react";
import { VIEW_TYPE_EXCALIDRAW } from "src/Constants";
import { PenSettingsModal } from "src/dialogs/PenSettingsModal";
import ExcalidrawView from "src/ExcalidrawView";
import { PenStyle } from "src/PenTypes";
import { PENS } from "src/utils/Pens";
import ExcalidrawPlugin from "../main";
import { ICONS, penIcon, stringToSVG } from "./ActionIcons";
declare const PLUGIN_VERSION:string;
export const setPen = (pen: PenStyle, api: any) => {
const st = api.getAppState();
api.updateScene({
appState: {
currentStrokeOptions: pen.penOptions,
...(!pen.strokeWidth || (pen.strokeWidth === 0)) ? null : {currentItemStrokeWidth: pen.strokeWidth},
...pen.backgroundColor ? {currentItemBackgroundColor: pen.backgroundColor} : null,
...pen.strokeColor ? {currentItemStrokeColor: pen.strokeColor} : null,
...pen.fillStyle === "" ? null : {currentItemFillStyle: pen.fillStyle},
...pen.roughness ? null : {currentItemRoughness: pen.roughness},
...pen.freedrawOnly && !st.resetCustomPen //switching from custom pen to next custom pen
? {
resetCustomPen: {
currentItemStrokeWidth: st.currentItemStrokeWidth,
currentItemBackgroundColor: st.currentItemBackgroundColor,
currentItemStrokeColor: st.currentItemStrokeColor,
currentItemFillStyle: st.currentItemFillStyle,
currentItemRoughness: st.currentItemRoughness,
}}
: null,
}
})
}
export const resetStrokeOptions = (resetCustomPen:any, api: ExcalidrawImperativeAPI, clearCurrentStrokeOptions: boolean) => {
api.updateScene({
appState: {
...resetCustomPen ? {
currentItemStrokeWidth: resetCustomPen.currentItemStrokeWidth,
currentItemBackgroundColor: resetCustomPen.currentItemBackgroundColor,
currentItemStrokeColor: resetCustomPen.currentItemStrokeColor,
currentItemFillStyle: resetCustomPen.currentItemFillStyle,
currentItemRoughness: resetCustomPen.currentItemRoughness,
}: null,
resetCustomPen: null,
...clearCurrentStrokeOptions ? {currentStrokeOptions: null} : null,
}
});
}
export class ObsidianMenu {
plugin: ExcalidrawPlugin;
toolsRef: React.MutableRefObject<any>;
private clickTimestamp:number[];
private activePen: PenStyle;
constructor(
private plugin: ExcalidrawPlugin,
private toolsRef: React.MutableRefObject<any>,
private view: ExcalidrawView
) {
this.clickTimestamp = Array.from({length: Object.keys(PENS).length}, () => 0);
}
constructor(plugin: ExcalidrawPlugin, toolsRef: React.MutableRefObject<any>) {
this.plugin = plugin;
this.toolsRef = toolsRef;
renderCustomPens = (isMobile: boolean, appState: AppState) => {
return(
appState.customPens?.map((key,index)=>{
const pen = this.plugin.settings.customPens[index]
//Reset stroke setting when changing to a different tool
if(
appState.resetCustomPen &&
appState.activeTool.type !== "freedraw" &&
appState.currentStrokeOptions === pen.penOptions
) {
setTimeout(()=> resetStrokeOptions(appState.resetCustomPen, this.view.excalidrawAPI, false))
}
//if Pen settings are loaded, select custom pen when activating the freedraw element
if (
!appState.resetCustomPen &&
appState.activeTool.type === "freedraw" &&
appState.currentStrokeOptions === pen.penOptions &&
pen.freedrawOnly
) {
setTimeout(()=>setPen(this.activePen,this.view.excalidrawAPI));
}
if(
this.activePen &&
appState.resetCustomPen &&
appState.activeTool.type === "freedraw" &&
appState.currentStrokeOptions === pen.penOptions &&
pen.freedrawOnly
) {
this.activePen.strokeWidth = appState.currentItemStrokeWidth;
this.activePen.backgroundColor = appState.currentItemBackgroundColor;
this.activePen.strokeColor = appState.currentItemStrokeColor;
this.activePen.fillStyle = appState.currentItemFillStyle;
this.activePen.roughness = appState.currentItemRoughness;
}
return (
<label
key={index}
className={clsx(
"ToolIcon",
"ToolIcon_size_medium",
{
"is-mobile": isMobile,
},
)}
onClick={() => {
const now = Date.now();
const dblClick = now-this.clickTimestamp[index] < 500;
//open pen settings on double click
if(dblClick) {
const penSettings = new PenSettingsModal(this.plugin,this.view,index);
(async () => {
await this.plugin.loadSettings();
penSettings.open();
})();
return;
}
this.clickTimestamp[index] = now;
const api = this.view.excalidrawAPI;
const st = api.getAppState();
//single second click to reset freedraw to default
if(st.currentStrokeOptions === pen.penOptions && st.activeTool.type === "freedraw") {
resetStrokeOptions(st.resetCustomPen, api, true);
return;
}
//apply pen settings to canvas
this.activePen = {...pen};
setPen(pen,api);
api.setActiveTool({type:"freedraw"});
}}
>
<div
className="ToolIcon__icon"
aria-label={pen.type}
style={{
...appState.activeTool.type === "freedraw" && appState.currentStrokeOptions === pen.penOptions
? {background: "var(--color-primary)"}
: {}
}}
>
{penIcon(pen)}
</div>
</label>
)
})
)
}
private longpressTimeout : { [key: number]: number } = {};
renderPinnedScriptButtons = (isMobile: boolean, appState: AppState) => {
let prevClickTimestamp = 0;
return (
appState?.pinnedScripts?.map((key,index)=>{ //pinned scripts
const scriptProp = this.plugin.scriptEngine.scriptIconMap[key];
const name = scriptProp?.name ?? "";
const icon = scriptProp?.svgString
? stringToSVG(scriptProp.svgString)
: ICONS.cog;
if(!this.longpressTimeout[index]) this.longpressTimeout[index] = 0;
return (
<label
key = {index}
className={clsx(
"ToolIcon",
"ToolIcon_size_medium",
{
"is-mobile": isMobile,
},
)}
onPointerUp={() => {
if(this.longpressTimeout[index]) {
window.clearTimeout(this.longpressTimeout[index]);
this.longpressTimeout[index] = 0;
(async ()=>{
const f = app.vault.getAbstractFileByPath(key);
if (f && f instanceof TFile) {
this.plugin.scriptEngine.executeScript(
this.view,
await app.vault.read(f),
this.plugin.scriptEngine.getScriptName(f),
f
);
}
})()
}
}}
onPointerDown={()=>{
const now = Date.now();
if(this.longpressTimeout[index]>0) {
window.clearTimeout(this.longpressTimeout[index]);
this.longpressTimeout[index] = 0;
}
if(now-prevClickTimestamp >= 500) {
this.longpressTimeout[index] = window.setTimeout(
() => {
this.longpressTimeout[index] = 0;
(async () =>{
await this.plugin.loadSettings();
const index = this.plugin.settings.pinnedScripts.indexOf(key)
if(index > -1) {
this.plugin.settings.pinnedScripts.splice(index,1);
this.view.excalidrawAPI?.setToast({message:`Pin removed: ${name}`, duration: 3000, closable: true});
}
await this.plugin.saveSettings();
app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW).forEach(v=> {
if (v.view instanceof ExcalidrawView) v.view.updatePinnedScripts()
})
})()
},
1500
)
}
prevClickTimestamp = now;
}}
>
<div className="ToolIcon__icon" aria-label={name}>
{icon}
</div>
</label>
)
})
)
}
renderButton = (isMobile: boolean, appState: AppState) => {
return (
<label
className={clsx(
"ToolIcon ToolIcon_type_floating",
"ToolIcon_size_medium",
{
"is-mobile": isMobile,
},
)}
onClick={() => {
this.toolsRef.current.setTheme(appState.theme);
this.toolsRef.current.toggleVisibility(
appState.zenModeEnabled || isMobile,
);
}}
>
<div className="ToolIcon__icon" aria-hidden="true">
<svg
aria-hidden="true"
focusable="false"
role="img"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 166 267"
>
<path fill="transparent" d="M0 0h165.742v267.245H0z" />
<g fillRule="evenodd">
<path
fill="#bd7efc"
strokeWidth="0"
d="M55.5 96.49 39.92 57.05 111.28 10l4.58 36.54L55.5 95.65"
/>
<path
fill="none"
stroke="#410380"
strokeWidth=".5"
d="M55.5 96.49c-5.79-14.66-11.59-29.33-15.58-39.44M55.5 96.49c-3.79-9.59-7.58-19.18-15.58-39.44m0 0C60.13 43.72 80.34 30.4 111.28 10M39.92 57.05C60.82 43.27 81.73 29.49 111.28 10m0 0c.97 7.72 1.94 15.45 4.58 36.54M111.28 10c1.14 9.12 2.29 18.24 4.58 36.54m0 0C95.41 63.18 74.96 79.82 55.5 95.65m60.36-49.11C102.78 57.18 89.71 67.82 55.5 95.65m0 0v.84m0-.84v.84"
/>
</g>
<g fillRule="evenodd">
<path
fill="#e2c4ff"
strokeWidth="0"
d="m111.234 10.06 44.51 42.07-40.66-5.08-3.85-36.99"
/>
<path
fill="none"
stroke="#410380"
strokeWidth=".5"
d="M111.234 10.06c11.83 11.18 23.65 22.36 44.51 42.07m-44.51-42.07 44.51 42.07m0 0c-13.07-1.63-26.13-3.27-40.66-5.08m40.66 5.08c-11.33-1.41-22.67-2.83-40.66-5.08m0 0c-1.17-11.29-2.35-22.58-3.85-36.99m3.85 36.99c-1.47-14.17-2.95-28.33-3.85-36.99m0 0s0 0 0 0m0 0s0 0 0 0"
/>
</g>
<g fillRule="evenodd">
<path
fill="#2f005e"
strokeWidth="0"
d="m10 127.778 45.77-32.99-15.57-38.08-30.2 71.07"
/>
<path
fill="none"
stroke="#410380"
strokeWidth=".5"
d="M10 127.778c16.85-12.14 33.7-24.29 45.77-32.99M10 127.778c16.59-11.95 33.17-23.91 45.77-32.99m0 0c-6.14-15.02-12.29-30.05-15.57-38.08m15.57 38.08c-4.08-9.98-8.16-19.96-15.57-38.08m0 0c-11.16 26.27-22.33 52.54-30.2 71.07m30.2-71.07c-10.12 23.81-20.23 47.61-30.2 71.07m0 0s0 0 0 0m0 0s0 0 0 0"
/>
</g>
<g fillRule="evenodd">
<path
fill="#410380"
strokeWidth="0"
d="m40.208 235.61 15.76-140.4-45.92 32.92 30.16 107.48"
/>
<path
fill="none"
stroke="#410380"
strokeWidth=".5"
d="M40.208 235.61c3.7-33.01 7.41-66.02 15.76-140.4m-15.76 140.4c3.38-30.16 6.77-60.32 15.76-140.4m0 0c-10.83 7.76-21.66 15.53-45.92 32.92m45.92-32.92c-11.69 8.38-23.37 16.75-45.92 32.92m0 0c6.84 24.4 13.69 48.8 30.16 107.48m-30.16-107.48c6.67 23.77 13.33 47.53 30.16 107.48m0 0s0 0 0 0m0 0s0 0 0 0"
/>
</g>
<g fillRule="evenodd">
<path
fill="#943feb"
strokeWidth="0"
d="m111.234 240.434-12.47 16.67-42.36-161.87 58.81-48.3 40.46 5.25-44.44 188.25"
/>
<path
fill="none"
stroke="#410380"
strokeWidth=".5"
d="M111.234 240.434c-3.79 5.06-7.57 10.12-12.47 16.67m12.47-16.67c-4.43 5.93-8.87 11.85-12.47 16.67m0 0c-16.8-64.17-33.59-128.35-42.36-161.87m42.36 161.87c-9.74-37.2-19.47-74.41-42.36-161.87m0 0c15.03-12.35 30.07-24.7 58.81-48.3m-58.81 48.3c22.49-18.47 44.97-36.94 58.81-48.3m0 0c9.48 1.23 18.95 2.46 40.46 5.25m-40.46-5.25c13.01 1.69 26.02 3.38 40.46 5.25m0 0c-10.95 46.41-21.91 92.82-44.44 188.25m44.44-188.25c-12.2 51.71-24.41 103.42-44.44 188.25m0 0s0 0 0 0m0 0s0 0 0 0"
/>
</g>
<g fillRule="evenodd">
<path
fill="#6212b3"
strokeWidth="0"
d="m40.379 235.667 15.9-140.21 42.43 161.79-58.33-21.58"
/>
<path
fill="none"
stroke="#410380"
strokeWidth=".5"
d="M40.379 235.667c4.83-42.62 9.67-85.25 15.9-140.21m-15.9 140.21c5.84-51.52 11.69-103.03 15.9-140.21m0 0c10.98 41.87 21.96 83.74 42.43 161.79m-42.43-161.79c13.28 50.63 26.56 101.25 42.43 161.79m0 0c-11.8-4.37-23.6-8.74-58.33-21.58m58.33 21.58c-21.73-8.04-43.47-16.08-58.33-21.58m0 0s0 0 0 0m0 0s0 0 0 0"
/>
</g>
</svg>
</div>
</label>
<>
<label
className={clsx(
"ToolIcon",
"ToolIcon_size_medium",
{
"is-mobile": isMobile,
},
)}
onClick={() => {
this.toolsRef.current.setTheme(appState.theme);
this.toolsRef.current.toggleVisibility(
appState.zenModeEnabled || isMobile,
);
}}
>
<div className="ToolIcon__icon" aria-hidden="true">
{ICONS.obsidian}
</div>
</label>
{this.renderCustomPens(isMobile,appState)}
{this.renderPinnedScriptButtons(isMobile,appState)}
</>
);
};
}

View File

@@ -2,14 +2,18 @@ import clsx from "clsx";
import { Notice, TFile } from "obsidian";
import * as React from "react";
import { ActionButton } from "./ActionButton";
import { ICONS, stringToSVG } from "./ActionIcons";
import { SCRIPT_INSTALL_FOLDER, CTRL_OR_CMD } from "../Constants";
import { ICONS, saveIcon, stringToSVG } from "./ActionIcons";
import { DEVICE, SCRIPT_INSTALL_FOLDER, VIEW_TYPE_EXCALIDRAW } from "../Constants";
import { insertLaTeXToView, search } from "../ExcalidrawAutomate";
import ExcalidrawView, { TextMode } from "../ExcalidrawView";
import { t } from "../lang/helpers";
import { ReleaseNotes } from "../dialogs/ReleaseNotes";
import { ScriptIconMap } from "../Scripts";
import { getIMGFilename } from "../utils/FileUtils";
import { ScriptInstallPrompt } from "src/dialogs/ScriptInstallPrompt";
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/types";
import { isALT, isCTRL, isSHIFT, mdPropModifier } from "src/utils/ModifierkeyHelper";
import { InsertPDFModal } from "src/dialogs/InsertPDFModal";
declare const PLUGIN_VERSION:string;
const dark = '<svg style="stroke:#ced4da;#212529;color:#ced4da;fill:#ced4da" ';
@@ -28,6 +32,7 @@ export type PanelState = {
theme: "dark" | "light";
excalidrawViewMode: boolean;
minimized: boolean;
isDirty: boolean;
isFullscreen: boolean;
isPreviewMode: boolean;
scriptIconMap: ScriptIconMap;
@@ -46,7 +51,7 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
previousHeight: number = 0;
onRightEdge: boolean = false;
onBottomEdge: boolean = false;
private containerRef: React.RefObject<HTMLDivElement>;
public containerRef: React.RefObject<HTMLDivElement>;
constructor(props: PanelProps) {
super(props);
@@ -59,6 +64,7 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
theme: "dark",
excalidrawViewMode: false,
minimized: false,
isDirty: false,
isFullscreen: false,
isPreviewMode: true,
scriptIconMap: {},
@@ -87,6 +93,14 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
});
}
setDirty(isDirty: boolean) {
this.setState(()=> {
return {
isDirty,
};
});
}
setExcalidrawViewMode(isViewModeEnabled: boolean) {
this.setState(() => {
return {
@@ -257,7 +271,7 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
className="Island App-menu__left scrollbar"
style={{
maxHeight: "350px",
backgroundColor: "transparent",
width: "initial",
//@ts-ignore
"--padding": 2,
display: this.state.minimized ? "none" : "block",
@@ -267,13 +281,13 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
<fieldset>
<legend>Utility actions</legend>
<div className="buttonList buttonListIcon">
<ActionButton
key={"search"}
title={t("SEARCH")}
<ActionButton
key={"scriptEngine"}
title={t("INSTALL_SCRIPT_BUTTON")}
action={() => {
search(this.props.view);
new ScriptInstallPrompt(this.props.view.plugin).open();
}}
icon={ICONS.search}
icon={ICONS.scriptEngine}
view={this.props.view}
/>
<ActionButton
@@ -348,6 +362,67 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
}
view={this.props.view}
/>
<ActionButton
key={"search"}
title={t("SEARCH")}
action={() => {
search(this.props.view);
}}
icon={ICONS.search}
view={this.props.view}
/>
<ActionButton
key={"ocr"}
title={t("RUN_OCR")}
action={(e:React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
if(!this.props.view.plugin.settings.taskboneEnabled) {
new Notice("Taskbone OCR is not enabled. Please go to plugins settings to enable it.",4000);
return;
}
this.props.view.plugin.taskbone.getTextForView(this.props.view, isCTRL(e));
}}
icon={ICONS.ocr}
view={this.props.view}
/>
<ActionButton
key={"openLink"}
title={t("OPEN_LINK_CLICK")}
action={(e) => {
const event = new MouseEvent("click", {
ctrlKey: e.ctrlKey || !(DEVICE.isIOS || DEVICE.isMacOS),
metaKey: e.metaKey || (DEVICE.isIOS || DEVICE.isMacOS),
shiftKey: e.shiftKey,
altKey: e.altKey,
});
this.props.view.handleLinkClick(event);
}}
icon={ICONS.openLink}
view={this.props.view}
/>
<ActionButton
key={"openLinkProperties"}
title={t("OPEN_LINK_PROPS")}
action={() => {
const event = new MouseEvent("click", {
ctrlKey: true,
metaKey: true,
shiftKey: false,
altKey: false,
});
this.props.view.handleLinkClick(event);
}}
icon={ICONS.openLinkProperties}
view={this.props.view}
/>
<ActionButton
key={"save"}
title={t("FORCE_SAVE")}
action={() => {
this.props.view.forceSave();
}}
icon={saveIcon(this.state.isDirty)}
view={this.props.view}
/>
</div>
</fieldset>
<fieldset>
@@ -427,6 +502,17 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
icon={ICONS.insertImage}
view={this.props.view}
/>
<ActionButton
key={"pdf"}
title={t("INSERT_PDF")}
action={() => {
this.props.centerPointer();
const insertPDFModal = new InsertPDFModal(this.props.view.plugin, this.props.view);
insertPDFModal.open();
}}
icon={ICONS.insertPDF}
view={this.props.view}
/>
<ActionButton
key={"insertMD"}
title={t("INSERT_MD")}
@@ -442,7 +528,11 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
<ActionButton
key={"latex"}
title={t("INSERT_LATEX")}
action={() => {
action={(e) => {
if(isALT(e)) {
this.props.view.openExternalLink("https://youtu.be/r08wk-58DPk");
return;
}
this.props.centerPointer();
insertLaTeXToView(this.props.view);
}}
@@ -466,8 +556,12 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
key={"link-to-element"}
title={t("INSERT_LINK_TO_ELEMENT")}
action={(e:React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
if(isALT(e)) {
this.props.view.openExternalLink("https://youtu.be/yZQoJg2RCKI");
return;
}
this.props.view.copyLinkToSelectedElementToClipboard(
e[CTRL_OR_CMD] ? "group=" : (e.shiftKey ? "area=" : "")
isCTRL(e) ? "group=" : (isSHIFT(e) ? "area=" : "")
);
}}
icon={ICONS.copyElementLink}
@@ -512,47 +606,72 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
return "";
}
const groups = new Set<string>();
Object.keys(this.state.scriptIconMap)
.filter((k) => filterCondition(k))
.forEach(k => groups.add(this.state.scriptIconMap[k].group))
const scriptlist = Array.from(groups).sort((a,b)=>a>b?1:-1);
scriptlist.push(scriptlist.shift());
return (
<fieldset>
<legend>{isDownloaded ? "Downloaded" : "User"} Scripts</legend>
<div className="buttonList buttonListIcon">
{Object.keys(this.state.scriptIconMap)
.filter((k) => filterCondition(k))
.sort()
.map((key: string) => (
<ActionButton
key={key}
title={
isDownloaded
? this.state.scriptIconMap[key].name.replace(
`${SCRIPT_INSTALL_FOLDER}/`,
"",
)
: this.state.scriptIconMap[key].name
}
action={async () => {
const f =
this.props.view.app.vault.getAbstractFileByPath(key);
if (f && f instanceof TFile) {
this.props.view.plugin.scriptEngine.executeScript(
this.props.view,
await this.props.view.plugin.app.vault.read(f),
this.props.view.plugin.scriptEngine.getScriptName(f)
);
<>
{scriptlist.map(group => (
<fieldset>
<legend>{isDownloaded ? group : (group === "" ? "User" : "User/"+group)}</legend>
<div className="buttonList buttonListIcon">
{Object.entries(this.state.scriptIconMap)
.filter(([k,v])=>v.group === group)
.sort()
.map(([key,value])=>(
<ActionButton
key={key}
title={value.name}
action={async () => {
const view = this.props.view;
const plugin = view.plugin;
const f = app.vault.getAbstractFileByPath(key);
if (f && f instanceof TFile) {
plugin.scriptEngine.executeScript(
view,
await app.vault.read(f),
plugin.scriptEngine.getScriptName(f),
f
);
}
}}
longpress={async () => {
const view = this.props.view;
const api = view.excalidrawAPI as ExcalidrawImperativeAPI;
const plugin = view.plugin;
await plugin.loadSettings();
const index = plugin.settings.pinnedScripts.indexOf(key)
if(index > -1) {
plugin.settings.pinnedScripts.splice(index,1);
api?.setToast({message:`Pin removed: ${value.name}`, duration: 3000, closable: true});
} else {
plugin.settings.pinnedScripts.push(key);
api?.setToast({message:`Pinned: ${value.name}`, duration: 3000, closable: true})
}
await plugin.saveSettings();
app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW).forEach(v=> {
if (v.view instanceof ExcalidrawView) v.view.updatePinnedScripts()
})
}}
icon={
value.svgString
? stringToSVG(value.svgString)
: (
ICONS.cog
)
}
}}
icon={
this.state.scriptIconMap[key].svgString
? stringToSVG(this.state.scriptIconMap[key].svgString)
: (
ICONS.cog
)
}
view={this.props.view}
/>
))}
</div>
</fieldset>
view={this.props.view}
/>
))}
</div>
</fieldset>
))}
</>
);
}
}

137
src/ocr/Taskbone.ts Normal file
View File

@@ -0,0 +1,137 @@
import { createPNG, ExcalidrawAutomate } from "../ExcalidrawAutomate";
import {Notice, requestUrl} from "obsidian"
import ExcalidrawPlugin from "../main"
import {log} from "../utils/Utils"
import ExcalidrawView, { ExportSettings } from "../ExcalidrawView"
import FrontmatterEditor from "src/utils/Frontmatter";
import { ExcalidrawElement, ExcalidrawImageElement } from "@zsviczian/excalidraw/types/element/types";
import { EmbeddedFilesLoader } from "src/EmbeddedFileLoader";
import { blobToBase64 } from "src/utils/FileUtils";
const TASKBONE_URL = "https://api.taskbone.com/"; //"https://excalidraw-preview.onrender.com/";
const TASKBONE_OCR_FN = "execute?id=60f394af-85f6-40bc-9613-5d26dc283cbb";
export default class Taskbone {
get apiKey() {
return this.plugin.settings.taskboneAPIkey;
}
constructor(
private plugin: ExcalidrawPlugin
) {
}
public async initialize(save:boolean = true):Promise<string> {
if(this.plugin.settings.taskboneAPIkey !== "") return;
const response = await requestUrl({
url: `${TASKBONE_URL}users/excalidraw-obsidian/identities`,
method: "post",
contentType: "application/json",
throw: false
});
if(!response) return;
const apiKey = response.json?.apiKey;
if(apiKey && typeof apiKey === "string") {
if(save) await this.plugin.loadSettings();
this.plugin.settings.taskboneAPIkey = apiKey;
if(save) await this.plugin.saveSettings();
}
return apiKey;
}
public async getTextForView(view: ExcalidrawView, forceReScan: boolean) {
await view.forceSave(true);
const viewElements = view.excalidrawAPI.getSceneElements().filter((el:ExcalidrawElement) =>
el.type==="freedraw" ||
( el.type==="image" &&
!this.plugin.isExcalidrawFile(view.excalidrawData.getFile(el.fileId)?.file)
));
if(viewElements.length === 0) {
new Notice ("Aborting OCR because there are no image or freedraw elements on the canvas.",4000);
return;
}
const fe = new FrontmatterEditor(view.data);
if(fe.hasKey("taskbone-ocr") && !forceReScan) {
new Notice ("The drawing has already been processed, you will find the result in the frontmatter in markdown view mode. If you ran the command from the Obsidian Panel in Excalidraw then you can CTRL(CMD)+click the command to force the rescaning.",4000)
return;
}
const bb = this.plugin.ea.getBoundingBox(viewElements);
const size = (bb.width*bb.height);
const minRatio = Math.sqrt(360000/size);
const maxRatio = Math.sqrt(size/16000000);
const scale = minRatio > 1
? minRatio
: (
maxRatio > 1
? 1/maxRatio
: 1
);
const loader = new EmbeddedFilesLoader(
this.plugin,
false,
);
const exportSettings: ExportSettings = {
withBackground: true,
withTheme: true,
};
const img =
await createPNG(
view.file.path + "#^taskbone",
scale,
exportSettings,
loader,
"light",
null,
null,
[],
this.plugin,
0
);
const text = await this.getTextForImage(img);
if(text) {
fe.setKey("taskbone-ocr",text);
view.data = fe.data;
view.save(false);
window.navigator.clipboard.writeText(text);
new Notice("I placed the recognized in the drawing's frontmatter and onto the system clipboard.");
}
}
private async getTextForImage(image: Blob):Promise<string> {
const url = TASKBONE_URL+TASKBONE_OCR_FN;
if(this.apiKey === "") {
await this.initialize();
}
const base64Image = await blobToBase64(image);
const input = {
records: [{
image: base64Image
}]
};
const apiResponse = await requestUrl ({
url: url,
method: "post",
contentType: "application/json",
body: JSON.stringify(input),
headers: {
authorization: `Bearer ${this.apiKey}`
},
throw: false
});
const content = apiResponse?.json;
if(!content || apiResponse.status !== 200) {
new Notice("Something went wrong while processing your request. Please check developer console for more information");
log(apiResponse);
return;
}
return content.records[0].text;
}
}

View File

@@ -7,14 +7,18 @@ import {
TextComponent,
TFile,
} from "obsidian";
import { VIEW_TYPE_EXCALIDRAW } from "./Constants";
import { GITHUB_RELEASES, VIEW_TYPE_EXCALIDRAW } from "./Constants";
import ExcalidrawView from "./ExcalidrawView";
import { t } from "./lang/helpers";
import type ExcalidrawPlugin from "./main";
import { PenStyle } from "./PenTypes";
import { DynamicStyle } from "./types";
import { setDynamicStyle } from "./utils/DynamicStyling";
import {
getDrawingFilename,
getEmbedFilename,
} from "./utils/FileUtils";
import { PENS } from "./utils/Pens";
import {
fragWithHTML,
setLeftHandedMode,
@@ -28,6 +32,8 @@ export interface ExcalidrawSettings {
compress: boolean;
autosave: boolean;
autosaveInterval: number;
autosaveIntervalDesktop: number;
autosaveIntervalMobile: number;
drawingFilenamePrefix: string;
drawingEmbedPrefixWithFilename: boolean;
drawingFilnameEmbedPostfix: string;
@@ -37,12 +43,16 @@ export interface ExcalidrawSettings {
displayExportedImageIfAvailable: boolean;
previewMatchObsidianTheme: boolean;
width: string;
dynamicStyling: DynamicStyle;
isLeftHanded: boolean;
matchTheme: boolean;
matchThemeAlways: boolean;
matchThemeTrigger: boolean;
defaultMode: string;
defaultPenMode: "never" | "mobile" | "always";
allowPinchZoom: boolean;
allowWheelZoom: boolean;
zoomToFitOnOpen: boolean;
zoomToFitOnResize: boolean;
zoomToFitMaxLevel: number;
openInAdjacentPane: boolean;
@@ -110,8 +120,22 @@ export interface ExcalidrawSettings {
showReleaseNotes: boolean;
showNewVersionNotification: boolean;
mathjaxSourceURL: string;
latexBoilerplate: string;
taskboneEnabled: boolean;
taskboneAPIkey: string;
pinnedScripts: string[];
customPens: PenStyle[];
numberOfCustomPens: number;
pdfScale: number;
pdfBorderBox: boolean;
pdfGapSize: number;
pdfLockAfterImport: boolean;
pdfNumColumns: number;
pdfImportScale: number;
}
declare const PLUGIN_VERSION:string;
export const DEFAULT_SETTINGS: ExcalidrawSettings = {
folder: "Excalidraw",
embedUseExcalidrawFolder: false,
@@ -120,6 +144,8 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
compress: false,
autosave: true,
autosaveInterval: 15000,
autosaveIntervalDesktop: 15000,
autosaveIntervalMobile: 10000,
drawingFilenamePrefix: "Drawing ",
drawingEmbedPrefixWithFilename: true,
drawingFilnameEmbedPostfix: " ",
@@ -129,12 +155,16 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
displayExportedImageIfAvailable: false,
previewMatchObsidianTheme: false,
width: "400",
dynamicStyling: "colorful",
isLeftHanded: false,
matchTheme: false,
matchThemeAlways: false,
matchThemeTrigger: false,
defaultMode: "normal",
defaultPenMode: "never",
allowPinchZoom: false,
allowWheelZoom: false,
zoomToFitOnOpen: true,
zoomToFitOnResize: true,
zoomToFitMaxLevel: 2,
linkPrefix: "📍",
@@ -178,7 +208,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
library2: {
type: "excalidrawlib",
version: 2,
source: "https://excalidraw.com",
source: GITHUB_RELEASES+PLUGIN_VERSION,
libraryItems: [],
},
//patchCommentBlock: true,
@@ -192,17 +222,42 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
mdBorderColor: "Black",
mdCSS: "",
scriptEngineSettings: {},
defaultTrayMode: false,
previousRelease: "1.6.13",
defaultTrayMode: true,
previousRelease: "0.0.0",
showReleaseNotes: true,
showNewVersionNotification: true,
mathjaxSourceURL: "https://cdn.jsdelivr.net/npm/mathjax@3.2.1/es5/tex-svg.js"
mathjaxSourceURL: "https://cdn.jsdelivr.net/npm/mathjax@3.2.1/es5/tex-svg.js",
latexBoilerplate: "\\color{blue}",
taskboneEnabled: false,
taskboneAPIkey: "",
pinnedScripts: [],
customPens: [
{...PENS["default"]},
{...PENS["highlighter"]},
{...PENS["finetip"]},
{...PENS["fountain"]},
{...PENS["marker"]},
{...PENS["thick-thin"]},
{...PENS["thin-thick-thin"]},
{...PENS["default"]},
{...PENS["default"]},
{...PENS["default"]}
],
numberOfCustomPens: 0,
pdfScale: 4,
pdfBorderBox: true,
pdfGapSize: 20,
pdfLockAfterImport: true,
pdfNumColumns: 1,
pdfImportScale: 0.3,
};
export class ExcalidrawSettingTab extends PluginSettingTab {
plugin: ExcalidrawPlugin;
private requestEmbedUpdate: boolean = false;
private requestReloadDrawings: boolean = false;
private requestUpdatePinnedPens: boolean = false;
private requestUpdateDynamicStyling: boolean = false;
private reloadMathJax: boolean = false;
//private applyDebounceTimer: number = 0;
@@ -228,6 +283,19 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.plugin.settings.scriptFolderPath = "Excalidraw/Scripts";
}
this.plugin.saveSettings();
if (this.requestUpdatePinnedPens) {
app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW).forEach(v=> {
if (v.view instanceof ExcalidrawView) v.view.updatePinnedCustomPens()
})
}
if (this.requestUpdateDynamicStyling) {
app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW).forEach(v=> {
if (v.view instanceof ExcalidrawView) {
setDynamicStyle(this.plugin.ea,v.view,v.view.previousBackgroundColor,this.plugin.settings.dynamicStyling);
}
})
}
if (this.requestReloadDrawings) {
const exs =
app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW);
@@ -254,6 +322,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.requestEmbedUpdate = false;
this.requestReloadDrawings = false;
const { containerEl } = this;
containerEl.addClass("excalidraw-settings");
this.containerEl.empty();
const coffeeDiv = containerEl.createDiv("coffee");
@@ -343,6 +412,8 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}),
);
this.containerEl.createEl("h1", { text: t("SAVING_HEAD") });
new Setting(containerEl)
.setName(t("COMPRESS_NAME"))
.setDesc(fragWithHTML(t("COMPRESS_DESC")))
@@ -353,7 +424,45 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.plugin.settings.compress = value;
this.applySettingsUpdate();
}),
);
);
new Setting(containerEl)
.setName(t("AUTOSAVE_INTERVAL_DESKTOP_NAME"))
.setDesc(fragWithHTML(t("AUTOSAVE_INTERVAL_DESKTOP_DESC")))
.addDropdown((dropdown) =>
dropdown
.addOption("15000", "Frequent (every 15 seconds)")
.addOption("60000", "Moderate (every 60 seconds)")
.addOption("300000", "Rare (every 5 minutes)")
.addOption("900000", "Practically never (every 15 minutes)")
.setValue(this.plugin.settings.autosaveIntervalDesktop.toString())
.onChange(async (value) => {
this.plugin.settings.autosaveIntervalDesktop = parseInt(value);
this.plugin.settings.autosaveInterval = app.isMobile
? this.plugin.settings.autosaveIntervalMobile
: this.plugin.settings.autosaveIntervalDesktop;
this.applySettingsUpdate();
}),
);
new Setting(containerEl)
.setName(t("AUTOSAVE_INTERVAL_MOBILE_NAME"))
.setDesc(fragWithHTML(t("AUTOSAVE_INTERVAL_MOBILE_DESC")))
.addDropdown((dropdown) =>
dropdown
.addOption("10000", "Frequent (every 10 seconds)")
.addOption("30000", "Moderate (every 30 seconds)")
.addOption("60000", "Rare (every 1 minute)")
.addOption("300000", "Practically never (every 5 minutes)")
.setValue(this.plugin.settings.autosaveIntervalMobile.toString())
.onChange(async (value) => {
this.plugin.settings.autosaveIntervalMobile = parseInt(value);
this.plugin.settings.autosaveInterval = app.isMobile
? this.plugin.settings.autosaveIntervalMobile
: this.plugin.settings.autosaveIntervalDesktop;
this.applySettingsUpdate();
}),
);
this.containerEl.createEl("h1", { text: t("FILENAME_HEAD") });
containerEl.createDiv("", (el) => {
@@ -458,6 +567,22 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.containerEl.createEl("h1", { text: t("DISPLAY_HEAD") });
new Setting(containerEl)
.setName(t("DYNAMICSTYLE_NAME"))
.setDesc(fragWithHTML(t("DYNAMICSTYLE_DESC")))
.addDropdown((dropdown) =>
dropdown
.addOption("none","Dynamic Styling OFF")
.addOption("colorful","Match color")
.addOption("gray","Gray, match tone")
.setValue(this.plugin.settings.dynamicStyling)
.onChange(async (value) => {
this.requestUpdateDynamicStyling = true;
this.plugin.settings.dynamicStyling = value as DynamicStyle;
this.applySettingsUpdate();
}),
);
new Setting(containerEl)
.setName(t("LEFTHANDED_MODE_NAME"))
.setDesc(fragWithHTML(t("LEFTHANDED_MODE_DESC")))
@@ -515,9 +640,10 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("DEFAULT_OPEN_MODE_DESC")))
.addDropdown((dropdown) =>
dropdown
.addOption("normal", "Normal Mode")
.addOption("zen", "Zen Mode")
.addOption("view", "View Mode")
.addOption("normal", "Always in normal-mode")
.addOption("zen", "Always in zen-mode")
.addOption("view", "Always in view-mode")
.addOption("view-mobile", "Usually normal, but view-mode on Phone")
.setValue(this.plugin.settings.defaultMode)
.onChange(async (value) => {
this.plugin.settings.defaultMode = value;
@@ -540,6 +666,48 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}),
);
new Setting(containerEl)
.setName(t("DEFAULT_PINCHZOOM_NAME"))
.setDesc(fragWithHTML(t("DEFAULT_PINCHZOOM_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.allowPinchZoom)
.onChange(async (value) => {
this.plugin.settings.allowPinchZoom = value;
app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW).forEach(v=> {
if (v.view instanceof ExcalidrawView) v.view.updatePinchZoom()
})
this.applySettingsUpdate();
}),
);
new Setting(containerEl)
.setName(t("DEFAULT_WHEELZOOM_NAME"))
.setDesc(fragWithHTML(t("DEFAULT_WHEELZOOM_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.allowWheelZoom)
.onChange(async (value) => {
this.plugin.settings.allowWheelZoom = value;
app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW).forEach(v=> {
if (v.view instanceof ExcalidrawView) v.view.updateWheelZoom()
})
this.applySettingsUpdate();
}),
);
new Setting(containerEl)
.setName(t("ZOOM_TO_FIT_ONOPEN_NAME"))
.setDesc(fragWithHTML(t("ZOOM_TO_FIT_ONOPEN_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.zoomToFitOnOpen)
.onChange(async (value) => {
this.plugin.settings.zoomToFitOnOpen = value;
this.applySettingsUpdate();
}),
);
new Setting(containerEl)
.setName(t("ZOOM_TO_FIT_NAME"))
.setDesc(fragWithHTML(t("ZOOM_TO_FIT_DESC")))
@@ -1228,6 +1396,70 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
}),
);
this.containerEl.createEl("h1", { text: t("NONSTANDARD_HEAD") });
this.containerEl.createEl("p", { text: t("NONSTANDARD_DESC") });
new Setting(containerEl)
.setName(t("CUSTOM_PEN_NAME"))
.setDesc(t("CUSTOM_PEN_DESC"))
.addDropdown((dropdown) =>
dropdown
.addOption("0","0")
.addOption("1","1")
.addOption("2","2")
.addOption("3","3")
.addOption("4","4")
.addOption("5","5")
.addOption("6","6")
.addOption("7","7")
.addOption("8","8")
.addOption("9","9")
.addOption("10","10")
.setValue(this.plugin.settings.numberOfCustomPens.toString())
.onChange((value)=>{
this.plugin.settings.numberOfCustomPens = parseInt(value);
this.requestUpdatePinnedPens = true;
this.applySettingsUpdate(false);
})
)
new Setting(containerEl)
.setName(t("ENABLE_FOURTH_FONT_NAME"))
.setDesc(fragWithHTML(t("ENABLE_FOURTH_FONT_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.experimentalEnableFourthFont)
.onChange(async (value) => {
this.requestReloadDrawings = true;
this.plugin.settings.experimentalEnableFourthFont = value;
this.applySettingsUpdate();
}),
);
new Setting(containerEl)
.setName(t("FOURTH_FONT_NAME"))
.setDesc(fragWithHTML(t("FOURTH_FONT_DESC")))
.addDropdown(async (d: DropdownComponent) => {
d.addOption("Virgil", "Virgil");
this.app.vault
.getFiles()
.filter((f) => ["ttf", "woff", "woff2"].contains(f.extension))
.forEach((f: TFile) => {
d.addOption(f.path, f.name);
});
d.setValue(this.plugin.settings.experimantalFourthFont).onChange(
(value) => {
this.requestReloadDrawings = true;
this.plugin.settings.experimantalFourthFont = value;
this.applySettingsUpdate(true);
this.plugin.initializeFourthFont();
},
);
});
this.containerEl.createEl("h1", { text: t("EXPERIMENTAL_HEAD") });
this.containerEl.createEl("p", { text: t("EXPERIMENTAL_DESC") });
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/628
new Setting(containerEl)
@@ -1245,10 +1477,18 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
})
})
this.containerEl.createEl("h1", { text: t("EXPERIMENTAL_HEAD") });
this.containerEl.createEl("p", { text: t("EXPERIMENTAL_DESC") });
new Setting(containerEl)
.setName(t("LATEX_DEFAULT_NAME"))
.setDesc(fragWithHTML(t("LATEX_DEFAULT_DESC")))
.addText((text) =>
text
.setValue(this.plugin.settings.latexBoilerplate)
.onChange( (value) => {
this.plugin.settings.latexBoilerplate = value;
this.applySettingsUpdate();
}),
);
new Setting(containerEl)
.setName(t("FIELD_SUGGESTER_NAME"))
@@ -1300,39 +1540,43 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}),
);
new Setting(containerEl)
.setName(t("ENABLE_FOURTH_FONT_NAME"))
.setDesc(fragWithHTML(t("ENABLE_FOURTH_FONT_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.experimentalEnableFourthFont)
.onChange(async (value) => {
this.requestReloadDrawings = true;
this.plugin.settings.experimentalEnableFourthFont = value;
this.applySettingsUpdate();
}),
);
this.containerEl.createEl("h2", { text: t("TASKBONE_HEAD") });
this.containerEl.createEl("p", { text: t("TASKBONE_DESC") });
let taskboneAPIKeyText: TextComponent;
new Setting(containerEl)
.setName(t("FOURTH_FONT_NAME"))
.setDesc(fragWithHTML(t("FOURTH_FONT_DESC")))
.addDropdown(async (d: DropdownComponent) => {
d.addOption("Virgil", "Virgil");
this.app.vault
.getFiles()
.filter((f) => ["ttf", "woff", "woff2"].contains(f.extension))
.forEach((f: TFile) => {
d.addOption(f.path, f.name);
});
d.setValue(this.plugin.settings.experimantalFourthFont).onChange(
(value) => {
this.requestReloadDrawings = true;
this.plugin.settings.experimantalFourthFont = value;
this.applySettingsUpdate(true);
this.plugin.initializeFourthFont();
},
);
});
.setName(t("TASKBONE_ENABLE_NAME"))
.setDesc(fragWithHTML(t("TASKBONE_ENABLE_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.taskboneEnabled)
.onChange(async (value) => {
taskboneAPIKeyText.setDisabled(!value);
this.plugin.settings.taskboneEnabled = value;
if(this.plugin.settings.taskboneAPIkey === "") {
const apiKey = await this.plugin.taskbone.initialize(false);
if(apiKey) {
taskboneAPIKeyText.setValue(apiKey);
}
}
this.applySettingsUpdate();
}),
);
new Setting(containerEl)
.setName(t("TASKBONE_APIKEY_NAME"))
.setDesc(fragWithHTML(t("TASKBONE_APIKEY_DESC")))
.addText((text) => {
taskboneAPIKeyText = text;
taskboneAPIKeyText
.setValue(this.plugin.settings.taskboneAPIkey)
.onChange(async (value) => {
this.plugin.settings.taskboneAPIkey = value;
this.applySettingsUpdate();
})
.setDisabled(!this.plugin.settings.taskboneEnabled);
}
);
//-------------------------------------
//Script settings

View File

@@ -15,7 +15,7 @@ export function get(el: Element, attr: string, backup?: string): string {
export function getNum(el: Element, attr: string, backup?: number): number {
const numVal = Number(get(el, attr));
return numVal === NaN ? backup || 0 : numVal;
return Number.isNaN(numVal) ? backup || 0 : numVal;
}
const presAttrs = {

View File

@@ -1,6 +1,6 @@
import { randomId, randomInteger } from "../utils";
import { ExcalidrawLinearElement, FillStyle, GroupId, StrokeSharpness, StrokeStyle } from "@zsviczian/excalidraw/types/element/types";
import { ExcalidrawLinearElement, FillStyle, GroupId, RoundnessType, StrokeStyle } from "@zsviczian/excalidraw/types/element/types";
export type Point = [number, number];
@@ -13,7 +13,7 @@ export type ExcalidrawElementBase = {
fillStyle: FillStyle;
strokeWidth: number;
strokeStyle: StrokeStyle;
strokeSharpness: StrokeSharpness;
roundness: null | { type: RoundnessType; value?: number };
roughness: number;
opacity: number;
width: number;
@@ -71,7 +71,7 @@ export function createExElement(): ExcalidrawElementBase {
fillStyle: "solid",
strokeWidth: 1,
strokeStyle: "solid",
strokeSharpness: "sharp",
roundness: null,
roughness: 0,
opacity: 100,
width: 0,

View File

@@ -1,9 +1,11 @@
import { GITHUB_RELEASES } from "src/Constants";
import { ExcalidrawGenericElement } from "./ExcalidrawElement";
declare const PLUGIN_VERSION:string;
class ExcalidrawScene {
type = "excalidraw";
version = 2;
source = "https://excalidraw.com";
source = GITHUB_RELEASES+PLUGIN_VERSION;
elements: ExcalidrawGenericElement[] = [];
constructor(elements:any = []) {

Some files were not shown because too many files have changed in this diff Show More