Compare commits
110 Commits
1.8.4
...
1.9.6.1-be
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
81fc788adc | ||
|
|
834343f821 | ||
|
|
6b4f9fddae | ||
|
|
fa86ef1136 | ||
|
|
bf20919552 | ||
|
|
5931be2aa4 | ||
|
|
ef20226ace | ||
|
|
fdec83d3a4 | ||
|
|
90b1bcbc3b | ||
|
|
c3650fd0ff | ||
|
|
ba8c2a7995 | ||
|
|
1a0783b56a | ||
|
|
e9bce326f9 | ||
|
|
0956f41b92 | ||
|
|
25473770c6 | ||
|
|
81c5a2cca1 | ||
|
|
90bc310643 | ||
|
|
b8ab8e1084 | ||
|
|
cc7d3d894c | ||
|
|
8d04ac01a1 | ||
|
|
81ddbec324 | ||
|
|
35bc366f10 | ||
|
|
9aee982e8e | ||
|
|
5638f91b25 | ||
|
|
443fd0eae3 | ||
|
|
454db1f315 | ||
|
|
c3440e2b54 | ||
|
|
0b51636d8a | ||
|
|
f52b011817 | ||
|
|
7b76acd9c9 | ||
|
|
2de1ba1f45 | ||
|
|
5e702499b0 | ||
|
|
79d67bc1f4 | ||
|
|
9fca82bb6f | ||
|
|
00c801e338 | ||
|
|
dd0c0cd021 | ||
|
|
12594baac6 | ||
|
|
b03bd7e4f9 | ||
|
|
02b21aeea9 | ||
|
|
a67bdfa5e8 | ||
|
|
52407e89fb | ||
|
|
7e930c2339 | ||
|
|
7ab8f07d1f | ||
|
|
d34086a395 | ||
|
|
334f122cca | ||
|
|
f80202e5e7 | ||
|
|
29736f10fc | ||
|
|
0654663dff | ||
|
|
4e12f7cc4c | ||
|
|
a42dbc0cdc | ||
|
|
5c40cdb3d3 | ||
|
|
d47a206206 | ||
|
|
ba0eaf067b | ||
|
|
f80edce3dc | ||
|
|
21968214af | ||
|
|
7770eb51dc | ||
|
|
d0229259a6 | ||
|
|
00cbea3705 | ||
|
|
e85857c29f | ||
|
|
1704a016b1 | ||
|
|
f5af19557a | ||
|
|
17b8b154c2 | ||
|
|
5c1030880a | ||
|
|
1b62983016 | ||
|
|
52fb7ab546 | ||
|
|
604bfbf23f | ||
|
|
3c1a3c18c2 | ||
|
|
f531c361de | ||
|
|
4609ea33bb | ||
|
|
41b1a170f7 | ||
|
|
e6d39eca75 | ||
|
|
2a1e3731ba | ||
|
|
8ca6a9fe96 | ||
|
|
6f2248ffa0 | ||
|
|
48e47f333e | ||
|
|
3091ed629a | ||
|
|
a9193dd695 | ||
|
|
3122e86e22 | ||
|
|
a6efe27146 | ||
|
|
adbec35e30 | ||
|
|
205a94d3a3 | ||
|
|
6e88c8f0eb | ||
|
|
32a05322d0 | ||
|
|
8738b74236 | ||
|
|
aa0ddd85fd | ||
|
|
bcd47ddb8e | ||
|
|
50f24b42cb | ||
|
|
0a5d511c96 | ||
|
|
70d93602f7 | ||
|
|
68c7c9f55e | ||
|
|
42f1fa88b9 | ||
|
|
3a2d064024 | ||
|
|
38cfdd4e0e | ||
|
|
fb93c0c352 | ||
|
|
f4fb1e3cc8 | ||
|
|
5c11e5733e | ||
|
|
8d8f7a7866 | ||
|
|
da89e32213 | ||
|
|
b6d36e5076 | ||
|
|
90c377f125 | ||
|
|
df85138890 | ||
|
|
654b656a2f | ||
|
|
1d22dcb488 | ||
|
|
a42e907d0c | ||
|
|
353cad21d6 | ||
|
|
2b02f186a6 | ||
|
|
3e12d1e815 | ||
|
|
539bbdf07f | ||
|
|
b993b358fe | ||
|
|
0639ea5969 |
7
.gitignore
vendored
@@ -15,5 +15,8 @@ data.json
|
||||
lib
|
||||
|
||||
#VSCode
|
||||
.vscode
|
||||
yarn.lock
|
||||
.vscode
|
||||
yarn.lock
|
||||
.DS_Store
|
||||
.lock
|
||||
.lock
|
||||
|
||||
32
README-BUILD.md
Normal 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"
|
||||
}
|
||||
```
|
||||
84
README.md
@@ -27,7 +27,7 @@ The Obsidian-Excalidraw plugin integrates [Excalidraw](https://excalidraw.com/),
|
||||
</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;"/> 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;"/> Script Enginge Store</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;"/> Script Engine 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;"/> Colors - Excalidraw Basics (Custom)</a><br>
|
||||
@@ -44,10 +44,11 @@ The Obsidian-Excalidraw plugin integrates [Excalidraw](https://excalidraw.com/),
|
||||
</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;"/> 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;"/> Fourt Font</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;"/> Fourth 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;"/> 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;"/> 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;"/> 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;"/> 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;"/> Mobile Support</a><br>
|
||||
@@ -68,9 +69,20 @@ The Obsidian-Excalidraw plugin integrates [Excalidraw](https://excalidraw.com/),
|
||||
|
||||
### Settings
|
||||
|
||||
Settings will allow you to customize Excalidraw to your needs:
|
||||
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.
|
||||
|
||||
- Default folder for new drawings and define custom filename pattern for new drawings.
|
||||
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
|
||||
|
||||
@@ -101,8 +113,7 @@ Settings will allow you to customize Excalidraw to your needs:
|
||||
- Experimental feature to add custom TAG to file explorer to mark drawing files.
|
||||
- Enable / disable autosave.
|
||||
|
||||
### Embedded images
|
||||
|
||||
### 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]]`,
|
||||
@@ -112,9 +123,13 @@ Settings will allow you to customize Excalidraw to your needs:
|
||||
- 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
|
||||
### Hyperlinks and Drag & Drop support
|
||||

|
||||
|
||||
#### Hyperlinks
|
||||
- Supports hyperlinks e.g.
|
||||
- `https://zsolt.blog`,
|
||||
- `[Obsidian](https://obsidian.md)`, and
|
||||
@@ -129,25 +144,11 @@ Settings will allow you to customize Excalidraw to your needs:
|
||||
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
|
||||
- Using the block reference you can also reference & transclude text that appears on drawings, in other documents
|
||||
|
||||
### 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.
|
||||
|
||||
### 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
|
||||
#### 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,
|
||||
@@ -159,15 +160,22 @@ You can edit formulas either in Markdown view, or by <kbd>CTRL/CMD + Click</kbd>
|
||||
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]]`,
|
||||
@@ -186,7 +194,6 @@ You can edit formulas either in Markdown view, or by <kbd>CTRL/CMD + Click</kbd>
|
||||
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
|
||||
@@ -204,8 +211,7 @@ You can edit formulas either in Markdown view, or by <kbd>CTRL/CMD + Click</kbd>
|
||||
- `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.
|
||||
- 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.
|
||||
@@ -216,7 +222,7 @@ You can edit formulas either in Markdown view, or by <kbd>CTRL/CMD + Click</kbd>
|
||||
- (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
|
||||
- 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:
|
||||
@@ -225,21 +231,27 @@ You can edit formulas either in Markdown view, or by <kbd>CTRL/CMD + Click</kbd>
|
||||
- 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:
|
||||
- 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]]`
|
||||
|
||||
### Other
|
||||
### 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.
|
||||
- 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).
|
||||
- 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.
|
||||
|
||||
|
||||
14
TODO.md
@@ -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
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -67,6 +67,7 @@ if(!isFirst) {
|
||||
ea.copyViewElementsToEAforEditing([fromElement]);
|
||||
|
||||
const previousTextElements = elements.filter((el)=>el.type==="text");
|
||||
const previousRectElements = elements.filter((el)=>el.type==="rectangle");
|
||||
if(previousTextElements.length>0) {
|
||||
const el = previousTextElements[0];
|
||||
ea.style.strokeColor = el.strokeColor;
|
||||
@@ -85,7 +86,8 @@ if(!isFirst) {
|
||||
{
|
||||
wrapAt: wrapLineLen,
|
||||
textAlign: "center",
|
||||
box: "rectangle",
|
||||
textVerticalAlign: "middle",
|
||||
box: previousRectElements.length > 0 ? "rectangle" : false,
|
||||
...fixWidth
|
||||
? {width: width, boxPadding:0}
|
||||
: {boxPadding: textPadding}
|
||||
@@ -104,14 +106,19 @@ if(!isFirst) {
|
||||
}
|
||||
);
|
||||
|
||||
const rect = ea.getElement(id);
|
||||
rect.strokeColor = fromElement.strokeColor;
|
||||
rect.strokeWidth = fromElement.strokeWidth;
|
||||
rect.strokeStyle = fromElement.strokeStyle;
|
||||
rect.roughness = fromElement.roughness;
|
||||
rect.strokeSharpness = fromElement.strokeSharpness;
|
||||
rect.backgroundColor = fromElement.backgroundColor;
|
||||
rect.fillStyle = fromElement.fillStyle;
|
||||
if (previousRectElements.length>0) {
|
||||
const rect = ea.getElement(id);
|
||||
rect.strokeColor = fromElement.strokeColor;
|
||||
rect.strokeWidth = fromElement.strokeWidth;
|
||||
rect.strokeStyle = fromElement.strokeStyle;
|
||||
rect.roughness = fromElement.roughness;
|
||||
rect.roundness = fromElement.roundness;
|
||||
rect.strokeSharpness = fromElement.strokeSharpness;
|
||||
rect.backgroundColor = fromElement.backgroundColor;
|
||||
rect.fillStyle = fromElement.fillStyle;
|
||||
rect.width = fromElement.width;
|
||||
rect.height = fromElement.height;
|
||||
}
|
||||
|
||||
await ea.addElementsToView(false,false);
|
||||
} else {
|
||||
@@ -122,6 +129,7 @@ if(!isFirst) {
|
||||
{
|
||||
wrapAt: wrapLineLen,
|
||||
textAlign: "center",
|
||||
textVerticalAlign: "middle",
|
||||
box: "rectangle",
|
||||
boxPadding: textPadding,
|
||||
...fixWidth?{width: width}:null
|
||||
|
||||
208
ea-scripts/Alternative Pens.md
Normal file
@@ -0,0 +1,208 @@
|
||||
/*
|
||||
IF YOU ACCIDENTLY MODIFY THIS FILE AND IT STOPS WORKING, SIMPLY DOWNLOAD IT AGAIN FROM THE SCRIPT LIBRARY.
|
||||
|
||||

|
||||
|
||||
# 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"});
|
||||
1
ea-scripts/Alternative Pens.svg
Normal 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 |
67
ea-scripts/Auto Draw for Pen.md
Normal 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 })
|
||||
|
||||
})();
|
||||
50
ea-scripts/Auto Draw for Pen.svg
Normal 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 |
@@ -308,16 +308,8 @@ function loadELK(doAfterLoaded) {
|
||||
function normalizeSelectedArrows() {
|
||||
let gapValue = 2;
|
||||
|
||||
const selectedIndividualArrows = ea
|
||||
.getMaximumGroups(ea.getViewSelectedElements())
|
||||
.reduce(
|
||||
(result, group) =>
|
||||
group.length === 1 &&
|
||||
(group[0].type === "arrow" || group[0].type === "line")
|
||||
? [...result, group[0]]
|
||||
: result,
|
||||
[]
|
||||
);
|
||||
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) {
|
||||
|
||||
@@ -67,5 +67,6 @@ setTimeout(async ()=>{
|
||||
ea.deleteViewElements(els);
|
||||
ea.clear();
|
||||
await ea.addImage(bb.topX,bb.topY,file,false);
|
||||
ea.addElementsToView(false, true, true);
|
||||
await ea.addElementsToView(false, true, true);
|
||||
ea.getExcalidrawAPI().history.clear(); //to avoid undo/redo messing up the decomposition
|
||||
},1000);
|
||||
|
||||
@@ -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;
|
||||
|
||||
12
ea-scripts/Excalidraw Collaboration Frame.md
Normal file
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
Creates a new Excalidraw.com collaboration room and places the link to the room on the clipboard.
|
||||
```js*/
|
||||
const room = Array.from(window.crypto.getRandomValues(new Uint8Array(10))).map((byte) => `0${byte.toString(16)}`.slice(-2)).join("");
|
||||
const key = (await window.crypto.subtle.exportKey("jwk",await window.crypto.subtle.generateKey({name:"AES-GCM",length:128},true,["encrypt", "decrypt"]))).k;
|
||||
const link = `https://excalidraw.com/#room=${room},${key}`;
|
||||
|
||||
ea.addIFrame(0,0,800,600,link);
|
||||
ea.addElementsToView(true,true);
|
||||
|
||||
window.navigator.clipboard.writeText(link);
|
||||
new Notice("The collaboration room link is available on the clipboard.",4000);
|
||||
1
ea-scripts/Excalidraw Collaboration Frame.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"><g stroke-width="1.5"></path><circle cx="9" cy="7" r="4"></circle><path d="M3 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path><path d="M21 21v-2a4 4 0 0 0 -3 -3.85"></path></g></svg>
|
||||
|
After Width: | Height: | Size: 382 B |
@@ -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);
|
||||
@@ -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 |
75
ea-scripts/Hardware Eraser Support.md
Normal 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 })
|
||||
})();
|
||||
23
ea-scripts/Hardware Eraser Support.svg
Normal 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 |
53
ea-scripts/Invert colors.md
Normal file
@@ -0,0 +1,53 @@
|
||||
/*
|
||||

|
||||
|
||||
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()
|
||||
});
|
||||
13
ea-scripts/Invert colors.svg
Normal 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 |
370
ea-scripts/Mindmap format.md
Normal file
@@ -0,0 +1,370 @@
|
||||
/*
|
||||
|
||||
format **the left to right** mind map
|
||||
|
||||

|
||||
|
||||
# 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
|
||||
|
||||

|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
const sceneElements = ea.getExcalidrawAPI().getSceneElements();
|
||||
|
||||
// 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) => {
|
||||
x = parent.x + parent.width + line.points[2][0];
|
||||
y = parent.y + parent.height / 2 + line.points[2][1] - children.height / 2;
|
||||
distX = children.x - x;
|
||||
distY = children.y - y;
|
||||
|
||||
ea.getElementsInTheSameGroupWithElement(children, sceneElements).forEach((el) => {
|
||||
el.x = el.x - distX;
|
||||
el.y = el.y - distY;
|
||||
});
|
||||
|
||||
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);
|
||||
1
ea-scripts/Mindmap format.svg
Normal 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 |
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
@@ -15,15 +23,55 @@ if(elements.length === 0) {
|
||||
elements = [elements[len]];
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
await ea.addElementsToView(false,true);
|
||||
|
||||
37
ea-scripts/PDF Page Text to Clipboard.md
Normal file
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
Copies the text from the selected PDF page on the Excalidraw canvas to the clipboard.
|
||||
|
||||
<iframe width="560" height="315" src="https://www.youtube.com/embed/Kwt_8WdOUT4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
|
||||
Link:: https://youtu.be/Kwt_8WdOUT4
|
||||
|
||||
|
||||
```js*/
|
||||
const el = ea.getViewSelectedElements().filter(el=>el.type==="image")[0];
|
||||
if(!el) {
|
||||
new Notice("Select a PDF page");
|
||||
return;
|
||||
}
|
||||
const f = ea.getViewFileForImageElement(el);
|
||||
if(f.extension.toLowerCase() !== "pdf") {
|
||||
new Notice("Select a PDF page");
|
||||
return;
|
||||
}
|
||||
|
||||
const pageNum = parseInt(ea.targetView.excalidrawData.getFile(el.fileId).linkParts.ref.replace(/\D/g, ""));
|
||||
if(isNaN(pageNum)) {
|
||||
new Notice("Can't find page number");
|
||||
return;
|
||||
}
|
||||
|
||||
const pdfDoc = await window.pdfjsLib.getDocument(app.vault.getResourcePath(f)).promise;
|
||||
const page = await pdfDoc.getPage(pageNum);
|
||||
const text = await page.getTextContent();
|
||||
if(!text) {
|
||||
new Notice("Could not get text");
|
||||
return;
|
||||
}
|
||||
pdfDoc.destroy();
|
||||
window.navigator.clipboard.writeText(
|
||||
text.items.reduce((acc, cur) => acc + cur.str.replace(/\x00/ug, '') + (cur.hasEOL ? "\n" : ""),"")
|
||||
);
|
||||
new Notice("Page text is available on the clipboard");
|
||||
1
ea-scripts/PDF Page Text to Clipboard.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><!--! Font Awesome Pro 6.4.0 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2023 Fonticons, Inc. --><path d="M64 0C28.7 0 0 28.7 0 64V448c0 35.3 28.7 64 64 64H320c35.3 0 64-28.7 64-64V160H256c-17.7 0-32-14.3-32-32V0H64zM256 0V128H384L256 0zM112 256H272c8.8 0 16 7.2 16 16s-7.2 16-16 16H112c-8.8 0-16-7.2-16-16s7.2-16 16-16zm0 64H272c8.8 0 16 7.2 16 16s-7.2 16-16 16H112c-8.8 0-16-7.2-16-16s7.2-16 16-16zm0 64H272c8.8 0 16 7.2 16 16s-7.2 16-16 16H112c-8.8 0-16-7.2-16-16s7.2-16 16-16z"/></svg>
|
||||
|
After Width: | Height: | Size: 622 B |
@@ -1,19 +1,42 @@
|
||||
/*
|
||||
|
||||
|
||||
<iframe width="560" height="315" src="https://www.youtube.com/embed/epYNx2FSf2w" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
|
||||
Link:: https://youtu.be/epYNx2FSf2w
|
||||
|
||||
<iframe width="560" height="315" src="https://www.youtube.com/embed/diBT5iaoAYo" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
|
||||
Link:: https://youtu.be/diBT5iaoAYo
|
||||
|
||||
Design your palette at http://paletton.com/
|
||||
Once you are happy with your colors, click Tables/Export in the bottom right of the screen:
|
||||

|
||||
Then click "Color swatches/as Sketch Palette"
|
||||
|
||||

|
||||
Copy the contents of the page to a markdown file in your vault. Place the file in the Excalidraw/Palettes folder (you can change this folder in settings).
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
```javascript
|
||||
Excalidraw appState Custom Palette Data Object:
|
||||
```js
|
||||
colorPalette: {
|
||||
canvasBackground: [string, string, string, string, string][] | string[],
|
||||
elementBackground: [string, string, string, string, string][] | string[],
|
||||
elementStroke: [string, string, string, string, string][] | string[],
|
||||
topPicks: {
|
||||
canvasBackground: [string, string, string, string, string],
|
||||
elementStroke: [string, string, string, string, string],
|
||||
elementBackground: [string, string, string, string, string]
|
||||
},
|
||||
}
|
||||
|
||||
*/
|
||||
//--------------------------
|
||||
// Load settings
|
||||
//--------------------------
|
||||
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.7.19")) {
|
||||
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.9.2")) {
|
||||
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
|
||||
return;
|
||||
}
|
||||
@@ -51,138 +74,256 @@ if(paletteFolder === "" || paletteFolder === "/") {
|
||||
if(!paletteFolder.endsWith("/")) paletteFolder += "/";
|
||||
|
||||
|
||||
//--------------------------
|
||||
// Select palette
|
||||
//--------------------------
|
||||
const palettes = app.vault.getFiles()
|
||||
.filter(f=>f.extension === "md" && f.path.toLowerCase() === paletteFolder + f.name.toLowerCase())
|
||||
.sort((a,b)=>a.basename.toLowerCase()<b.basename.toLowerCase()?-1:1);
|
||||
const file = await utils.suggester(["Excalidraw Default"].concat(palettes.map(f=>f.name)),["Default"].concat(palettes), "Choose a palette, press ESC to abort");
|
||||
if(!file) return;
|
||||
|
||||
if(file === "Default") {
|
||||
api.updateScene({
|
||||
appState: {
|
||||
colorPalette: {}
|
||||
//-----------------------
|
||||
// UPDATE CustomPalette
|
||||
//-----------------------
|
||||
const updateColorPalette = (paletteFragment) => {
|
||||
const st = ea.getExcalidrawAPI().getAppState();
|
||||
colorPalette = st.colorPalette ?? {};
|
||||
if(paletteFragment?.topPicks) {
|
||||
if(!colorPalette.topPicks) {
|
||||
colorPalette.topPicks = {
|
||||
...paletteFragment.topPicks
|
||||
};
|
||||
} else {
|
||||
colorPalette.topPicks = {
|
||||
...colorPalette.topPicks,
|
||||
...paletteFragment.topPicks
|
||||
}
|
||||
}
|
||||
});
|
||||
return;
|
||||
} else {
|
||||
colorPalette = {
|
||||
...colorPalette,
|
||||
...paletteFragment
|
||||
}
|
||||
}
|
||||
ea.viewUpdateScene({appState: {colorPalette}});
|
||||
ea.addElementsToView(true,true); //elements is empty, but this will save the file
|
||||
}
|
||||
|
||||
//--------------------------
|
||||
// Load palette
|
||||
//--------------------------
|
||||
const sketchPalette = await app.vault.read(file);
|
||||
|
||||
const parseJSON = (data) => {
|
||||
try {
|
||||
return JSON.parse(data);
|
||||
} catch(e) {
|
||||
//----------------
|
||||
// LOAD PALETTE
|
||||
//----------------
|
||||
const loadPalette = async () => {
|
||||
//--------------------------
|
||||
// Select palette
|
||||
//--------------------------
|
||||
const palettes = app.vault.getFiles()
|
||||
.filter(f=>f.extension === "md" && f.path.toLowerCase() === paletteFolder + f.name.toLowerCase())
|
||||
.sort((a,b)=>a.basename.toLowerCase()<b.basename.toLowerCase()?-1:1);
|
||||
const file = await utils.suggester(["Excalidraw Default"].concat(palettes.map(f=>f.name)),["Default"].concat(palettes), "Choose a palette, press ESC to abort");
|
||||
if(!file) return;
|
||||
|
||||
if(file === "Default") {
|
||||
api.updateScene({
|
||||
appState: {
|
||||
colorPalette: {}
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
//--------------------------
|
||||
// Load palette
|
||||
//--------------------------
|
||||
const sketchPalette = await app.vault.read(file);
|
||||
|
||||
const parseJSON = (data) => {
|
||||
try {
|
||||
return JSON.parse(data);
|
||||
} catch(e) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const loadPaletteFromPlainText = (data) => {
|
||||
const colors = [];
|
||||
data.replaceAll("\r","").split("\n").forEach(c=>{
|
||||
c = c.trim();
|
||||
if(c==="") return;
|
||||
if(c.match(/[^hslrga-fA-F\(\d\.\,\%\s)#]/)) return;
|
||||
const cm = ea.getCM(c);
|
||||
if(cm) colors.push(cm.stringHEX({alpha: false}));
|
||||
})
|
||||
return colors;
|
||||
}
|
||||
|
||||
const paletteJSON = parseJSON(sketchPalette);
|
||||
|
||||
const colors = paletteJSON
|
||||
? paletteJSON.colors.map(c=>ea.getCM({r:c.red*255,g:c.green*255,b:c.blue*255,a:c.alpha}).stringHEX({alpha: false}))
|
||||
: loadPaletteFromPlainText(sketchPalette);
|
||||
const baseColor = ea.getCM(colors[0]);
|
||||
|
||||
// Add black, white, transparent, gary
|
||||
const palette = [[
|
||||
"transparent",
|
||||
"black",
|
||||
baseColor.mix({color: lightGray, ratio:0.95}).stringHEX({alpha: false}),
|
||||
baseColor.mix({color: darkGray, ratio:0.95}).stringHEX({alpha: false}),
|
||||
"white"
|
||||
]];
|
||||
|
||||
// Create Excalidraw palette
|
||||
for(i=0;i<Math.floor(colors.length/5);i++) {
|
||||
palette.push([
|
||||
colors[i*5+1],
|
||||
colors[i*5+2],
|
||||
colors[i*5],
|
||||
colors[i*5+3],
|
||||
colors[i*5+4]
|
||||
]);
|
||||
}
|
||||
|
||||
const getShades = (c,type) => {
|
||||
cm = ea.getCM(c);
|
||||
const lightness = cm.lightness;
|
||||
if(lightness === 0 || lightness === 100) return c;
|
||||
|
||||
switch(type) {
|
||||
case "canvas":
|
||||
return [
|
||||
c,
|
||||
ea.getCM(c).lightnessTo((100-lightness)*0.5+lightness).stringHEX({alpha: false}),
|
||||
ea.getCM(c).lightnessTo((100-lightness)*0.25+lightness).stringHEX({alpha: false}),
|
||||
ea.getCM(c).lightnessTo(lightness*0.5).stringHEX({alpha: false}),
|
||||
ea.getCM(c).lightnessTo(lightness*0.25).stringHEX({alpha: false}),
|
||||
];
|
||||
case "stroke":
|
||||
return [
|
||||
ea.getCM(c).lightnessTo((100-lightness)*0.5+lightness).stringHEX({alpha: false}),
|
||||
ea.getCM(c).lightnessTo((100-lightness)*0.25+lightness).stringHEX({alpha: false}),
|
||||
ea.getCM(c).lightnessTo(lightness*0.5).stringHEX({alpha: false}),
|
||||
ea.getCM(c).lightnessTo(lightness*0.25).stringHEX({alpha: false}),
|
||||
c,
|
||||
];
|
||||
case "background":
|
||||
return [
|
||||
ea.getCM(c).lightnessTo((100-lightness)*0.5+lightness).stringHEX({alpha: false}),
|
||||
c,
|
||||
ea.getCM(c).lightnessTo((100-lightness)*0.25+lightness).stringHEX({alpha: false}),
|
||||
ea.getCM(c).lightnessTo(lightness*0.5).stringHEX({alpha: false}),
|
||||
ea.getCM(c).lightnessTo(lightness*0.25).stringHEX({alpha: false}),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
const paletteSize = palette.flat().length;
|
||||
const newPalette = {
|
||||
canvasBackground: palette.flat().map(c=>getShades(c,"canvas")),
|
||||
elementStroke: palette.flat().map(c=>getShades(c,"stroke")),
|
||||
elementBackground: palette.flat().map(c=>getShades(c,"background"))
|
||||
};
|
||||
|
||||
|
||||
//--------------------------
|
||||
// Check if palette has the same size as the current. Is re-paint possible?
|
||||
//--------------------------
|
||||
const oldPalette = api.getAppState().colorPalette;
|
||||
|
||||
//You can only switch and repaint equal size palettes
|
||||
let canRepaint = Boolean(oldPalette) && Object.keys(oldPalette).length === 3 &&
|
||||
oldPalette.canvasBackground.length === paletteSize &&
|
||||
oldPalette.elementBackground.length === paletteSize &&
|
||||
oldPalette.elementStroke.length === paletteSize;
|
||||
|
||||
//Check that the palette for canvas background, element stroke and element background are the same
|
||||
for(i=0;canRepaint && i<paletteSize;i++) {
|
||||
if(
|
||||
oldPalette.canvasBackground[i] !== oldPalette.elementBackground[i] ||
|
||||
oldPalette.canvasBackground[i] !== oldPalette.elementStroke[i]
|
||||
) {
|
||||
canRepaint = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const shouldRepaint = canRepaint && await utils.suggester(["Try repainting the drawing with the new palette","Just load the new palette"], [true, false],"ESC will load the palette without repainting");
|
||||
|
||||
|
||||
//--------------------------
|
||||
// Apply palette
|
||||
//--------------------------
|
||||
if(shouldRepaint) {
|
||||
const map = new Map();
|
||||
for(i=0;i<paletteSize;i++) {
|
||||
map.set(oldPalette.canvasBackground[i],newPalette.canvasBackground[i])
|
||||
}
|
||||
|
||||
ea.copyViewElementsToEAforEditing(ea.getViewElements());
|
||||
ea.getElements().forEach(el=>{
|
||||
el.strokeColor = map.get(el.strokeColor)??el.strokeColor;
|
||||
el.backgroundColor = map.get(el.backgroundColor)??el.backgroundColor;
|
||||
})
|
||||
|
||||
const canvasColor = api.getAppState().viewBackgroundColor;
|
||||
|
||||
await api.updateScene({
|
||||
appState: {
|
||||
viewBackgroundColor: map.get(canvasColor)??canvasColor
|
||||
}
|
||||
});
|
||||
|
||||
ea.addElementsToView();
|
||||
}
|
||||
updateColorPalette(newPalette);
|
||||
}
|
||||
|
||||
//-------------
|
||||
// TOP PICKS
|
||||
//-------------
|
||||
const topPicks = async () => {
|
||||
const elements = ea.getViewSelectedElements().filter(el=>["rectangle", "diamond", "ellipse", "line"].includes(el.type));
|
||||
if(elements.length !== 5) {
|
||||
new Notice("Select 5 elements, the script will use the background color of these elements",6000);
|
||||
return;
|
||||
}
|
||||
|
||||
const colorType = await utils.suggester(["View Background", "Element Background", "Stroke"],["view", "background", "stroke"], "Which top-picks would you like to set?");
|
||||
|
||||
if(!colorType) {
|
||||
new Notice("You did not select which color to set");
|
||||
return;
|
||||
}
|
||||
|
||||
const topPicks = elements.map(el=>el.backgroundColor);
|
||||
switch(colorType) {
|
||||
case "view": updateColorPalette({topPicks: {canvasBackground: topPicks}}); break;
|
||||
case "stroke": updateColorPalette({topPicks: {elementStroke: topPicks}}); break;
|
||||
default: updateColorPalette({topPicks: {elementBackground: topPicks}}); break;
|
||||
}
|
||||
}
|
||||
|
||||
//-----------------------------------
|
||||
// Copy palette from another file
|
||||
//-----------------------------------
|
||||
const copyPaletteFromFile = async () => {
|
||||
const files = app.vault.getFiles().filter(f => ea.isExcalidrawFile(f)).sort((a,b)=>a.name > b.name ? 1 : -1);
|
||||
const file = await utils.suggester(files.map(f=>f.path),files,"Select the file to copy from");
|
||||
if(!file) {
|
||||
return;
|
||||
}
|
||||
scene = await ea.getSceneFromFile(file);
|
||||
if(!scene || !scene.appState) {
|
||||
new Notice("unknown error");
|
||||
return;
|
||||
}
|
||||
ea.viewUpdateScene({appState: {colorPalette: {...scene.appState.colorPalette}}});
|
||||
ea.addElementsToView(true,true);
|
||||
}
|
||||
|
||||
const loadPaletteFromPlainText = (data) => {
|
||||
const colors = [];
|
||||
data.replaceAll("\r","").split("\n").forEach(c=>{
|
||||
c = c.trim();
|
||||
if(c==="") return;
|
||||
if(c.match(/[^hslrga-fA-F\(\d\.\,\%\s)#]/)) return;
|
||||
const cm = ea.getCM(c);
|
||||
if(cm) colors.push(cm.stringHEX({alpha: false}));
|
||||
})
|
||||
return colors;
|
||||
}
|
||||
//----------
|
||||
// START
|
||||
//----------
|
||||
const action = await utils.suggester(
|
||||
["Load palette from file", "Set top-picks based on the background color of 5 selected elements", "Copy palette from another Excalidraw File"],
|
||||
["palette","top-picks","copy"]
|
||||
);
|
||||
if(!action) return;
|
||||
|
||||
const paletteJSON = parseJSON(sketchPalette);
|
||||
|
||||
const colors = paletteJSON
|
||||
? paletteJSON.colors.map(c=>ea.getCM({r:c.red*255,g:c.green*255,b:c.blue*255,a:c.alpha}).stringHEX({alpha: false}))
|
||||
: loadPaletteFromPlainText(sketchPalette);
|
||||
const baseColor = ea.getCM(colors[0]);
|
||||
|
||||
// Add black, white, transparent, gary
|
||||
const palette = [[
|
||||
"transparent",
|
||||
"black",
|
||||
baseColor.mix({color: lightGray, ratio:0.95}).stringHEX({alpha: false}),
|
||||
baseColor.mix({color: darkGray, ratio:0.95}).stringHEX({alpha: false}),
|
||||
"white"
|
||||
]];
|
||||
|
||||
// Create Excalidraw palette
|
||||
for(i=0;i<Math.floor(colors.length/5);i++) {
|
||||
palette.push([
|
||||
colors[i*5+1],
|
||||
colors[i*5+2],
|
||||
colors[i*5],
|
||||
colors[i*5+3],
|
||||
colors[i*5+4]
|
||||
]);
|
||||
}
|
||||
|
||||
const paletteSize = palette.flat().length;
|
||||
const newPalette = {
|
||||
canvasBackground: palette.flat(),
|
||||
elementStroke: palette.flat(),
|
||||
elementBackground: palette.flat()
|
||||
};
|
||||
|
||||
|
||||
//--------------------------
|
||||
// Check if palette has the same size as the current. Is re-paint possible?
|
||||
//--------------------------
|
||||
const oldPalette = api.getAppState().colorPalette;
|
||||
|
||||
//You can only switch and repaint equal size palettes
|
||||
let canRepaint = Object.keys(oldPalette).length === 3 &&
|
||||
oldPalette.canvasBackground.length === paletteSize &&
|
||||
oldPalette.elementBackground.length === paletteSize &&
|
||||
oldPalette.elementStroke.length === paletteSize;
|
||||
|
||||
//Check that the palette for canvas background, element stroke and element background are the same
|
||||
for(i=0;canRepaint && i<paletteSize;i++) {
|
||||
if(
|
||||
oldPalette.canvasBackground[i] !== oldPalette.elementBackground[i] ||
|
||||
oldPalette.canvasBackground[i] !== oldPalette.elementStroke[i]
|
||||
) {
|
||||
canRepaint = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const shouldRepaint = canRepaint && await utils.suggester(["Try repainting the drawing with the new palette","Just load the new palette"], [true, false],"ESC will load the palette without repainting");
|
||||
|
||||
|
||||
//--------------------------
|
||||
// Apply palette
|
||||
//--------------------------
|
||||
if(shouldRepaint) {
|
||||
const map = new Map();
|
||||
for(i=0;i<paletteSize;i++) {
|
||||
map.set(oldPalette.canvasBackground[i],newPalette.canvasBackground[i])
|
||||
}
|
||||
|
||||
ea.copyViewElementsToEAforEditing(ea.getViewElements());
|
||||
ea.getElements().forEach(el=>{
|
||||
el.strokeColor = map.get(el.strokeColor)??el.strokeColor;
|
||||
el.backgroundColor = map.get(el.backgroundColor)??el.backgroundColor;
|
||||
})
|
||||
|
||||
const canvasColor = api.getAppState().viewBackgroundColor;
|
||||
|
||||
await api.updateScene({
|
||||
appState: {
|
||||
colorPalette: newPalette,
|
||||
viewBackgroundColor: map.get(canvasColor)??canvasColor
|
||||
}
|
||||
});
|
||||
|
||||
ea.addElementsToView();
|
||||
} else {
|
||||
api.updateScene({
|
||||
appState: {
|
||||
colorPalette: newPalette
|
||||
}
|
||||
});
|
||||
}
|
||||
switch(action) {
|
||||
case "palette": loadPalette(); break;
|
||||
case "top-picks": topPicks(); break;
|
||||
case "copy": copyPaletteFromFile(); break;
|
||||
}
|
||||
@@ -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!||[@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.||[@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)|
|
||||
@@ -1,29 +1,386 @@
|
||||
/*
|
||||

|
||||
|
||||
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();
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||

|
||||
|
||||
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());
|
||||
@@ -5,18 +5,23 @@ The script will convert your drawing into a slideshow presentation.
|
||||
|
||||
```javascript
|
||||
*/
|
||||
|
||||
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.8.2")) {
|
||||
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.8.17")) {
|
||||
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
|
||||
return;
|
||||
}
|
||||
|
||||
const statusBar = document.querySelector("div.status-bar");
|
||||
const ctrlKey = ea.targetView.modifierKeyDown.ctrlKey || ea.targetView.modifierKeyDown.metaKey;
|
||||
const altKey = ea.targetView.modifierKeyDown.altKey || ctrlKey;
|
||||
|
||||
//constants
|
||||
const STEPCOUNT = 100;
|
||||
const TRANSITION_DELAY = 1500; //maximum time for transition between slides in milliseconds
|
||||
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 doc = ea.targetView.ownerDocument;
|
||||
const inPopoutWindow = altKey || ea.targetView.ownerDocument !== document;
|
||||
const win = ea.targetView.ownerWindow;
|
||||
const api = ea.getExcalidrawAPI();
|
||||
const contentEl = ea.targetView.contentEl;
|
||||
@@ -26,34 +31,78 @@ const sleep = async (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
window.removePresentationEventHandlers?.();
|
||||
|
||||
//check if line or arrow is selected, if not inform the user and terminate presentation
|
||||
const lineEl = ea.getViewSelectedElement();
|
||||
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)) {
|
||||
new Notice("Please select the line or arrow for the presentation path");
|
||||
api.setToast({
|
||||
message:"Please select the line or arrow for the presentation path",
|
||||
duration: 3000,
|
||||
closable: true
|
||||
})
|
||||
return;
|
||||
}
|
||||
|
||||
//goto fullscreen
|
||||
if(app.isMobile) {
|
||||
ea.viewToggleFullScreen(true);
|
||||
} else {
|
||||
await contentEl.requestFullscreen();
|
||||
await sleep(50);
|
||||
ea.setViewModeEnabled(true);
|
||||
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");
|
||||
}
|
||||
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 originalColor = {
|
||||
strokeColor: lineEl.strokeColor,
|
||||
backgroundColor: lineEl.backgroundColor
|
||||
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();
|
||||
}
|
||||
ea.copyViewElementsToEAforEditing([lineEl]);
|
||||
ea.getElement(lineEl.id).strokeColor = "transparent";
|
||||
ea.getElement(lineEl.id).backgroundColor = "transparent";
|
||||
await ea.addElementsToView();
|
||||
|
||||
//----------------------------
|
||||
//scroll-to-location functions
|
||||
@@ -64,8 +113,11 @@ 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]}
|
||||
: slide <= 0 ? slideCount : slide - 1;
|
||||
return {
|
||||
pointA:lineEl.points[slide*2],
|
||||
pointB:lineEl.points[slide*2+1]
|
||||
}
|
||||
}
|
||||
|
||||
const getSlideRect = ({pointA, pointB}) => {
|
||||
@@ -91,25 +143,34 @@ const getSlideRect = ({pointA, pointB}) => {
|
||||
}
|
||||
|
||||
let busy = false;
|
||||
const scrollToNextRect = async ({left,top,right,bottom,nextZoom}) => {
|
||||
const scrollToNextRect = async ({left,top,right,bottom,nextZoom},steps = STEPCOUNT) => {
|
||||
const startTimer = Date.now();
|
||||
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)/STEPCOUNT;
|
||||
const xStep = (left+scrollX)/STEPCOUNT;
|
||||
const yStep = (top+scrollY)/STEPCOUNT;
|
||||
for(i=1;i<=STEPCOUNT;i++) {
|
||||
const zoomStep = (zoom.value-nextZoom)/steps;
|
||||
const xStep = (left+scrollX)/steps;
|
||||
const yStep = (top+scrollY)/steps;
|
||||
let i=1;
|
||||
while(i<=steps) {
|
||||
api.updateScene({
|
||||
appState: {
|
||||
scrollX:scrollX-(xStep*i),
|
||||
scrollY:scrollY-(yStep*i),
|
||||
zoom:{value:zoom.value-zoomStep*i},
|
||||
shouldCacheIgnoreZoom:true,
|
||||
}
|
||||
});
|
||||
await sleep(FRAME_SLEEP);
|
||||
const ellapsed = Date.now()-startTimer;
|
||||
if(ellapsed > TRANSITION_DELAY) {
|
||||
i = i<steps ? steps : steps+1;
|
||||
} else {
|
||||
const timeProgress = ellapsed / TRANSITION_DELAY;
|
||||
i=Math.min(Math.round(steps*timeProgress),steps)
|
||||
await sleep(FRAME_SLEEP);
|
||||
}
|
||||
}
|
||||
api.updateScene({appState:{shouldCacheIgnoreZoom:false}});
|
||||
busy = false;
|
||||
@@ -125,73 +186,151 @@ const navigate = async (dir) => {
|
||||
? slide<=prevSlide
|
||||
: slide>=prevSlide;
|
||||
if(shouldExit) {
|
||||
if(!app.isMobile) await doc.exitFullscreen();
|
||||
exitPresentation();
|
||||
return;
|
||||
}
|
||||
if(slideNumberEl) slideNumberEl.innerText = (slide+1).toString();
|
||||
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 CTRL/CMD + click the presentation script icon or press ENTER during presentation."});
|
||||
settingsModal.contentEl.createEl("p",{text: "If you don't want the presentation in fullscreen mode, hold down the ALT/OPT key when clicking the script button."});
|
||||
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
|
||||
//--------------------------------------
|
||||
//create slideshow controlpanel container
|
||||
const top = contentEl.innerHeight;
|
||||
const left = contentEl.innerWidth;
|
||||
const containerEl = 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 = containerEl.createDiv({
|
||||
cls: "panelColumn",
|
||||
});
|
||||
let controlPanelEl;
|
||||
let slideNumberEl;
|
||||
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: "<",
|
||||
const createNavigationPanel = () => {
|
||||
//create slideshow controlpanel container
|
||||
const top = contentEl.innerHeight;
|
||||
const left = contentEl.innerWidth;
|
||||
controlPanelEl = contentEl.createDiv({
|
||||
cls: ["excalidraw","excalidraw-presentation-panel"],
|
||||
attr: {
|
||||
style: `
|
||||
margin-top: calc(var(--default-button-size)*0.25);
|
||||
margin-left: calc(var(--default-button-size)*0.25);`
|
||||
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);`
|
||||
}
|
||||
}, 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"],
|
||||
})
|
||||
});
|
||||
});
|
||||
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) => {
|
||||
if(ea.targetView.leaf !== app.workspace.activeLeaf) return;
|
||||
e.preventDefault();
|
||||
switch(e.key) {
|
||||
case "escape":
|
||||
if(app.isMobile) exitPresentation();
|
||||
case "Escape":
|
||||
if(app.isMobile || inPopoutWindow) exitPresentation();
|
||||
break;
|
||||
case "ArrowRight":
|
||||
case "ArrowDown":
|
||||
@@ -201,9 +340,25 @@ const keydownListener = (e) => {
|
||||
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;
|
||||
}
|
||||
}
|
||||
doc.addEventListener('keydown',keydownListener);
|
||||
|
||||
//slideshow panel drag
|
||||
let pos1 = pos2 = pos3 = pos4 = 0;
|
||||
@@ -214,19 +369,25 @@ const updatePosition = (deltaY = 0, deltaX = 0) => {
|
||||
offsetLeft,
|
||||
clientWidth: width,
|
||||
clientHeight: height,
|
||||
} = containerEl;
|
||||
containerEl.style.top = (offsetTop - deltaY) + 'px';
|
||||
containerEl.style.left = (offsetLeft - deltaX) + 'px';
|
||||
} = 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) => {
|
||||
@@ -238,45 +399,119 @@ const onDrag = (e) => {
|
||||
updatePosition(pos2, pos1);
|
||||
}
|
||||
|
||||
containerEl.addEventListener('pointerdown', pointerDown, false);
|
||||
win.addEventListener('pointerup', pointerUp, false);
|
||||
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;
|
||||
containerEl.parentElement?.removeChild(containerEl);
|
||||
if(!app.isMobile) win.removeEventListener('fullscreenchange', fullscreenListener);
|
||||
doc.removeEventListener('keydown',keydownListener);
|
||||
win.removeEventListener('pointerup',pointerUp);
|
||||
contentEl.querySelector(".layer-ui__wrapper").removeClass("excalidraw-hidden");
|
||||
delete window.removePresentationEventHandlers;
|
||||
//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 = () => {
|
||||
window.removePresentationEventHandlers?.();
|
||||
if(app.isMobile) ea.viewToggleFullScreen(true);
|
||||
else ea.setViewModeEnabled(false);
|
||||
const exitPresentation = async (openForEdit = false) => {
|
||||
statusBar.style.display = "inherit";
|
||||
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));
|
||||
ea.getElement(lineEl.id).strokeColor = originalColor.strokeColor;
|
||||
ea.getElement(lineEl.id).backgroundColor = originalColor.backgroundColor;
|
||||
ea.addElementsToView();
|
||||
ea.selectElementsInView(ea.getElements());
|
||||
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();
|
||||
})
|
||||
}
|
||||
|
||||
ea.onLinkClickHook = () => {
|
||||
exitPresentation();
|
||||
return true;
|
||||
};
|
||||
|
||||
const fullscreenListener = (e) => {
|
||||
e.preventDefault();
|
||||
exitPresentation();
|
||||
}
|
||||
|
||||
if(!app.isMobile) {
|
||||
win.addEventListener('fullscreenchange', fullscreenListener);
|
||||
|
||||
//--------------------------
|
||||
// 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"));
|
||||
statusBar.style.display = "none";
|
||||
}
|
||||
|
||||
//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 {
|
||||
if(window.ExcalidrawSlideshowStartTimer) {
|
||||
clearTimeout(window.ExcalidrawSlideshowStartTimer);
|
||||
delete window.ExcalidrawSlideshowStartTimer;
|
||||
}
|
||||
if(ctrlKey) {
|
||||
await start();
|
||||
presentationSettings();
|
||||
return;
|
||||
}
|
||||
window.ExcalidrawSlideshow = {
|
||||
script: utils.scriptFile.path,
|
||||
timestamp
|
||||
};
|
||||
window.ExcalidrawSlideshowStartTimer = setTimeout(start,500);
|
||||
}
|
||||
@@ -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 |
126
ea-scripts/Text to Sticky Notes.md
Normal file
@@ -0,0 +1,126 @@
|
||||
/*
|
||||

|
||||
|
||||
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);
|
||||
1
ea-scripts/Text to Sticky Notes.svg
Normal 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 |
@@ -31,6 +31,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/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]]|
|
||||
@@ -44,6 +45,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/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/Excalidraw%20Collaboration%20Frame.svg"/></div>|[[#Excalidraw Collaboration Frame]]|
|
||||
|<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]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.svg"/></div>|[[#Expand rectangles vertically keep text centered]]|
|
||||
@@ -53,13 +55,18 @@ 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/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/PDF%20Page%20Text%20to%20Clipboard.svg"/></div>|[[#PDF Page Text to Clipboard]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Rename%20Image.svg"/></div>|[[#Rename Image]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Repeat%20Elements.svg"/></div>|[[#Repeat Elements]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Reverse%20arrows.svg"/></div>|[[#Reverse arrows]]|
|
||||
@@ -75,9 +82,11 @@ 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/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/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
|
||||
@@ -102,6 +111,18 @@ 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
|
||||
@@ -180,6 +201,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/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>
|
||||
|
||||
## Excalidraw Collaboration Frame
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Excalidraw%20Collaboration%20Frame.md
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/1-2-3'>@1-2-3</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Excalidraw%20Collaboration%20Frame.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Creates a new Excalidraw.com collaboration room and places the link to the room on the clipboard.<iframe width="400" height="225" src="https://www.youtube.com/embed/7isRfeAhEH4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></td></tr></table>
|
||||
|
||||
## 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
|
||||
@@ -234,12 +261,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
|
||||
@@ -252,6 +297,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
|
||||
@@ -276,6 +327,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/Palette%20loader.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Design your palette at <a href="http://paletton.com/" target="_blank">paletton.com</a> Once you are happy with your colors, click Tables/Export in the bottom right of the screen. Then click "Color swatches/as Sketch Palette", and copy the contents of the page to a markdown file in the palette folder of your vault (default is Excalidraw/Palette)<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-sketch-palette-loader-1.jpg'></td></tr></table>
|
||||
|
||||
## PDF Page Text to Clipboard
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/PDF%20Page%20Text%20to%20Clipboard.md
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/PDF%20Page%20Text%20to%20Clipboard.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Copies the text from the selected PDF page on the Excalidraw canvas to the clipboard.<br><iframe width="400" height="225" src="https://www.youtube.com/embed/Kwt_8WdOUT4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br><a href='https://youtu.be/Kwt_8WdOUT4' target='_blank'>Link to video on YouTube</a></td></tr></table>
|
||||
|
||||
## Rename Image
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Rename%20Image.md
|
||||
@@ -366,6 +423,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/Text%20Arch.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Fit a text to the arch of a circle. The script will prompt you for the radius of the circle and then split your text to individual letters and place each letter to the arch defined by the radius. Setting a lower radius value will increase the arching of the text. Note that the arched-text will no longer be editable as a text element and it will no longer function as a markdown link. Emojis are currently not supported.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/text-arch.jpg'></td></tr></table>
|
||||
|
||||
## Text to Sticky Notes
|
||||
```excalidraw-script-install
|
||||
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/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
|
||||
@@ -376,4 +439,4 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
|
||||
```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>
|
||||
17
ea-scripts/pens/Fine tipped pen - fixed pressure.md
Normal 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,
|
||||
},
|
||||
}
|
||||
}
|
||||
16
ea-scripts/pens/Fountain pen.md
Normal 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,
|
||||
},
|
||||
}
|
||||
}
|
||||
16
ea-scripts/pens/Mindmap - thick-thin-thick.md
Normal 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",
|
||||
}
|
||||
}
|
||||
}
|
||||
16
ea-scripts/pens/Mindmap - thick-thin.md
Normal 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",
|
||||
}
|
||||
}
|
||||
}
|
||||
18
ea-scripts/pens/Thick marker - dynamic pressure.md
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
19
ea-scripts/pens/Thick marker - fixed pressure.md
Normal 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
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
images/excalidraw-modifiers.png
Normal file
|
After Width: | Height: | Size: 373 KiB |
BIN
images/scripts-alternative-pens.jpg
Normal file
|
After Width: | Height: | Size: 54 KiB |
BIN
images/scripts-invert-colors.jpg
Normal file
|
After Width: | Height: | Size: 84 KiB |
BIN
images/scripts-mindmap-format-1.png
Normal file
|
After Width: | Height: | Size: 91 KiB |
BIN
images/scripts-mindmap-format-2.png
Normal file
|
After Width: | Height: | Size: 46 KiB |
|
Before Width: | Height: | Size: 59 KiB After Width: | Height: | Size: 224 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 57 KiB |
BIN
images/scripts-sticky-note-matrix.jpg
Normal file
|
After Width: | Height: | Size: 64 KiB |
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "1.8.3-beta",
|
||||
"minAppVersion": "0.16.0",
|
||||
"version": "1.9.6.1-beta",
|
||||
"minAppVersion": "1.1.6",
|
||||
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
|
||||
"author": "Zsolt Viczian",
|
||||
"authorUrl": "https://zsolt.blog",
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "1.8.2",
|
||||
"minAppVersion": "0.16.0",
|
||||
"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.6",
|
||||
"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
|
||||
}
|
||||
|
||||
60
package.json
@@ -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-1",
|
||||
"clsx": "^1.1.1",
|
||||
"@zsviczian/excalidraw": "0.15.2-obsidian-5",
|
||||
"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": "^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/core": "^7.20.12",
|
||||
"@babel/preset-env": "^7.20.2",
|
||||
"@babel/preset-react": "^7.18.6",
|
||||
"@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",
|
||||
"@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": "^18.0.9",
|
||||
"@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"
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -2,13 +2,14 @@ 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";
|
||||
@@ -21,6 +22,7 @@ import {
|
||||
MAX_IMAGE_SIZE,
|
||||
COLOR_NAMES,
|
||||
fileid,
|
||||
GITHUB_RELEASES,
|
||||
} from "./Constants";
|
||||
import { getDrawingFilename, } from "./utils/FileUtils";
|
||||
import {
|
||||
@@ -37,8 +39,8 @@ import {
|
||||
wrapTextAtCharLength,
|
||||
} from "./utils/Utils";
|
||||
import { getNewOrAdjacentLeaf, isObsidianThemeDark } from "./utils/ObsidianUtils";
|
||||
import { AppState, BinaryFileData, Point } from "@zsviczian/excalidraw/types/types";
|
||||
import { EmbeddedFilesLoader, FileData } from "./EmbeddedFileLoader";
|
||||
import { AppState, BinaryFileData, DataURL, ExcalidrawImperativeAPI, 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";
|
||||
@@ -61,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,
|
||||
@@ -86,6 +89,7 @@ const {
|
||||
getCommonBoundingBox,
|
||||
getMaximumGroups,
|
||||
measureText,
|
||||
getDefaultLineHeight,
|
||||
//@ts-ignore
|
||||
} = excalidrawLib;
|
||||
|
||||
@@ -118,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"
|
||||
@@ -139,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
|
||||
@@ -190,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";
|
||||
}
|
||||
};
|
||||
@@ -269,6 +289,26 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* @param file: TFile
|
||||
* @returns ExcalidrawScene
|
||||
*/
|
||||
async getSceneFromFile(file: TFile): Promise<{elements: ExcalidrawElement[]; appState: AppState;}> {
|
||||
if(!file) {
|
||||
errorMessage("file not found", "getScene()");
|
||||
return null;
|
||||
}
|
||||
if(!this.isExcalidrawFile(file)) {
|
||||
errorMessage("file is not an Excalidraw file", "getScene()");
|
||||
return null;
|
||||
}
|
||||
const template = await getTemplate(this.plugin,file.path,false,new EmbeddedFilesLoader(this.plugin),0);
|
||||
return {
|
||||
elements: template.elements,
|
||||
appState: template.appState
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* get all elements from ExcalidrawAutomate elementsDict
|
||||
* @returns elements from elemenetsDict
|
||||
@@ -310,10 +350,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(
|
||||
@@ -352,7 +396,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,
|
||||
@@ -383,18 +427,17 @@ 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,
|
||||
},
|
||||
@@ -402,8 +445,9 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
|
||||
};
|
||||
|
||||
const generateMD = ():string => {
|
||||
let outString = params.plaintext ? params.plaintext + "\n\n" : "";
|
||||
const textElements = this.getElements().filter(el => el.type === "text") as ExcalidrawTextElement[];
|
||||
let outString = "# Text Elements\n";
|
||||
outString += "# Text Elements\n";
|
||||
textElements.forEach(te=> {
|
||||
outString += `${te.rawText ?? (te.originalText ?? te.text)} ^${te.id}\n\n`;
|
||||
});
|
||||
@@ -568,6 +612,7 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
|
||||
y: number,
|
||||
w: number,
|
||||
h: number,
|
||||
link: string | null = null,
|
||||
) {
|
||||
return {
|
||||
id,
|
||||
@@ -584,7 +629,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),
|
||||
@@ -592,11 +641,50 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
|
||||
isDeleted: false,
|
||||
groupIds: [] as any,
|
||||
boundElements: [] as any,
|
||||
link: null as string,
|
||||
link,
|
||||
locked: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param topX
|
||||
* @param topY
|
||||
* @param width
|
||||
* @param height
|
||||
* @returns
|
||||
*/
|
||||
addIFrame(topX: number, topY: number, width: number, height: number, url?: string, file?: TFile): string {
|
||||
//@ts-ignore
|
||||
if (!this.targetView || !this.targetView?._loaded) {
|
||||
errorMessage("targetView not set", "addIFrame()");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!url && !file) {
|
||||
errorMessage("Either the url or the file must be set. If both are provided the URL takes precedence", "addIFrame()");
|
||||
return null;
|
||||
}
|
||||
|
||||
const id = nanoid();
|
||||
this.elementsDict[id] = this.boxedElement(
|
||||
id,
|
||||
"iframe",
|
||||
topX,
|
||||
topY,
|
||||
width,
|
||||
height,
|
||||
url ? url : file ? `[[${
|
||||
app.metadataCache.fileToLinktext(
|
||||
file,
|
||||
this.targetView.file.path,
|
||||
file.extension === "md",
|
||||
)
|
||||
}]]` : "",
|
||||
);
|
||||
return id;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param topX
|
||||
@@ -726,6 +814,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
|
||||
@@ -744,9 +852,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 {
|
||||
@@ -757,12 +867,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":
|
||||
@@ -798,6 +911,7 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
|
||||
);
|
||||
}
|
||||
}
|
||||
this.style.strokeColor = strokeColor;
|
||||
const isContainerBound = boxId && formatting.box !== "blob";
|
||||
this.elementsDict[id] = {
|
||||
text,
|
||||
@@ -806,12 +920,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]);
|
||||
@@ -932,7 +1047,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();
|
||||
@@ -940,17 +1055,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,
|
||||
};
|
||||
@@ -1186,7 +1312,7 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
|
||||
strokeStyle: "solid",
|
||||
roughness: 1,
|
||||
opacity: 100,
|
||||
strokeSharpness: "sharp",
|
||||
roundness: null,
|
||||
fontFamily: 1,
|
||||
fontSize: 20,
|
||||
textAlign: "left",
|
||||
@@ -1596,6 +1722,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
|
||||
*/
|
||||
@@ -1791,6 +1941,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 };
|
||||
};
|
||||
@@ -1827,7 +1978,7 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
|
||||
* @returns
|
||||
*/
|
||||
verifyMinimumPluginVersion(requiredVersion: string): boolean {
|
||||
return PLUGIN_VERSION === requiredVersion || isVersionNewerThanOther(PLUGIN_VERSION,requiredVersion);
|
||||
return verifyMinimumPluginVersion(requiredVersion);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1844,7 +1995,7 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
|
||||
* @param elements
|
||||
* @returns
|
||||
*/
|
||||
selectElementsInView(elements: ExcalidrawElement[]): void {
|
||||
selectElementsInView(elements: ExcalidrawElement[] | string[]): void {
|
||||
//@ts-ignore
|
||||
if (!this.targetView || !this.targetView?._loaded) {
|
||||
errorMessage("targetView not set", "selectElementsInView()");
|
||||
@@ -1853,8 +2004,13 @@ export class ExcalidrawAutomate implements ExcalidrawAutomateInterface {
|
||||
if (!elements || elements.length === 0) {
|
||||
return;
|
||||
}
|
||||
const API = this.getExcalidrawAPI();
|
||||
API.selectElements(elements);
|
||||
const API: ExcalidrawImperativeAPI = this.getExcalidrawAPI();
|
||||
if(typeof elements[0] === "string") {
|
||||
const els = this.getViewElements().filter(el=>(elements as string[]).includes(el.id));
|
||||
API.selectElements(els);
|
||||
} else {
|
||||
API.selectElements(elements as ExcalidrawElement[]);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -2048,6 +2204,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) {
|
||||
@@ -2055,10 +2212,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 };
|
||||
}
|
||||
@@ -2205,7 +2364,7 @@ export async function createPNG(
|
||||
{
|
||||
type: "excalidraw",
|
||||
version: 2,
|
||||
source: "https://excalidraw.com",
|
||||
source: GITHUB_RELEASES+PLUGIN_VERSION,
|
||||
elements,
|
||||
appState: {
|
||||
theme: forceTheme ?? template?.appState?.theme ?? canvasTheme,
|
||||
@@ -2258,7 +2417,7 @@ export async function createSVG(
|
||||
//createAndOpenDrawing
|
||||
type: "excalidraw",
|
||||
version: 2,
|
||||
source: "https://excalidraw.com",
|
||||
source: GITHUB_RELEASES+PLUGIN_VERSION,
|
||||
elements,
|
||||
appState: {
|
||||
theme: forceTheme ?? template?.appState?.theme ?? canvasTheme,
|
||||
@@ -2369,7 +2528,7 @@ function errorMessage(message: string, source: string) {
|
||||
errorlog({
|
||||
where: "ExcalidrawAutomate",
|
||||
source,
|
||||
message: "unknown error",
|
||||
message: message??"unknown error",
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2380,7 +2539,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) => {
|
||||
@@ -2403,6 +2562,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",
|
||||
@@ -2462,4 +2623,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);
|
||||
}
|
||||
@@ -17,6 +17,9 @@ import {
|
||||
FRONTMATTER_KEY_LINKBUTTON_OPACITY,
|
||||
FRONTMATTER_KEY_ONLOAD_SCRIPT,
|
||||
FRONTMATTER_KEY_AUTOEXPORT,
|
||||
FRONTMATTER_KEY_IFRAME_THEME,
|
||||
DEVICE,
|
||||
IFRAME_THEME_FRONTMATTER_VALUES,
|
||||
} from "./Constants";
|
||||
import { _measureText } from "./ExcalidrawAutomate";
|
||||
import ExcalidrawPlugin from "./main";
|
||||
@@ -24,6 +27,7 @@ import { JSON_parse } from "./Constants";
|
||||
import { TextMode } from "./ExcalidrawView";
|
||||
import {
|
||||
compress,
|
||||
debug,
|
||||
decompress,
|
||||
//getBakPath,
|
||||
getBinaryFileFromDataURL,
|
||||
@@ -31,6 +35,7 @@ import {
|
||||
getExportTheme,
|
||||
getLinkParts,
|
||||
hasExportTheme,
|
||||
isVersionNewerThanOther,
|
||||
LinkParts,
|
||||
wrapTextAtCharLength,
|
||||
} from "./utils/Utils";
|
||||
@@ -40,8 +45,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 };
|
||||
|
||||
@@ -56,7 +61,8 @@ declare module "obsidian" {
|
||||
const {
|
||||
wrapText,
|
||||
getFontString,
|
||||
getMaxContainerWidth,
|
||||
getBoundTextMaxWidth,
|
||||
getDefaultLineHeight,
|
||||
//@ts-ignore
|
||||
} = excalidrawLib;
|
||||
|
||||
@@ -72,6 +78,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);
|
||||
},
|
||||
@@ -241,11 +256,12 @@ export class ExcalidrawData {
|
||||
private app: App;
|
||||
private showLinkBrackets: boolean;
|
||||
private linkPrefix: string;
|
||||
public iFrameTheme: "light" | "dark" | "auto" | "default" = "auto";
|
||||
private urlPrefix: string;
|
||||
public autoexportPreference: AutoexportPreference = AutoexportPreference.inherit;
|
||||
private textMode: TextMode = TextMode.raw;
|
||||
public loaded: boolean = false;
|
||||
private files: Map<FileId, EmbeddedFile> = null; //fileId, path
|
||||
public files: Map<FileId, EmbeddedFile> = null; //fileId, path
|
||||
private equations: Map<FileId, { latex: string; isLoaded: boolean }> = null; //fileId, path
|
||||
private compatibilityMode: boolean = false;
|
||||
selectedElementIds: {[key:string]:boolean} = {}; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/609
|
||||
@@ -266,6 +282,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) {
|
||||
@@ -356,12 +374,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),
|
||||
);
|
||||
@@ -421,6 +444,7 @@ export class ExcalidrawData {
|
||||
this.setLinkPrefix();
|
||||
this.setUrlPrefix();
|
||||
this.setAutoexportPreferences();
|
||||
this.setIFrameThemePreference();
|
||||
|
||||
this.scene = null;
|
||||
|
||||
@@ -517,8 +541,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,
|
||||
@@ -540,13 +565,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);
|
||||
}
|
||||
@@ -586,6 +624,7 @@ export class ExcalidrawData {
|
||||
this.setShowLinkBrackets();
|
||||
this.setLinkPrefix();
|
||||
this.setUrlPrefix();
|
||||
this.setIFrameThemePreference();
|
||||
this.scene = JSON.parse(data);
|
||||
if (!this.scene.files) {
|
||||
this.scene.files = {}; //loading legacy scenes without the files element
|
||||
@@ -615,17 +654,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
|
||||
@@ -651,16 +692,21 @@ export class ExcalidrawData {
|
||||
const originalText =
|
||||
(await this.getText(te.id)) ?? te.originalText ?? te.text;
|
||||
const wrapAt = this.textElements.get(te.id)?.wrapAt;
|
||||
this.updateTextElement(
|
||||
te,
|
||||
wrapAt ? wrapText(
|
||||
try { //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1062
|
||||
this.updateTextElement(
|
||||
te,
|
||||
wrapAt ? wrapText(
|
||||
originalText,
|
||||
getFontString({fontSize: te.fontSize, fontFamily: te.fontFamily}),
|
||||
getBoundTextMaxWidth(container)
|
||||
) : originalText,
|
||||
originalText,
|
||||
getFontString({fontSize: te.fontSize, fontFamily: te.fontFamily}),
|
||||
getMaxContainerWidth(container)
|
||||
) : originalText,
|
||||
originalText,
|
||||
forceupdate,
|
||||
); //(await this.getText(te.id))??te.text serves the case when the whole #Text Elements section is deleted by accident
|
||||
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});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1048,11 +1094,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" : "";
|
||||
@@ -1074,6 +1125,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
|
||||
@@ -1119,7 +1218,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();
|
||||
@@ -1143,47 +1242,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1245,6 +1308,7 @@ export class ExcalidrawData {
|
||||
this.setLinkPrefix() ||
|
||||
this.setUrlPrefix() ||
|
||||
this.setShowLinkBrackets() ||
|
||||
this.setIFrameThemePreference() ||
|
||||
this.findNewElementLinksInScene();
|
||||
await this.updateTextElementsFromScene();
|
||||
if (result || this.findNewTextElementsInScene()) {
|
||||
@@ -1326,7 +1390,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
|
||||
@@ -1413,6 +1479,23 @@ export class ExcalidrawData {
|
||||
}
|
||||
}
|
||||
|
||||
private setIFrameThemePreference(): boolean {
|
||||
const iFrameTheme = this.iFrameTheme;
|
||||
const fileCache = this.app.metadataCache.getFileCache(this.file);
|
||||
if (
|
||||
fileCache?.frontmatter &&
|
||||
fileCache.frontmatter[FRONTMATTER_KEY_IFRAME_THEME] != null
|
||||
) {
|
||||
this.iFrameTheme = fileCache.frontmatter[FRONTMATTER_KEY_IFRAME_THEME].toLowerCase();
|
||||
if (!IFRAME_THEME_FRONTMATTER_VALUES.includes(this.iFrameTheme)) {
|
||||
this.iFrameTheme = "default";
|
||||
}
|
||||
} else {
|
||||
this.iFrameTheme = this.plugin.settings.iframeMatchExcalidrawTheme ? "auto" : "default";
|
||||
}
|
||||
return iFrameTheme != this.iFrameTheme;
|
||||
}
|
||||
|
||||
private setShowLinkBrackets(): boolean {
|
||||
const showLinkBrackets = this.showLinkBrackets;
|
||||
const fileCache = this.app.metadataCache.getFileCache(this.file);
|
||||
@@ -1444,17 +1527,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, {
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1495,6 +1590,13 @@ export class ExcalidrawData {
|
||||
}
|
||||
if (this.plugin.filesMaster.has(fileId)) {
|
||||
const masterFile = this.plugin.filesMaster.get(fileId);
|
||||
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);
|
||||
@@ -1506,7 +1608,8 @@ export class ExcalidrawData {
|
||||
this.file.path,
|
||||
(masterFile.blockrefData
|
||||
? path + "#" + masterFile.blockrefData
|
||||
: path) + (fixScale?"|100%":"")
|
||||
: path) + (fixScale?"|100%":""),
|
||||
masterFile.colorMapJSON
|
||||
);
|
||||
this.files.set(fileId, embeddedFile);
|
||||
return true;
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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,8 @@ import {
|
||||
svgToBase64,
|
||||
} from "./utils/Utils";
|
||||
import { isObsidianThemeDark } from "./utils/ObsidianUtils";
|
||||
import { linkClickModifierType } from "./utils/ModifierkeyHelper";
|
||||
import { imageCache } from "./utils/ImageCache";
|
||||
|
||||
interface imgElementAttributes {
|
||||
file?: TFile;
|
||||
@@ -55,6 +57,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 +82,14 @@ const getIMG = async (
|
||||
withTheme: forceTheme ? true : plugin.settings.exportWithTheme,
|
||||
};
|
||||
const img = createEl("img");
|
||||
let style = `max-width:${imgAttributes.fwidth}px; width:100%;`; //removed !important https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/886
|
||||
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
|
||||
@@ -103,6 +107,8 @@ const getIMG = async (
|
||||
theme ? theme === "dark" : undefined,
|
||||
);
|
||||
|
||||
const cacheReady = imageCache.isReady();
|
||||
|
||||
if (!plugin.settings.displaySVGInPreview) {
|
||||
const width = parseInt(imgAttributes.fwidth);
|
||||
const scale = width >= 2400
|
||||
@@ -115,12 +121,24 @@ const getIMG = async (
|
||||
? 2
|
||||
: 1;
|
||||
|
||||
//In case of PNG I cannot change the viewBox to select the area of the element
|
||||
//being referenced. For PNG only the group reference works
|
||||
|
||||
const cacheKey = {...filenameParts, isDark: theme==="dark", isSVG: false, scale};
|
||||
|
||||
if(cacheReady) {
|
||||
const src = await imageCache.get(cacheKey);
|
||||
//In case of PNG I cannot change the viewBox to select the area of the element
|
||||
//being referenced. For PNG only the group reference works
|
||||
if(src) {
|
||||
img.src = src;
|
||||
return img;
|
||||
}
|
||||
}
|
||||
|
||||
const quickPNG = !filenameParts.hasGroupref
|
||||
? await getQuickImagePreview(plugin, file.path, "png")
|
||||
: undefined;
|
||||
|
||||
|
||||
const png =
|
||||
quickPNG ??
|
||||
(await createPNG(
|
||||
@@ -141,13 +159,25 @@ const getIMG = async (
|
||||
return null;
|
||||
}
|
||||
img.src = URL.createObjectURL(png);
|
||||
cacheReady && imageCache.add(cacheKey, img.src);
|
||||
return img;
|
||||
}
|
||||
|
||||
const cacheKey = {...filenameParts, isDark: theme==="dark", isSVG: false, scale:1};
|
||||
if(cacheReady) {
|
||||
const src = await imageCache.get(cacheKey);
|
||||
if(src) {
|
||||
img.setAttribute("src", src);
|
||||
return img;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if(!(filenameParts.hasBlockref || filenameParts.hasSectionref)) {
|
||||
const quickSVG = await getQuickImagePreview(plugin, file.path, "svg");
|
||||
if (quickSVG) {
|
||||
img.setAttribute("src", svgToBase64(quickSVG));
|
||||
cacheReady && imageCache.add(cacheKey, img.src);
|
||||
return img;
|
||||
}
|
||||
}
|
||||
@@ -179,60 +209,98 @@ 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));
|
||||
cacheReady && imageCache.add(cacheKey, img.src);
|
||||
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 +347,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 +411,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 +633,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
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
330
src/customIFrame.tsx
Normal file
@@ -0,0 +1,330 @@
|
||||
import { NonDeletedExcalidrawElement } from "@zsviczian/excalidraw/types/element/types";
|
||||
import ExcalidrawView from "./ExcalidrawView";
|
||||
import { Notice, Workspace, WorkspaceLeaf, WorkspaceSplit } from "obsidian";
|
||||
import * as React from "react";
|
||||
import { getParentOfClass, isObsidianThemeDark } from "./utils/ObsidianUtils";
|
||||
import { getLinkParts } from "./utils/Utils";
|
||||
import { DEVICE, REG_LINKINDEX_INVALIDCHARS } from "./Constants";
|
||||
import { ExcalidrawImperativeAPI, UIAppState } from "@zsviczian/excalidraw/types/types";
|
||||
|
||||
declare module "obsidian" {
|
||||
interface Workspace {
|
||||
floatingSplit: any;
|
||||
}
|
||||
|
||||
interface WorkspaceSplit {
|
||||
containerEl: HTMLDivElement;
|
||||
}
|
||||
}
|
||||
|
||||
const KEYBOARD_EVENT_TYPES = [
|
||||
"keydown",
|
||||
"keyup",
|
||||
"keypress"
|
||||
];
|
||||
|
||||
const EXTENDED_EVENT_TYPES = [
|
||||
/* "pointerdown",
|
||||
"pointerup",
|
||||
"pointermove",
|
||||
"mousedown",
|
||||
"mouseup",
|
||||
"mousemove",
|
||||
"mouseover",
|
||||
"mouseout",
|
||||
"mouseenter",
|
||||
"mouseleave",
|
||||
"dblclick",
|
||||
"drag",
|
||||
"dragend",
|
||||
"dragenter",
|
||||
"dragexit",
|
||||
"dragleave",
|
||||
"dragover",
|
||||
"dragstart",
|
||||
"drop",*/
|
||||
"copy",
|
||||
"cut",
|
||||
"paste",
|
||||
/*"wheel",
|
||||
"touchstart",
|
||||
"touchend",
|
||||
"touchmove",*/
|
||||
];
|
||||
|
||||
const YOUTUBE_REG =
|
||||
/^(?:http(?:s)?:\/\/)?(?:(?:w){3}.)?youtu(?:be|.be)?(?:\.com)?\/(?:embed\/|watch\?v=|shorts\/)?([a-zA-Z0-9_-]+)(?:\?t=|&t=)?([a-zA-Z0-9_-]+)?[^\s]*$/;
|
||||
const VIMEO_REG =
|
||||
/^(?:http(?:s)?:\/\/)?(?:(?:w){3}.)?(?:player\.)?vimeo\.com\/(?:video\/)?([^?\s]+)(?:\?.*)?$/;
|
||||
const TWITTER_REG = /^(?:http(?:s)?:\/\/)?(?:(?:w){3}.)?twitter.com/;
|
||||
|
||||
type ConstructableWorkspaceSplit = new (ws: Workspace, dir: "horizontal"|"vertical") => WorkspaceSplit;
|
||||
|
||||
const getContainerForDocument = (doc:Document) => {
|
||||
if (doc !== document && app.workspace.floatingSplit) {
|
||||
for (const container of app.workspace.floatingSplit.children) {
|
||||
if (container.doc === doc) return container;
|
||||
}
|
||||
}
|
||||
return app.workspace.rootSplit;
|
||||
};
|
||||
|
||||
export const useDefaultExcalidrawFrame = (element: NonDeletedExcalidrawElement) => {
|
||||
return element.link.match(YOUTUBE_REG) || element.link.match(VIMEO_REG);
|
||||
}
|
||||
|
||||
const leafMap = new Map<string, WorkspaceLeaf>();
|
||||
|
||||
export const renderWebView = (src: string, radius: number):JSX.Element =>{
|
||||
if(DEVICE.isIOS || DEVICE.isAndroid) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const twitterLink = src.match(TWITTER_REG);
|
||||
if (twitterLink) {
|
||||
src = `https://twitframe.com/show?url=${encodeURIComponent(src)}`;
|
||||
}
|
||||
|
||||
return (
|
||||
<webview
|
||||
className="excalidraw__iframe"
|
||||
title="Excalidraw Embedded Content"
|
||||
allowFullScreen={true}
|
||||
src={src}
|
||||
style={{
|
||||
overflow: "hidden",
|
||||
borderRadius: `${radius}px`,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function RenderObsidianView(
|
||||
{ element, linkText, radius, view, containerRef, appState }:{
|
||||
element: NonDeletedExcalidrawElement;
|
||||
linkText: string;
|
||||
radius: number;
|
||||
view: ExcalidrawView;
|
||||
containerRef: React.RefObject<HTMLDivElement>;
|
||||
appState: UIAppState;
|
||||
}): JSX.Element {
|
||||
|
||||
//This is definitely not the right solution, feels like sticking plaster
|
||||
//patch disappearing content on mobile
|
||||
const patchMobileView = () => {
|
||||
if(DEVICE.isDesktop) return;
|
||||
console.log("patching mobile view");
|
||||
const parent = getParentOfClass(view.containerEl,"mod-top");
|
||||
if(parent) {
|
||||
if(!parent.hasClass("mod-visible")) {
|
||||
parent.addClass("mod-visible");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let subpath:string = null;
|
||||
|
||||
if (linkText.search("#") > -1) {
|
||||
const linkParts = getLinkParts(linkText, view.file);
|
||||
subpath = `#${linkParts.isBlockRef ? "^" : ""}${linkParts.ref}`;
|
||||
linkText = linkParts.path;
|
||||
}
|
||||
|
||||
if (linkText.match(REG_LINKINDEX_INVALIDCHARS)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const file = app.metadataCache.getFirstLinkpathDest(
|
||||
linkText,
|
||||
view.file.path,
|
||||
);
|
||||
|
||||
if (!file) {
|
||||
return null;
|
||||
}
|
||||
const react = view.plugin.getPackage(view.ownerWindow).react;
|
||||
|
||||
//@ts-ignore
|
||||
const leafRef = react.useRef<WorkspaceLeaf | null>(null);
|
||||
const isEditingRef = react.useRef(false);
|
||||
const isActiveRef = react.useRef(false);
|
||||
|
||||
const stopPropagation = react.useCallback((event:React.PointerEvent<HTMLElement>) => {
|
||||
if(isActiveRef.current) {
|
||||
event.stopPropagation(); // Stop the event from propagating up the DOM tree
|
||||
}
|
||||
}, [isActiveRef.current]);
|
||||
|
||||
react.useEffect(() => {
|
||||
EXTENDED_EVENT_TYPES.forEach((type) => containerRef.current.removeEventListener(type, stopPropagation));
|
||||
if(!containerRef?.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
if(isActiveRef.current) {
|
||||
EXTENDED_EVENT_TYPES.forEach((type) => containerRef.current.addEventListener(type, stopPropagation));
|
||||
}
|
||||
|
||||
return () => {
|
||||
if(!containerRef?.current) {
|
||||
return;
|
||||
}
|
||||
EXTENDED_EVENT_TYPES.forEach((type) => containerRef.current.removeEventListener(type, stopPropagation));
|
||||
}; //cleanup on unmount
|
||||
}, [isActiveRef.current, containerRef.current]);
|
||||
|
||||
react.useEffect(() => {
|
||||
if(!containerRef?.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
while(containerRef.current.hasChildNodes()) {
|
||||
containerRef.current.removeChild(containerRef.current.lastChild);
|
||||
}
|
||||
|
||||
const doc = view.ownerDocument;
|
||||
const rootSplit:WorkspaceSplit = new (WorkspaceSplit as ConstructableWorkspaceSplit)(app.workspace, "vertical");
|
||||
rootSplit.getRoot = () => app.workspace[doc === document ? 'rootSplit' : 'floatingSplit'];
|
||||
rootSplit.getContainer = () => getContainerForDocument(doc);
|
||||
containerRef.current.appendChild(rootSplit.containerEl);
|
||||
rootSplit.containerEl.style.width = '100%';
|
||||
rootSplit.containerEl.style.height = '100%';
|
||||
rootSplit.containerEl.style.borderRadius = `${radius}px`;
|
||||
leafRef.current = app.workspace.createLeafInParent(rootSplit, 0);
|
||||
const workspaceLeaf:HTMLDivElement = rootSplit.containerEl.querySelector("div.workspace-leaf");
|
||||
if(workspaceLeaf) workspaceLeaf.style.borderRadius = `${radius}px`;
|
||||
(async () => {
|
||||
await leafRef.current.openFile(file, subpath ? { eState: { subpath }, state: {mode:"preview"} } : undefined);
|
||||
if (leafRef.current.view?.getViewType() === "canvas") {
|
||||
leafRef.current.view.canvas?.setReadonly(true);
|
||||
}
|
||||
patchMobileView();
|
||||
})();
|
||||
return () => {}; //cleanup on unmount
|
||||
}, [linkText, subpath]);
|
||||
|
||||
const handleClick = react.useCallback((event: React.PointerEvent<HTMLElement>) => {
|
||||
if(isActiveRef.current) {
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
if (isActiveRef.current && !isEditingRef.current) {
|
||||
if (!leafRef.current?.view || leafRef.current.view.getViewType() !== 'markdown') {
|
||||
return;
|
||||
}
|
||||
|
||||
const api:ExcalidrawImperativeAPI = view.excalidrawAPI;
|
||||
const el = api.getSceneElements().filter(el=>el.id === element.id)[0];
|
||||
|
||||
if(!el || el.angle !== 0) {
|
||||
new Notice("Sorry, cannot edit rotated markdown documents");
|
||||
return;
|
||||
}
|
||||
//@ts-ignore
|
||||
const modes = leafRef.current.view.modes;
|
||||
if (!modes) {
|
||||
return;
|
||||
}
|
||||
leafRef.current.view.setMode(modes['source']);
|
||||
app.workspace.setActiveLeaf(leafRef.current);
|
||||
isEditingRef.current = true;
|
||||
patchMobileView();
|
||||
}
|
||||
}, [leafRef.current, isActiveRef.current, element]);
|
||||
|
||||
react.useEffect(() => {
|
||||
if(!containerRef?.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
KEYBOARD_EVENT_TYPES.forEach((type) => containerRef.current.addEventListener(type, stopPropagation));
|
||||
containerRef.current.addEventListener("click", handleClick);
|
||||
|
||||
return () => {
|
||||
if(!containerRef?.current) {
|
||||
return;
|
||||
}
|
||||
KEYBOARD_EVENT_TYPES.forEach((type) => containerRef.current.removeEventListener(type, stopPropagation));
|
||||
EXTENDED_EVENT_TYPES.forEach((type) => containerRef.current.removeEventListener(type, stopPropagation));
|
||||
containerRef.current.removeEventListener("click", handleClick);
|
||||
}; //cleanup on unmount
|
||||
}, []);
|
||||
|
||||
|
||||
react.useEffect(() => {
|
||||
if(!containerRef?.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
if(!leafRef.current?.view || leafRef.current.view.getViewType() !== "markdown") {
|
||||
return;
|
||||
}
|
||||
|
||||
//@ts-ignore
|
||||
const modes = leafRef.current.view.modes;
|
||||
if(!modes) {
|
||||
return;
|
||||
}
|
||||
|
||||
isActiveRef.current = (appState.activeIFrame?.element.id === element.id) && (appState.activeIFrame?.state === "active");
|
||||
|
||||
if(!isActiveRef.current) {
|
||||
//@ts-ignore
|
||||
leafRef.current.view.setMode(modes["preview"]);
|
||||
isEditingRef.current = false;
|
||||
app.workspace.setActiveLeaf(view.leaf);
|
||||
return;
|
||||
}
|
||||
}, [appState.activeIFrame?.element, appState.activeIFrame?.state, element.id]);
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export const CustomIFrame: React.FC<{element: NonDeletedExcalidrawElement; radius: number; view: ExcalidrawView; appState: UIAppState; linkText: string}> = ({ element, radius, view, appState, linkText }) => {
|
||||
const react = view.plugin.getPackage(view.ownerWindow).react;
|
||||
const containerRef: React.RefObject<HTMLDivElement> = react.useRef(null);
|
||||
const theme = view.excalidrawData.iFrameTheme === "dark"
|
||||
? "theme-dark"
|
||||
: view.excalidrawData.iFrameTheme === "light"
|
||||
? "theme-light"
|
||||
: view.excalidrawData.iFrameTheme === "auto"
|
||||
? appState.theme === "dark" ? "theme-dark" : "theme-light"
|
||||
: isObsidianThemeDark() ? "theme-dark" : "theme-light";
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
style = {{
|
||||
width: `100%`,
|
||||
height: `100%`,
|
||||
borderRadius: `${radius}px`,
|
||||
color: `var(--text-normal)`,
|
||||
}}
|
||||
className={theme}
|
||||
>
|
||||
<RenderObsidianView
|
||||
element={element}
|
||||
linkText={linkText}
|
||||
radius={radius}
|
||||
view={view}
|
||||
containerRef={containerRef}
|
||||
appState={appState}/>
|
||||
{(appState.activeIFrame?.element === element && appState.activeIFrame?.state === "hover") && (<div
|
||||
style={{
|
||||
content: "",
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
width: `100%`,
|
||||
height: `100%`,
|
||||
background: `radial-gradient(
|
||||
ellipse at center,
|
||||
rgba(0, 0, 0, 0) 20%,
|
||||
rgba(0, 0, 0, 0.6) 80%
|
||||
)`,
|
||||
}}/>)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
211
src/dialogs/ExportDialog.ts
Normal 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();
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
})();
|
||||
}
|
||||
|
||||
342
src/dialogs/InsertPDFModal.ts
Normal 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();
|
||||
}
|
||||
}
|
||||
|
||||
612
src/dialogs/PenSettingsModal.ts
Normal 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;
|
||||
})
|
||||
)
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,11 +145,17 @@ 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: "",
|
||||
},
|
||||
{
|
||||
field: "getSceneFromFile",
|
||||
code: "async getSceneFromFile(file: TFile): Promise<{elements: ExcalidrawElement[]; appState: AppState;}>;",
|
||||
desc: "returns the elements and appState from a file, if the file is not an excalidraw file, it will return null",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "getElements",
|
||||
code: "getElements(): ExcalidrawElement[];",
|
||||
@@ -204,9 +216,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: "",
|
||||
},
|
||||
@@ -228,6 +246,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
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: "",
|
||||
},
|
||||
{
|
||||
field: "addIFrame",
|
||||
code: "addIFrame(topX: number, topY: number, width: number, height: number, url?: string, file?: TFile): string;",
|
||||
desc: "Adds an iframe to the drawing. If url is not null then the iframe will be loaded from the url. The url maybe a markdown link to an note in the Vault or a weblink. If url is null then the iframe will be loaded from the file. Both the url and the file may not be null.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "addLaTex",
|
||||
code: "addLaTex(topX: number, topY: number, tex: string): Promise<string>;",
|
||||
@@ -434,8 +458,8 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
},
|
||||
{
|
||||
field: "selectElementsInView",
|
||||
code: "selectElementsInView(elements: ExcalidrawElement[]):void;",
|
||||
desc: "Elements provided will be set as selected in the targetView.",
|
||||
code: "selectElementsInView(elements: ExcalidrawElement[] | string[]):void;",
|
||||
desc: "You can supply a list of Excalidraw Elements or the string IDs of those elements. The elements provided will be set as selected in the targetView.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
@@ -515,9 +539,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
export const EXCALIDRAW_SCRIPTENGINE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "inputPrompt",
|
||||
code: "inputPrompt: (header: string, placeholder?: string, value?: string, buttons?: [{caption:string, 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: "",
|
||||
@@ -528,6 +555,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[] = [
|
||||
@@ -628,5 +661,12 @@ export const FRONTMATTER_KEYS_INFO: SuggesterInfo[] = [
|
||||
desc: "Override autoexport settings for this file. Valid values are\nnone\nboth\npng\nsvg",
|
||||
after: ": png",
|
||||
},
|
||||
{
|
||||
field: "iframe-theme",
|
||||
code: null,
|
||||
desc: "Override iFrame theme plugin-settings for this file. 'match' will match the Excalidraw theme, 'default' will match the obsidian theme. Valid values are\ndark\nlight\nauto\ndefault",
|
||||
after: ": auto",
|
||||
},
|
||||
|
||||
|
||||
];
|
||||
|
||||
252
src/dialogs/UniversalInsertFileModal.ts
Normal file
@@ -0,0 +1,252 @@
|
||||
import { ButtonComponent, DropdownComponent, TFile, ToggleComponent } from "obsidian";
|
||||
import ExcalidrawView from "../ExcalidrawView";
|
||||
import ExcalidrawPlugin from "../main";
|
||||
import { Modal, Setting, TextComponent } from "obsidian";
|
||||
import { FileSuggestionModal } from "./FolderSuggester";
|
||||
import { IMAGE_TYPES, REG_BLOCK_REF_CLEAN } from "src/Constants";
|
||||
import { insertIFrameToView, insertImageToView } from "src/utils/ExcalidrawViewUtils";
|
||||
import { getEA } from "src";
|
||||
import { InsertPDFModal } from "./InsertPDFModal";
|
||||
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/types";
|
||||
import { MAX_IMAGE_SIZE } from "src/Constants";
|
||||
import { ExcalidrawAutomate } from "src/ExcalidrawAutomate";
|
||||
|
||||
const {
|
||||
viewportCoordsToSceneCoords,
|
||||
sceneCoordsToViewportCoords
|
||||
//@ts-ignore
|
||||
} = excalidrawLib;
|
||||
|
||||
export class UniversalInsertFileModal extends Modal {
|
||||
private center: { x: number, y: number } = { x: 0, y: 0 };
|
||||
constructor(
|
||||
private plugin: ExcalidrawPlugin,
|
||||
private view: ExcalidrawView,
|
||||
) {
|
||||
super(app);
|
||||
const appState = (view.excalidrawAPI as ExcalidrawImperativeAPI).getAppState();
|
||||
const containerRect = view.containerEl.getBoundingClientRect();
|
||||
const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
|
||||
const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
|
||||
|
||||
const curViewport = sceneCoordsToViewportCoords({
|
||||
sceneX: view.currentPosition.x,
|
||||
sceneY: view.currentPosition.y,},
|
||||
appState);
|
||||
|
||||
if (
|
||||
curViewport.x >= containerRect.left + 150 &&
|
||||
curViewport.y <= containerRect.right - 150 &&
|
||||
curViewport.y >= containerRect.top + 150 &&
|
||||
curViewport.y <= containerRect.bottom - 150
|
||||
) {
|
||||
const sceneX = view.currentPosition.x - MAX_IMAGE_SIZE / 2;
|
||||
const sceneY = view.currentPosition.y - MAX_IMAGE_SIZE / 2;
|
||||
this.center = {x: sceneX, y: sceneY};
|
||||
} else {
|
||||
const centerX = containerRect.left + containerRect.width / 2;
|
||||
const centerY = containerRect.top + containerRect.height / 2;
|
||||
|
||||
const clientX = Math.max(0, Math.min(viewportWidth, centerX));
|
||||
const clientY = Math.max(0, Math.min(viewportHeight, centerY));
|
||||
|
||||
this.center = viewportCoordsToSceneCoords ({clientX, clientY}, appState);
|
||||
this.center = {x: this.center.x - MAX_IMAGE_SIZE / 2, y: this.center.y - MAX_IMAGE_SIZE / 2};
|
||||
}
|
||||
}
|
||||
|
||||
private onKeyDown: (evt: KeyboardEvent) => void;
|
||||
|
||||
onOpen(): void {
|
||||
this.containerEl.classList.add("excalidraw-release");
|
||||
this.titleEl.setText(`Insert File From Vault`);
|
||||
this.createForm();
|
||||
}
|
||||
|
||||
async createForm() {
|
||||
const ce = this.contentEl;
|
||||
let sectionPicker: DropdownComponent;
|
||||
let sectionPickerSetting: Setting;
|
||||
let actionIFrame: ButtonComponent;
|
||||
let actionImage: ButtonComponent;
|
||||
let actionPDF: ButtonComponent;
|
||||
let sizeToggleSetting: Setting
|
||||
let anchorTo100: boolean = false;
|
||||
let file: TFile;
|
||||
|
||||
const updateForm = async () => {
|
||||
const ea = this.plugin.ea;
|
||||
const isMarkdown = file && file.extension === "md" && !ea.isExcalidrawFile(file);
|
||||
const isImage = file && (IMAGE_TYPES.contains(file.extension) || ea.isExcalidrawFile(file));
|
||||
const isIFrame = file && !isImage;
|
||||
const isPDF = file && file.extension === "pdf";
|
||||
const isExcalidraw = file && ea.isExcalidrawFile(file);
|
||||
|
||||
if (isMarkdown) {
|
||||
sectionPickerSetting.settingEl.style.display = "";
|
||||
sectionPicker.selectEl.style.display = "block";
|
||||
while(sectionPicker.selectEl.options.length > 0) {
|
||||
sectionPicker.selectEl.remove(0);
|
||||
}
|
||||
sectionPicker.addOption("","");
|
||||
(await app.metadataCache.blockCache
|
||||
.getForFile({ isCancelled: () => false },file))
|
||||
.blocks.filter((b: any) => b.display && b.node?.type === "heading")
|
||||
.forEach((b: any) => {
|
||||
sectionPicker.addOption(
|
||||
`#${b.display.replaceAll(REG_BLOCK_REF_CLEAN, "").trim()}`,
|
||||
b.display)
|
||||
});
|
||||
} else {
|
||||
sectionPickerSetting.settingEl.style.display = "none";
|
||||
sectionPicker.selectEl.style.display = "none";
|
||||
}
|
||||
|
||||
if (isExcalidraw) {
|
||||
sizeToggleSetting.settingEl.style.display = "";
|
||||
} else {
|
||||
sizeToggleSetting.settingEl.style.display = "none";
|
||||
}
|
||||
|
||||
if (isImage || (file?.extension === "md")) {
|
||||
actionImage.buttonEl.style.display = "block";
|
||||
} else {
|
||||
actionImage.buttonEl.style.display = "none";
|
||||
}
|
||||
|
||||
if (isIFrame) {
|
||||
actionIFrame.buttonEl.style.display = "block";
|
||||
} else {
|
||||
actionIFrame.buttonEl.style.display = "none";
|
||||
}
|
||||
|
||||
if (isPDF) {
|
||||
actionPDF.buttonEl.style.display = "block";
|
||||
} else {
|
||||
actionPDF.buttonEl.style.display = "none";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
const search = new TextComponent(ce);
|
||||
search.inputEl.style.width = "100%";
|
||||
const suggester = new FileSuggestionModal(this.app, search,app.vault.getFiles().filter((f: TFile) => f!==this.view.file));
|
||||
search.onChange(() => {
|
||||
file = suggester.getSelectedItem();
|
||||
updateForm();
|
||||
});
|
||||
|
||||
sectionPickerSetting = new Setting(ce)
|
||||
.setName("Select section heading")
|
||||
.addDropdown(dropdown => {
|
||||
sectionPicker = dropdown;
|
||||
sectionPicker.selectEl.style.width = "100%";
|
||||
})
|
||||
|
||||
sizeToggleSetting = new Setting(ce)
|
||||
.setName("Anchor to 100% of original size")
|
||||
.setDesc("This is a pro feature, use it only if you understand how it works. If enabled even if you change the size of the imported image in Excalidraw, the next time you open the drawing this image will pop back to 100% size. This is useful when embedding an atomic Excalidraw idea into another note and preserving relative sizing of text and icons.")
|
||||
.addToggle(toggle => {
|
||||
toggle.setValue(anchorTo100)
|
||||
.onChange((value) => {
|
||||
anchorTo100 = value;
|
||||
})
|
||||
})
|
||||
|
||||
new Setting(ce)
|
||||
.addButton(button => {
|
||||
button
|
||||
.setButtonText("as iFrame")
|
||||
.onClick(async () => {
|
||||
const path = app.metadataCache.fileToLinktext(
|
||||
file,
|
||||
this.view.file.path,
|
||||
file.extension === "md",
|
||||
)
|
||||
const ea:ExcalidrawAutomate = getEA(this.view);
|
||||
ea.selectElementsInView(
|
||||
[await insertIFrameToView (
|
||||
ea,
|
||||
this.center,
|
||||
//this.view.currentPosition,
|
||||
undefined,
|
||||
`[[${path}${sectionPicker.selectEl.value}]]`,
|
||||
)]
|
||||
);
|
||||
this.close();
|
||||
})
|
||||
actionIFrame = button;
|
||||
})
|
||||
.addButton(button => {
|
||||
button
|
||||
.setButtonText("as Pdf")
|
||||
.onClick(() => {
|
||||
const insertPDFModal = new InsertPDFModal(this.plugin, this.view);
|
||||
insertPDFModal.open(file);
|
||||
this.close();
|
||||
})
|
||||
actionPDF = button;
|
||||
})
|
||||
.addButton(button => {
|
||||
button
|
||||
.setButtonText("as Image")
|
||||
.onClick(async () => {
|
||||
const ea:ExcalidrawAutomate = getEA(this.view);
|
||||
ea.selectElementsInView(
|
||||
[await insertImageToView (
|
||||
ea,
|
||||
this.center,
|
||||
//this.view.currentPosition,
|
||||
file,
|
||||
ea.isExcalidrawFile(file) ? !anchorTo100 : undefined,
|
||||
)]
|
||||
);
|
||||
this.close();
|
||||
})
|
||||
actionImage = button;
|
||||
})
|
||||
|
||||
this.view.ownerWindow.addEventListener("keydown", this.onKeyDown = (evt: KeyboardEvent) => {
|
||||
const isVisible = (b: ButtonComponent) => b.buttonEl.style.display !== "none";
|
||||
switch (evt.key) {
|
||||
case "Escape": this.close(); return;
|
||||
case "Enter":
|
||||
if (isVisible(actionIFrame) && !isVisible(actionImage) && !isVisible(actionPDF)) {
|
||||
actionIFrame.buttonEl.click();
|
||||
return;
|
||||
}
|
||||
if (isVisible(actionImage) && !isVisible(actionIFrame) && !isVisible(actionPDF)) {
|
||||
actionImage.buttonEl.click();
|
||||
return;
|
||||
}
|
||||
if (isVisible(actionPDF) && !isVisible(actionIFrame) && !isVisible(actionImage)) {
|
||||
actionPDF.buttonEl.click();
|
||||
return;
|
||||
}
|
||||
return;
|
||||
case "i":
|
||||
if (isVisible(actionImage)) {
|
||||
actionImage.buttonEl.click();
|
||||
}
|
||||
return;
|
||||
case "p":
|
||||
if (isVisible(actionPDF)) {
|
||||
actionPDF.buttonEl.click();
|
||||
}
|
||||
return
|
||||
case "f":
|
||||
if (isVisible(actionIFrame)) {
|
||||
actionIFrame.buttonEl.click();
|
||||
}
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
search.inputEl.focus();
|
||||
updateForm();
|
||||
}
|
||||
|
||||
onClose(): void {
|
||||
this.view.ownerWindow.removeEventListener("keydown", this.onKeyDown);
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,48 +1,51 @@
|
||||
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",
|
||||
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,8 +58,10 @@ 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",
|
||||
UNIVERSAL_ADD_FILE: "Insert ANY file from your Vault to the active drawing",
|
||||
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",
|
||||
@@ -69,18 +74,13 @@ 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)",
|
||||
EXPORT_IMAGE: `Export Image`,
|
||||
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)",
|
||||
@@ -172,10 +172,17 @@ FILENAME_HEAD: "Filename",
|
||||
"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." +
|
||||
"<br><b>Toggle ON:</b> Left-handed mode.<br><b>Toggle OFF:</b> Right-handed moded",
|
||||
IFRAME_MATCH_THEME_NAME: "IFrames (markdown embeds) to match Excalidraw theme",
|
||||
IFRAME_MATCH_THEME_DESC:
|
||||
"Set this to true if you are for example using Obsidian in dark mode but use excalidraw with a light background. " +
|
||||
"With this setting the embedded Obsidian markdown document will match the Excalidraw theme (i.e. light colors if Excalidraw is in light mode). ",
|
||||
MATCH_THEME_NAME: "New drawing to match Obsidian theme",
|
||||
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. " +
|
||||
@@ -196,6 +203,16 @@ FILENAME_HEAD: "Filename",
|
||||
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",
|
||||
@@ -207,7 +224,7 @@ FILENAME_HEAD: "Filename",
|
||||
"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. " +
|
||||
@@ -215,13 +232,13 @@ FILENAME_HEAD: "Filename",
|
||||
"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: `${
|
||||
@@ -244,16 +261,16 @@ FILENAME_HEAD: "Filename",
|
||||
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.",
|
||||
@@ -279,8 +296,9 @@ FILENAME_HEAD: "Filename",
|
||||
"Use the <code>http://iframely.server.crestify.com/iframely?url=</code> to get title of page when dropping a link into Excalidraw",
|
||||
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:
|
||||
"The width of the markdown page. This effects the word wrapping when transcluding longer paragraphs, and the width of " +
|
||||
@@ -311,12 +329,16 @@ FILENAME_HEAD: "Filename",
|
||||
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. " +
|
||||
'You can override this css setting by adding the following frontmatter-key to the embedded markdown file: "excalidraw-css: css_file_in_vault|css-snippet".',
|
||||
EMBED_HEAD: "Embed & Export",
|
||||
EMBED_IMAGE_CACHE_NAME: "Cache images for embedding in markdown",
|
||||
EMBED_IMAGE_CACHE_DESC: "Cache images for embedding in markdown. This will speed up the embedding process, but in case you compose images of several sub-component drawings, " +
|
||||
"the embedded image in Markdown won't update until you open the drawing and save it to trigger an update of the cache.",
|
||||
EMBED_IMAGE_CACHE_CLEAR: "Clear image cache",
|
||||
EMBED_REUSE_EXPORTED_IMAGE_NAME:
|
||||
"If found, use the already exported image for preview",
|
||||
EMBED_REUSE_EXPORTED_IMAGE_DESC:
|
||||
@@ -361,7 +383,7 @@ FILENAME_HEAD: "Filename",
|
||||
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:
|
||||
@@ -397,6 +419,12 @@ FILENAME_HEAD: "Filename",
|
||||
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.",
|
||||
@@ -421,7 +449,7 @@ FILENAME_HEAD: "Filename",
|
||||
"Files that use this fourth font will (partly) lose their platform independence. " +
|
||||
"Depending on the custom font set in settings, they will look differently when loaded in another vault, or at a later time. " +
|
||||
"Also the 4th font will display as system default font on excalidraw.com, or other Excalidraw versions.",
|
||||
FOURTH_FONT_NAME: "Forth font file",
|
||||
FOURTH_FONT_NAME: "Fourth font file",
|
||||
FOURTH_FONT_DESC:
|
||||
"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.",
|
||||
@@ -432,7 +460,7 @@ FILENAME_HEAD: "Filename",
|
||||
"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 Conditaions</a> and the " +
|
||||
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 " +
|
||||
@@ -441,7 +469,7 @@ FILENAME_HEAD: "Filename",
|
||||
|
||||
//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",
|
||||
@@ -450,6 +478,9 @@ FILENAME_HEAD: "Filename",
|
||||
"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:
|
||||
@@ -466,6 +497,7 @@ FILENAME_HEAD: "Filename",
|
||||
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"
|
||||
};
|
||||
|
||||
@@ -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.5(50%)且不能超过 10(1000%)。",
|
||||
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 的内部链接,或者打开所选的图形或文本元素里的链接"
|
||||
};
|
||||
|
||||
251
src/main.ts
@@ -16,7 +16,7 @@ import {
|
||||
request,
|
||||
MetadataCache,
|
||||
FrontMatterCache,
|
||||
Command
|
||||
Command,
|
||||
} from "obsidian";
|
||||
import {
|
||||
BLANK_DRAWING,
|
||||
@@ -25,22 +25,19 @@ import {
|
||||
ICON_NAME,
|
||||
SCRIPTENGINE_ICON,
|
||||
SCRIPTENGINE_ICON_NAME,
|
||||
PNG_ICON,
|
||||
PNG_ICON_NAME,
|
||||
SVG_ICON,
|
||||
SVG_ICON_NAME,
|
||||
RERENDER_EVENT,
|
||||
FRONTMATTER_KEY,
|
||||
FRONTMATTER,
|
||||
JSON_parse,
|
||||
nanoid,
|
||||
DARK_BLANK_DRAWING,
|
||||
CTRL_OR_CMD,
|
||||
SCRIPT_INSTALL_CODEBLOCK,
|
||||
SCRIPT_INSTALL_FOLDER,
|
||||
VIRGIL_FONT,
|
||||
VIRGIL_DATAURL,
|
||||
EXPORT_TYPES,
|
||||
EXPORT_IMG_ICON_NAME,
|
||||
EXPORT_IMG_ICON,
|
||||
} from "./Constants";
|
||||
import ExcalidrawView, { TextMode, getTextMode } from "./ExcalidrawView";
|
||||
import {
|
||||
@@ -52,7 +49,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";
|
||||
@@ -96,15 +93,19 @@ 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";
|
||||
import { ExportDialog } from "./dialogs/ExportDialog";
|
||||
import { UniversalInsertFileModal } from "./dialogs/UniversalInsertFileModal";
|
||||
import { image } from "html2canvas/dist/types/css/types/image";
|
||||
import { imageCache } from "./utils/ImageCache";
|
||||
|
||||
declare module "obsidian" {
|
||||
interface App {
|
||||
@@ -157,7 +158,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 +169,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,24 +198,12 @@ 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(PNG_ICON_NAME, PNG_ICON);
|
||||
addIcon(SVG_ICON_NAME, SVG_ICON);
|
||||
addIcon(EXPORT_IMG_ICON_NAME, EXPORT_IMG_ICON);
|
||||
|
||||
await this.loadSettings({reEnableAutosave:true});
|
||||
imageCache.plugin = this;
|
||||
|
||||
this.addSettingTab(new ExcalidrawSettingTab(this.app, this));
|
||||
this.ea = await initExcalidrawAutomate(this);
|
||||
@@ -417,7 +395,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";
|
||||
});
|
||||
@@ -463,7 +441,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
break;
|
||||
}
|
||||
};
|
||||
button.addClass("mod-cta");
|
||||
button.addClass("mod-muted");
|
||||
let decodedURI = source;
|
||||
try {
|
||||
decodedURI = decodeURI(source);
|
||||
@@ -477,9 +455,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 () => {
|
||||
@@ -517,6 +496,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}`);
|
||||
@@ -709,8 +691,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) => {
|
||||
@@ -718,7 +700,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(
|
||||
@@ -727,7 +709,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
}
|
||||
this.createAndOpenDrawing(
|
||||
getDrawingFilename(this.settings),
|
||||
"active-pane",
|
||||
linkClickModifierType(emulateCTRLClickForLinks(e)),
|
||||
folderpath,
|
||||
);
|
||||
});
|
||||
@@ -857,6 +839,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"),
|
||||
@@ -877,7 +867,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) {
|
||||
@@ -898,7 +888,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({
|
||||
@@ -913,6 +903,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"),
|
||||
@@ -937,24 +939,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
},
|
||||
});
|
||||
|
||||
this.addCommand({
|
||||
id: "export-svg",
|
||||
name: t("EXPORT_SVG"),
|
||||
checkCallback: (checking: boolean) => {
|
||||
if (checking) {
|
||||
return (
|
||||
Boolean(this.app.workspace.getActiveViewOfType(ExcalidrawView))
|
||||
);
|
||||
}
|
||||
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
|
||||
if (view) {
|
||||
view.saveSVG();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
|
||||
this.addCommand({
|
||||
id: "run-ocr",
|
||||
name: t("RUN_OCR"),
|
||||
@@ -1018,8 +1002,8 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
});
|
||||
|
||||
this.addCommand({
|
||||
id: "export-png",
|
||||
name: t("EXPORT_PNG"),
|
||||
id: "disable-binding",
|
||||
name: t("TOGGLE_DISABLEBINDING"),
|
||||
checkCallback: (checking: boolean) => {
|
||||
if (checking) {
|
||||
return (
|
||||
@@ -1028,7 +1012,29 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
}
|
||||
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
|
||||
if (view) {
|
||||
view.savePNG();
|
||||
view.toggleDisableBinding();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
|
||||
this.addCommand({
|
||||
id: "export-image",
|
||||
name: t("EXPORT_IMAGE"),
|
||||
checkCallback: (checking: boolean) => {
|
||||
if (checking) {
|
||||
return (
|
||||
Boolean(this.app.workspace.getActiveViewOfType(ExcalidrawView))
|
||||
);
|
||||
}
|
||||
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
|
||||
if (view) {
|
||||
if(!view.exportDialog) {
|
||||
view.exportDialog = new ExportDialog(this, view,view.file);
|
||||
view.exportDialog.createForm();
|
||||
}
|
||||
view.exportDialog.open();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
@@ -1332,6 +1338,40 @@ 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: "universal-add-file",
|
||||
name: t("UNIVERSAL_ADD_FILE"),
|
||||
checkCallback: (checking: boolean) => {
|
||||
if (checking) {
|
||||
return Boolean(this.app.workspace.getActiveViewOfType(ExcalidrawView))
|
||||
}
|
||||
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
|
||||
if (view) {
|
||||
const insertFileModal = new UniversalInsertFileModal(this, view);
|
||||
insertFileModal.open();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
|
||||
this.addCommand({
|
||||
id: "insert-LaTeX-symbol",
|
||||
name: t("INSERT_LATEX"),
|
||||
@@ -1485,6 +1525,18 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
}
|
||||
|
||||
private registerMonkeyPatches() {
|
||||
//@ts-ignore
|
||||
if(!app.plugins?.plugins?.["obsidian-hover-editor"]) {
|
||||
this.register( //stolen from hover editor
|
||||
around(WorkspaceLeaf.prototype, {
|
||||
getRoot(old) {
|
||||
return function () {
|
||||
const top = old.call(this);
|
||||
return top.getRoot === this.getRoot ? top : top.getRoot();
|
||||
};
|
||||
}
|
||||
}));
|
||||
}
|
||||
this.registerEvent(
|
||||
app.workspace.on("editor-menu", (menu, editor, view) => {
|
||||
if(!view || !(view instanceof MarkdownView)) return;
|
||||
@@ -1798,7 +1850,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" &&
|
||||
@@ -1807,9 +1871,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);
|
||||
}
|
||||
}
|
||||
@@ -2099,8 +2167,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));
|
||||
@@ -2109,16 +2177,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)
|
||||
@@ -2130,12 +2204,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> {
|
||||
@@ -2236,12 +2317,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
@@ -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">
|
||||
|
||||
@@ -1,6 +1,110 @@
|
||||
import * as React from "react";
|
||||
import { PenStyle } from "src/PenTypes";
|
||||
|
||||
export const ICONS = {
|
||||
ExportImage: (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="var(--icon-fill-color)"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<g strokeWidth="1.25">
|
||||
<path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
|
||||
<path d="M15 8h.01"></path>
|
||||
<path d="M12 20h-5a3 3 0 0 1 -3 -3v-10a3 3 0 0 1 3 -3h10a3 3 0 0 1 3 3v5"></path>
|
||||
<path d="M4 15l4 -4c.928 -.893 2.072 -.893 3 0l4 4"></path>
|
||||
<path d="M14 14l1 -1c.617 -.593 1.328 -.793 2.009 -.598"></path>
|
||||
<path d="M19 16v6"></path>
|
||||
<path d="M22 19l-3 3l-3 -3"></path>
|
||||
</g>
|
||||
</svg>
|
||||
),
|
||||
Discord: (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="var(--icon-fill-color)"
|
||||
stroke="none"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
viewBox="0 0 640 512"
|
||||
>
|
||||
<path
|
||||
d="M524.531,69.836a1.5,1.5,0,0,0-.764-.7A485.065,485.065,0,0,0,404.081,32.03a1.816,1.816,0,0,0-1.923.91,337.461,337.461,0,0,0-14.9,30.6,447.848,447.848,0,0,0-134.426,0,309.541,309.541,0,0,0-15.135-30.6,1.89,1.89,0,0,0-1.924-.91A483.689,483.689,0,0,0,116.085,69.137a1.712,1.712,0,0,0-.788.676C39.068,183.651,18.186,294.69,28.43,404.354a2.016,2.016,0,0,0,.765,1.375A487.666,487.666,0,0,0,176.02,479.918a1.9,1.9,0,0,0,2.063-.676A348.2,348.2,0,0,0,208.12,430.4a1.86,1.86,0,0,0-1.019-2.588,321.173,321.173,0,0,1-45.868-21.853,1.885,1.885,0,0,1-.185-3.126c3.082-2.309,6.166-4.711,9.109-7.137a1.819,1.819,0,0,1,1.9-.256c96.229,43.917,200.41,43.917,295.5,0a1.812,1.812,0,0,1,1.924.233c2.944,2.426,6.027,4.851,9.132,7.16a1.884,1.884,0,0,1-.162,3.126,301.407,301.407,0,0,1-45.89,21.83,1.875,1.875,0,0,0-1,2.611,391.055,391.055,0,0,0,30.014,48.815,1.864,1.864,0,0,0,2.063.7A486.048,486.048,0,0,0,610.7,405.729a1.882,1.882,0,0,0,.765-1.352C623.729,277.594,590.933,167.465,524.531,69.836ZM222.491,337.58c-28.972,0-52.844-26.587-52.844-59.239S193.056,219.1,222.491,219.1c29.665,0,53.306,26.82,52.843,59.239C275.334,310.993,251.924,337.58,222.491,337.58Zm195.38,0c-28.971,0-52.843-26.587-52.843-59.239S388.437,219.1,417.871,219.1c29.667,0,53.307,26.82,52.844,59.239C470.715,310.993,447.538,337.58,417.871,337.58Z"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
Github: (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="var(--icon-fill-color)"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path
|
||||
d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4">
|
||||
</path>
|
||||
<path
|
||||
d="M9 18c-4.51 2-5-2-7-2">
|
||||
</path>
|
||||
</svg>
|
||||
),
|
||||
YouTube: (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="var(--icon-fill-color)"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path
|
||||
d="M12 19c-2.3 0-6.4-.2-8.1-.6-.7-.2-1.2-.7-1.4-1.4-.3-1.1-.5-3.4-.5-5s.2-3.9.5-5c.2-.7.7-1.2 1.4-1.4C5.6 5.2 9.7 5 12 5s6.4.2 8.1.6c.7.2 1.2.7 1.4 1.4.3 1.1.5 3.4.5 5s-.2 3.9-.5 5c-.2.7-.7 1.2-1.4 1.4-1.7.4-5.8.6-8.1.6 0 0 0 0 0 0z">
|
||||
</path>
|
||||
<polygon points="10 15 15 12 10 9"></polygon>
|
||||
</svg>
|
||||
)
|
||||
,
|
||||
heart: (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="var(--icon-fill-color)"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path
|
||||
d="M20.42 4.58a5.4 5.4 0 0 0-7.65 0l-.77.78-.77-.78a5.4 5.4 0 0 0-7.65 0C1.46 6.7 1.33 10.28 4 13l8 8 8-8c2.67-2.72 2.54-6.3.42-8.42z">
|
||||
</path>
|
||||
</svg>
|
||||
),
|
||||
twitter: (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="var(--icon-fill-color)"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path
|
||||
d="M22 4s-.7 2.1-2 3.4c1.6 10-9.4 17.3-18 11.6 2.2.1 4.4-.6 6-2C3 15.5.5 9.6 3 5c2.2 2.6 5.6 4.1 9 4-.9-4.2 4-6.6 7-3.8 1.1 0 3-1.2 3-1.2z">
|
||||
</path>
|
||||
</svg>
|
||||
),
|
||||
exportLibrary: (
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
@@ -66,6 +170,22 @@ export const ICONS = {
|
||||
</g>
|
||||
</svg>
|
||||
),
|
||||
//fa-file-pdf
|
||||
insertPDF: (
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
role="img"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 512 512"
|
||||
fill="var(--icon-fill-color)"
|
||||
stroke="none"
|
||||
>
|
||||
<path
|
||||
d="M64 464H96v48H64c-35.3 0-64-28.7-64-64V64C0 28.7 28.7 0 64 0H229.5c17 0 33.3 6.7 45.3 18.7l90.5 90.5c12 12 18.7 28.3 18.7 45.3V288H336V160H256c-17.7 0-32-14.3-32-32V48H64c-8.8 0-16 7.2-16 16V448c0 8.8 7.2 16 16 16zM176 352h32c30.9 0 56 25.1 56 56s-25.1 56-56 56H192v32c0 8.8-7.2 16-16 16s-16-7.2-16-16V448 368c0-8.8 7.2-16 16-16zm32 80c13.3 0 24-10.7 24-24s-10.7-24-24-24H192v48h16zm96-80h32c26.5 0 48 21.5 48 48v64c0 26.5-21.5 48-48 48H304c-8.8 0-16-7.2-16-16V368c0-8.8 7.2-16 16-16zm32 128c8.8 0 16-7.2 16-16V400c0-8.8-7.2-16-16-16H320v96h16zm80-112c0-8.8 7.2-16 16-16h48c8.8 0 16 7.2 16 16s-7.2 16-16 16H448v32h32c8.8 0 16 7.2 16 16s-7.2 16-16 16H448v48c0 8.8-7.2 16-16 16s-16-7.2-16-16V432 368z"
|
||||
/>
|
||||
</svg>
|
||||
),
|
||||
//far fa-image
|
||||
insertImage: (
|
||||
<svg
|
||||
@@ -126,46 +246,6 @@ export const ICONS = {
|
||||
<path d="M326.612 185.391c59.747 59.809 58.927 155.698.36 214.59-.11.12-.24.25-.36.37l-67.2 67.2c-59.27 59.27-155.699 59.262-214.96 0-59.27-59.26-59.27-155.7 0-214.96l37.106-37.106c9.84-9.84 26.786-3.3 27.294 10.606.648 17.722 3.826 35.527 9.69 52.721 1.986 5.822.567 12.262-3.783 16.612l-13.087 13.087c-28.026 28.026-28.905 73.66-1.155 101.96 28.024 28.579 74.086 28.749 102.325.51l67.2-67.19c28.191-28.191 28.073-73.757 0-101.83-3.701-3.694-7.429-6.564-10.341-8.569a16.037 16.037 0 0 1-6.947-12.606c-.396-10.567 3.348-21.456 11.698-29.806l21.054-21.055c5.521-5.521 14.182-6.199 20.584-1.731a152.482 152.482 0 0 1 20.522 17.197zM467.547 44.449c-59.261-59.262-155.69-59.27-214.96 0l-67.2 67.2c-.12.12-.25.25-.36.37-58.566 58.892-59.387 154.781.36 214.59a152.454 152.454 0 0 0 20.521 17.196c6.402 4.468 15.064 3.789 20.584-1.731l21.054-21.055c8.35-8.35 12.094-19.239 11.698-29.806a16.037 16.037 0 0 0-6.947-12.606c-2.912-2.005-6.64-4.875-10.341-8.569-28.073-28.073-28.191-73.639 0-101.83l67.2-67.19c28.239-28.239 74.3-28.069 102.325.51 27.75 28.3 26.872 73.934-1.155 101.96l-13.087 13.087c-4.35 4.35-5.769 10.79-3.783 16.612 5.864 17.194 9.042 34.999 9.69 52.721.509 13.906 17.454 20.446 27.294 10.606l37.106-37.106c59.271-59.259 59.271-155.699.001-214.959z" />
|
||||
</svg>
|
||||
),
|
||||
exportSVG: (
|
||||
<svg
|
||||
viewBox="0 0 28 28"
|
||||
stroke="var(--icon-fill-color)"
|
||||
fill="var(--icon-fill-color)"
|
||||
strokeWidth="1"
|
||||
>
|
||||
<text style={{ fontSize: "28px", fontWeight: "bold" }} x="4" y="24">
|
||||
S
|
||||
</text>
|
||||
</svg>
|
||||
),
|
||||
exportPNG: (
|
||||
<svg
|
||||
viewBox="0 0 28 28"
|
||||
stroke="var(--icon-fill-color)"
|
||||
fill="var(--icon-fill-color)"
|
||||
strokeWidth="1"
|
||||
>
|
||||
<text style={{ fontSize: "28px", fontWeight: "bold" }} x="4" y="24">
|
||||
P
|
||||
</text>
|
||||
</svg>
|
||||
),
|
||||
exportExcalidraw: (
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
focusable="false"
|
||||
role="img"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 100 100"
|
||||
stroke="var(--icon-fill-color)"
|
||||
strokeWidth="2"
|
||||
>
|
||||
<g transform="translate(30,5)">
|
||||
<path d="M14.45 1.715c-2.723 2.148-6.915 5.797-10.223 8.93l-2.61 2.445.477 3.207c.258 1.75.738 5.176 1.031 7.582.332 2.406.66 4.668.773 4.996.145.438 0 .656-.406.656-.699 0-.734-.183 1.176 5.832.7 2.297 1.363 4.414 1.434 4.633.074.254.367.363.699.254.332-.145.515-.438.406-.691-.113-.293.074-.586.367-.696.403-.144.367-.437-.258-1.492-.992-1.64-3.53-15.64-3.675-20.164-.11-3.207-.11-3.242 1.25-5.066 1.324-1.786 4.375-4.485 9.078-7.91 1.324-.985 2.648-2.079 3.015-2.446.551-.656.809-.472 5.442 4.414 2.683 2.805 5.664 5.688 6.617 6.414l1.766 1.313-1.36 2.844c-.734 1.53-3.715 7.437-6.656 13.054-6.137 11.813-4.887 10.68-12.02 10.79l-4.632.038-1.547 1.75c-1.617 1.86-1.836 2.551-1.063 3.72.293.398.512 1.054.512 1.456 0 .656.258.766 1.73.84.918.035 1.762.145 1.875.254.11.11.258 2.371.368 5.031l.144 4.813-2.46 5.25C1.616 72.516 0 76.527 0 77.84c0 .691.148 1.273.293 1.273.367 0 .367-.035 15.332-30.988 6.95-14.363 13.531-27.89 14.633-30.113 1.101-2.227 2.094-4.266 2.168-4.559.074-.328-2.461-2.844-6.508-6.379C22.281 3.864 19.082.95 18.785.621c-.844-1.023-2.094-.695-4.336 1.094zM15.7 43.64c-1.692 3.246-1.766 3.28-6.4 3.5-4.081.218-4.152.183-4.152-.582 0-.438-.148-1.024-.332-1.313-.222-.328-.074-.914.442-1.715l.808-1.238h3.676c2.024-.04 4.34-.184 5.149-.328.808-.149 1.507-.219 1.578-.184.074.035-.293.875-.77 1.86zm-3.09 5.832c-.294.765-1.067 2.37-1.692 3.574-1.027 2.043-1.137 2.113-1.395 1.277-.148-.511-.257-2.008-.296-3.355-.036-2.66-.11-2.625 2.98-2.809l.992-.035zm0 0" />
|
||||
<path d="M15.55 10.39c-.66.473-.843.95-.843 2.153 0 1.422.11 1.64 1.102 2.039.992.402 1.25.367 2.39-.398 1.508-1.024 1.543-1.278.442-2.918-.957-1.422-1.914-1.676-3.09-.875zm2.098 1.313c.586 1.02.22 1.785-.882 1.785-.993 0-1.434-.984-.883-1.968.441-.801 1.285-.727 1.765.183zm0 0M38.602 18.594c0 .183-.22.363-.477.363-.219 0-.844 1.023-1.324 2.262-1.469 3.793-16.176 32.629-16.211 31.718 0-.472-.223-.8-.59-.8-.516 0-.59.289-.367 1.71.219 1.641.074 2.008-5.149 12.071-2.941 5.723-6.101 11.703-7.02 13.305-.956 1.68-1.69 3.5-1.765 4.265-.11 1.313.035 1.496 3.235 4.23 1.84 1.606 4.191 3.61 5.222 4.52 4.63 4.196 6.801 5.871 7.387 5.762.883-.145 14.523-14.328 14.559-15.129 0-.367-.66-5.906-1.47-12.324-1.398-10.938-2.722-23.734-2.573-24.973.109-.765-.442-4.633-.844-6.308-.332-1.313-.184-1.86 2.46-7.84 1.544-3.535 3.567-7.875 4.45-9.625.844-1.75 1.582-3.281 1.582-3.39 0-.11-.258-.18-.55-.18-.298 0-.555.144-.555.363zm-8.454 27.234c.403 2.55 1.211 8.676 1.801 13.598 1.14 9.043 2.461 19.07 2.832 21.62.219 1.278.07 1.532-2.316 4.157-4.156 4.629-8.567 9.188-10.074 10.356l-1.399 1.093-7.168-6.636c-6.617-6.051-7.168-6.672-6.765-7.403.222-.398 2.097-3.789 4.156-7.508 2.058-3.718 4.777-8.68 6.027-11.011 1.29-2.371 2.465-4.41 2.684-4.52.258-.148.332 3.535.258 11.375-.149 11.703-.11 11.739 1.066 11.485.148 0 .258-5.907.258-13.09V56.293l3.86-7.656c2.132-4.23 3.898-7.621 3.972-7.586.07.039.441 2.187.808 4.777zm0 0" />
|
||||
</g>
|
||||
</svg>
|
||||
),
|
||||
//fa-solid fa-magnifying-glass
|
||||
search: (
|
||||
<svg
|
||||
@@ -441,6 +521,84 @@ export const ICONS = {
|
||||
/>
|
||||
</g>
|
||||
</svg>
|
||||
),
|
||||
obsidian: (
|
||||
<svg
|
||||
//aria-hidden="true"
|
||||
focusable="false"
|
||||
role="img"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 512 512"
|
||||
>
|
||||
<defs>
|
||||
<radialGradient id="b" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-48 -185 123 -32 179 429.7)">
|
||||
<stop stopColor="#fff" stopOpacity=".4"/>
|
||||
<stop offset="1" stopOpacity=".1"/>
|
||||
</radialGradient>
|
||||
<radialGradient id="c" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(41 -310 229 30 341.6 351.3)">
|
||||
<stop stopColor="#fff" stopOpacity=".6"/>
|
||||
<stop offset="1" stopColor="#fff" stopOpacity=".1"/>
|
||||
</radialGradient>
|
||||
<radialGradient id="d" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(57 -261 178 39 190.5 296.3)">
|
||||
<stop stopColor="#fff" stopOpacity=".8"/>
|
||||
<stop offset="1" stopColor="#fff" stopOpacity=".4"/>
|
||||
</radialGradient>
|
||||
<radialGradient id="e" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-79 -133 153 -90 321.4 464.2)">
|
||||
<stop stopColor="#fff" stopOpacity=".3"/>
|
||||
<stop offset="1" stopOpacity=".3"/>
|
||||
</radialGradient>
|
||||
<radialGradient id="f" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-29 136 -92 -20 300.7 149.9)">
|
||||
<stop stopColor="#fff" stopOpacity="0"/>
|
||||
<stop offset="1" stopColor="#fff" stopOpacity=".2"/>
|
||||
</radialGradient>
|
||||
<radialGradient id="g" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(72 73 -155 153 137.8 225.2)">
|
||||
<stop stopColor="#fff" stopOpacity=".2"/>
|
||||
<stop offset="1" stopColor="#fff" stopOpacity=".4"/>
|
||||
</radialGradient>
|
||||
<radialGradient id="h" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(20 118 -251 43 215.1 273.7)">
|
||||
<stop stopColor="#fff" stopOpacity=".1"/>
|
||||
<stop offset="1" stopColor="#fff" stopOpacity=".3"/>
|
||||
</radialGradient>
|
||||
<radialGradient id="i" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="matrix(-162 -85 268 -510 374.4 371.7)">
|
||||
<stop stopColor="#fff" stopOpacity=".2"/>
|
||||
<stop offset=".5" stopColor="#fff" stopOpacity=".2"/>
|
||||
<stop offset="1" stopColor="#fff" stopOpacity=".3"/>
|
||||
</radialGradient>
|
||||
<filter id="a" x="80.1" y="37" width="351.1" height="443.2" filterUnits="userSpaceOnUse" colorInterpolationFilters="sRGB">
|
||||
<feFlood floodOpacity="0" result="BackgroundImageFix"/>
|
||||
<feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/>
|
||||
<feGaussianBlur stdDeviation="6.5" result="effect1_foregroundBlur_744_9191"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<g filter="url(#a)">
|
||||
<path d="M359.2 437.5c-2.6 19-21.3 33.9-40 28.7-26.5-7.2-57.2-18.6-84.8-20.7l-42.4-3.2a28 28 0 0 1-18-8.3l-73-74.8a27.7 27.7 0 0 1-5.4-30.7s45-98.6 46.8-103.7c1.6-5.1 7.8-49.9 11.4-73.9a28 28 0 0 1 9-16.5L249 57.2a28 28 0 0 1 40.6 3.4l72.6 91.6a29.5 29.5 0 0 1 6.2 18.3c0 17.3 1.5 53 11.2 76a301.3 301.3 0 0 0 35.6 58.2 14 14 0 0 1 1 15.6c-6.3 10.7-18.9 31.3-36.6 57.6a142.2 142.2 0 0 0-20.5 59.6Z" fill="#000" fillOpacity=".3"/>
|
||||
</g>
|
||||
<path id="arrow" d="M359.9 434.3c-2.6 19.1-21.3 34-40 28.9-26.4-7.3-57-18.7-84.7-20.8l-42.3-3.2a27.9 27.9 0 0 1-18-8.4l-73-75a27.9 27.9 0 0 1-5.4-31s45.1-99 46.8-104.2c1.7-5.1 7.8-50 11.4-74.2a28 28 0 0 1 9-16.6l86.2-77.5a28 28 0 0 1 40.6 3.5l72.5 92a29.7 29.7 0 0 1 6.2 18.3c0 17.4 1.5 53.2 11.1 76.3a303 303 0 0 0 35.6 58.5 14 14 0 0 1 1.1 15.7c-6.4 10.8-18.9 31.4-36.7 57.9a143.3 143.3 0 0 0-20.4 59.8Z" fill="#6c31e3"/>
|
||||
<path d="M182.7 436.4c33.9-68.7 33-118 18.5-153-13.2-32.4-37.9-52.8-57.3-65.5-.4 1.9-1 3.7-1.8 5.4L96.5 324.8a27.9 27.9 0 0 0 5.5 31l72.9 75c2.3 2.3 5 4.2 7.8 5.6Z" fill="url(#b)"/>
|
||||
<path d="M274.9 297c9.1.9 18 2.9 26.8 6.1 27.8 10.4 53.1 33.8 74 78.9 1.5-2.6 3-5.1 4.6-7.5a1222 1222 0 0 0 36.7-57.9 14 14 0 0 0-1-15.7 303 303 0 0 1-35.7-58.5c-9.6-23-11-58.9-11.1-76.3 0-6.6-2.1-13.1-6.2-18.3l-72.5-92-1.2-1.5c5.3 17.5 5 31.5 1.7 44.2-3 11.8-8.6 22.5-14.5 33.8-2 3.8-4 7.7-5.9 11.7a140 140 0 0 0-15.8 58c-1 24.2 3.9 54.5 20 95Z" fill="url(#c)"/>
|
||||
<path d="M274.8 297c-16.1-40.5-21-70.8-20-95 1-24 8-42 15.8-58l6-11.7c5.8-11.3 11.3-22 14.4-33.8a78.5 78.5 0 0 0-1.7-44.2 28 28 0 0 0-39.4-2l-86.2 77.5a28 28 0 0 0-9 16.6L144.2 216c0 .7-.2 1.3-.3 2 19.4 12.6 44 33 57.3 65.3 2.6 6.4 4.8 13.1 6.4 20.4a200 200 0 0 1 67.2-6.8Z" fill="url(#d)"/>
|
||||
<path d="M320 463.2c18.6 5.1 37.3-9.8 39.9-29a153 153 0 0 1 15.9-52.2c-21-45.1-46.3-68.5-74-78.9-29.5-11-61.6-7.3-94.2.6 7.3 33.1 3 76.4-24.8 132.7 3.1 1.6 6.6 2.5 10.1 2.8l43.9 3.3c23.8 1.7 59.3 14 83.2 20.7Z" fill="url(#e)"/>
|
||||
<path fillRule="evenodd" clipRule="evenodd" d="M255 200.5c-1.1 24 1.9 51.4 18 91.8l-5-.5c-14.5-42.1-17.7-63.7-16.6-88 1-24.3 8.9-43 16.7-59 2-4 6.6-11.5 8.6-15.3 5.8-11.3 9.7-17.2 13-27.5 4.8-14.4 3.8-21.2 3.2-28 3.7 24.5-10.4 45.8-21 67.5a145 145 0 0 0-17 59Z" fill="url(#f)"/>
|
||||
<path fillRule="evenodd" clipRule="evenodd" d="M206 285.1c2 4.4 3.7 8 4.9 13.5l-4.3 1c-1.7-6.4-3-11-5.5-16.5-14.6-34.3-38-52-57-65 23 12.4 46.7 31.9 61.9 67Z" fill="url(#g)"/>
|
||||
<path fillRule="evenodd" clipRule="evenodd" d="M211.1 303c8 37.5-1 85.2-27.5 131.6 22.2-46 33-90.1 24-131l3.5-.7Z" fill="url(#h)"/>
|
||||
<path fillRule="evenodd" clipRule="evenodd" d="M302.7 299.5c43.5 16.3 60.3 52 72.8 81.9-15.5-31.2-37-65.7-74.4-78.5-28.4-9.8-52.4-8.6-93.5.7l-.9-4c43.6-10 66.4-11.2 96 0Z" fill="url(#i)"/>
|
||||
</svg>
|
||||
),
|
||||
"add-file": (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="var(--icon-fill-color)"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/>
|
||||
<polyline points="14 2 14 8 20 8"/>
|
||||
<line x1="12" x2="12" y1="18" y2="12"/>
|
||||
<line x1="9" x2="15" y1="15" y2="15"/>
|
||||
</svg>
|
||||
)
|
||||
};
|
||||
|
||||
@@ -462,6 +620,109 @@ export const saveIcon = (isDirty: boolean) => {
|
||||
)
|
||||
}
|
||||
|
||||
export const penIcon = (pen: PenStyle) => {
|
||||
switch(pen.type) {
|
||||
case "highlighter":
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="var(--icon-fill-color)"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path fill={pen.strokeColor??"var(--icon-fill-color)"} strokeWidth="2" d="m9 11-6 6v3h9l3-3"></path>
|
||||
<path fill="none" strokeWidth="2" d="m22 12-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4"></path>
|
||||
</svg>
|
||||
)
|
||||
case "finetip":
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill={pen.strokeColor??"var(--icon-fill-color)"}
|
||||
stroke={pen.strokeColor??"var(--icon-fill-color)"}
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path strokeWidth="2" d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"></path>
|
||||
</svg>
|
||||
)
|
||||
case "fountain":
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="var(--icon-fill-color)"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path fill={pen.strokeColor??"var(--icon-fill-color)"} d="m12 19 7-7 3 3-7 7-3-3z"></path>
|
||||
<path fill="none" d="m18 13-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"></path>
|
||||
<path fill="none" d="m2 2 7.586 7.586"></path>
|
||||
<circle fill="none" cx="11" cy="11" r="2"></circle>
|
||||
</svg>
|
||||
)
|
||||
case "marker":
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 576 512"
|
||||
fill={pen.strokeColor??"var(--icon-fill-color)"}
|
||||
stroke={pen.strokeColor??"var(--icon-fill-color)"}
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M331 315l158.4-215L460.1 70.6 245 229 331 315zm-187 5l0 0V248.3c0-15.3 7.2-29.6 19.5-38.6L436.6 8.4C444 2.9 453 0 462.2 0c11.4 0 22.4 4.5 30.5 12.6l54.8 54.8c8.1 8.1 12.6 19 12.6 30.5c0 9.2-2.9 18.2-8.4 25.6L350.4 396.5c-9 12.3-23.4 19.5-38.6 19.5H240l-25.4 25.4c-12.5 12.5-32.8 12.5-45.3 0l-50.7-50.7c-12.5-12.5-12.5-32.8 0-45.3L144 320zM23 466.3l63-63 70.6 70.6-31 31c-4.5 4.5-10.6 7-17 7H40c-13.3 0-24-10.7-24-24v-4.7c0-6.4 2.5-12.5 7-17z"/>
|
||||
</svg>
|
||||
)
|
||||
case "thick-thin":
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 108 106"
|
||||
strokeWidth="2"
|
||||
fill={pen.strokeColor??"var(--icon-fill-color)"}
|
||||
stroke={pen.strokeColor??"var(--icon-fill-color)"}
|
||||
>
|
||||
<path d="m-.58 95.628.22-.89q.22-.89.49-2.44.26-1.54.77-3.35t1.31-3.43q.79-1.61.2-.26-.6 1.34-.03-.14.58-1.49 1.54-2.97.96-1.49 2.54-3.18 1.59-1.68 3.46-2.96 1.86-1.27.81-.54-1.04.73.6-.46 1.64-1.19 2.8-1.81 1.16-.63.16-.08-.99.54 1.21-.5 2.2-1.03 1.11-.58-1.1.45-.03-.07 1.06-.53 2.32-.82 1.26-.3 2.91-.52 1.64-.23 3.05-.18 1.4.05 2.5.12 1.09.07 2.25.24 1.16.17 2.3.49 1.15.32 2.11.78.96.47 2.21 1.01 1.25.55 2.37 1.04t2.34.89q1.22.4 2.5.65 1.29.25 2.44.33 1.16.08 2.35.17 1.18.08 2.26-.1 1.08-.19 2-1.1.92-.91 1.25-1.93.32-1.02.38-2.15t.57.21q.51 1.34-.03-.02-.55-1.37-.96-2.83-.41-1.45.5-.67.92.79-.03-.06-.95-.85-1.52-1.8-.57-.94-1.5-1.52-.93-.57-1.94-1.22-1.01-.65-1.97-1.88-.96-1.22-1.44-2.54-.49-1.32-.65-2.57-.17-1.24-.11-2.35.06-1.11.31-2.91.24-1.79.76-2.77.51-.97 1.29-1.8.77-.84 1.64-1.55.88-.72 1.9-1.33 1.03-.61 2.43-1.15 1.41-.55 2.69-.92 1.29-.37 2.81-.68 1.53-.31 2.83-.58 1.31-.27 2.78-.47 1.47-.2 2.58-.49 1.12-.28 2.19-.58 1.08-.31 2.13-.73 1.05-.42 2.44-1.32 1.39-.9 2.68-1.85 1.3-.95 2.25-1.87.95-.91 2.06-2 1.11-1.09 1.92-1.93.82-.84 1.54-1.82.71-.98 1.4-1.88.69-.9 1.38-1.96.69-1.07 1.25-2.04.55-.97 1.21-1.94.65-.96 1.35-1.79.69-.83 1.46-1.74.77-.9 1.66-1.73.89-.84 2.72-2.31 1.84-1.48 1.84-1.47v.01l-1.1 1.03q-1.1 1.02-1.77 1.92-.68.9-1.39 1.85-.71.96-1.41 1.91-.7.96-1.19 1.92-.48.95-.95 1.92-.46.96-.9 1.95-.43.99-1.02 2.16-.59 1.17-1.17 2.15-.58.97-1.23 2.13t-1.29 2.02q-.64.86-1.3 1.73-.66.88-1.42 1.78-.75.9-1.72 2.03-.97 1.14-1.81 1.89-.85.75-1.98 1.71-1.14.96-2.05 1.61-.91.64-2.42 1.38-1.51.73-2.71 1.21t-2.49.92q-1.3.44-2.35.69-1.06.24-2.1.59-1.03.34-2.06.74-1.03.4-2.29.94-1.26.54-2.27 1.11-1.01.58-1.57 1.57-.56.99-.81 2.06-.25 1.08.56 2.02.8.94-.21-.02-1.02-.96-.01-.48 1 .49 1.87 1.25.87.77 0 0-.88-.77.46-.01 1.34.75 2.6 1.68 1.26.94 2.08 2.03.81 1.09.01.27-.8-.82.3.26 1.11 1.08 1.71 2.1.61 1.02 1.21 2.25.6 1.24.92 2.36.32 1.12-.16.13-.49-.98.02.36.51 1.35.71 2.69.2 1.34.24 2.46.03 1.12-.09 2.42-.13 1.29-.72 3.21-.6 1.92-1.4 3.49-.81 1.58-1.77 2.83-.96 1.24-2.88 2.72-1.92 1.48-2.95 1.85-1.04.36-2.47.76-1.44.41-3.33.72-1.89.32-3.37.41-1.48.09-2.63.15-1.15.05-2.74-.06-1.59-.1-2.8-.29-1.2-.19-3.2-.63-1.99-.45-3.63-.92-1.63-.48-3.28-.79-1.65-.31-2.76-.2-1.11.1-2.21.42-1.11.32.39-.29 1.49-.6-.12.21-1.61.8-.39.19 1.21-.61.29.13-.92.74-1.83 1.34-.92.61.15-.19t.3-.05q-.77.75-1.58 1.57-.81.82.01-.18.82-1 .24.23t-.72 2.72q-.15 1.48-.08 2.4.07.91-.19 2.16-.26 1.26-.81 2.41-.55 1.16-1.36 2.15t-1.84 1.75q-1.03.77-2.21 1.27t-2.44.7q-1.27.2-2.53.1-1.28-.11-2.49-.52-1.22-.41-2.3-1.1-1.08-.68-1.96-1.61-.89-.92-1.52-2.04-.64-1.11-.99-2.34-.36-1.23-.41-2.51l-.04-1.27Z"/>
|
||||
</svg>
|
||||
)
|
||||
case "thin-thick-thin":
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 114 113"
|
||||
strokeWidth="2"
|
||||
fill={pen.strokeColor??"var(--icon-fill-color)"}
|
||||
stroke={pen.strokeColor??"var(--icon-fill-color)"}
|
||||
>
|
||||
<path d="m10 103.405.13-1.22q.14-1.22 1.3-3.16 1.15-1.94 2.74-3.46 1.59-1.53 3.35-2.72 1.77-1.2 4-1.95 2.23-.76 4.45-1t4.86-.4q2.64-.15 5.14-.34 2.51-.19 4.85-.94 2.35-.75 4.55-1.71 2.21-.97 4.16-2.26 1.95-1.3 4.03-2.97 2.07-1.67 3.85-3.05 1.78-1.37 3.72-2.48 1.94-1.11 3.3-2.99 1.36-1.89 2.58-3.74 1.22-1.85-.63-3.42-1.85-1.57-3.82-2.86-1.97-1.3-4.11-2.08-2.15-.78-4.21-1.6-2.06-.81-4.02-1.96-1.96-1.14-3.71-2.48-1.74-1.33-3.37-2.77-1.63-1.43-3.23-3.62-1.6-2.18-2.23-4.64-.62-2.46-.36-4.96.27-2.49 1.19-4.46.91-1.97 2.42-3.7 1.5-1.73 3.5-3.15t4.11-2.28q2.1-.86 4.33-1.44 2.24-.58 4.92-.84 2.68-.26 4.83-.19t4.69.35q2.53.28 4.75.66 2.23.38 4.48.2 2.26-.19 4.43-1.3 2.17-1.12 4.2-2.36 2.04-1.24 3.93-2.43 1.9-1.19 3.84-2.14 1.95-.95 4.04-1.78 2.09-.83 4.56-2.28 2.46-1.46 2.46-1.45h.01q.01 0-1.38 1.3-1.38 1.29-3.08 2.59-1.7 1.3-3.5 2.5t-3.42 2.65q-1.62 1.45-3.18 3-1.57 1.56-3.37 3.13-1.8 1.57-3.6 2.91-1.81 1.33-3.92 2.12t-4.24.92q-2.13.14-4.31.26-2.18.12-4.5.39t-4.56.88q-2.25.61-4.24 1.6-1.99 1-3.83 2.29-1.83 1.29.18 2.44 2.01 1.15 4.2 1.92 2.2.78 4.34 1 2.15.22 4.4.69 2.25.46 4.34 1.16 2.08.71 4.33 1.91 2.25 1.21 4.11 2.73 1.87 1.52 3.68 4.03 1.82 2.5 2.74 5 .93 2.5 1.18 5.03.26 2.53-.04 4.81t-1.4 4.85q-1.09 2.58-2.4 4.26-1.3 1.68-3.1 3.44t-4.02 3.62q-2.23 1.85-4.32 3.07-2.08 1.23-4.34 1.99-2.25.76-4.46 1.96t-4.37 2.14q-2.15.93-4.22 1.81t-4.36 1.35q-2.3.46-4.52.82-2.22.35-4.76.38-2.54.04-4.87-.28t-4.67-.67q-2.34-.35-4.72-.54-2.39-.19-4.64.37-2.25.56-4.16 1.66-1.91 1.11-3.52 2.71-1.61 1.6-2.55 2.39l-.94.78Z"/>
|
||||
</svg>
|
||||
)
|
||||
default:
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 512 512"
|
||||
fill={pen.strokeColor??"var(--icon-fill-color)"}
|
||||
stroke={pen.strokeColor??"var(--icon-fill-color)"}
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<path d="M453.3 19.3l39.4 39.4c25 25 25 65.5 0 90.5l-52.1 52.1 0 0-1-1 0 0-16-16-96-96-17-17 52.1-52.1c25-25 65.5-25 90.5 0zM241 114.9c-9.4-9.4-24.6-9.4-33.9 0L105 217c-9.4 9.4-24.6 9.4-33.9 0s-9.4-24.6 0-33.9L173.1 81c28.1-28.1 73.7-28.1 101.8 0L288 94.1l17 17 96 96 16 16 1 1-17 17L229.5 412.5c-48 48-109.2 80.8-175.8 94.1l-25 5c-7.9 1.6-16-.9-21.7-6.6s-8.1-13.8-6.6-21.7l5-25c13.3-66.6 46.1-127.8 94.1-175.8L254.1 128 241 114.9z"/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export const stringToSVG = (svg: string) => {
|
||||
svg = svg
|
||||
.replace(/stroke\s*=\s*['"][^"']*['"]/g,"")
|
||||
|
||||
@@ -1,125 +1,280 @@
|
||||
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";
|
||||
import { UniversalInsertFileModal } from "src/dialogs/UniversalInsertFileModal";
|
||||
|
||||
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>
|
||||
<label
|
||||
className={clsx(
|
||||
"ToolIcon",
|
||||
"ToolIcon_size_medium",
|
||||
{
|
||||
"is-mobile": isMobile,
|
||||
},
|
||||
)}
|
||||
onClick={() => {
|
||||
const insertFileModal = new UniversalInsertFileModal(this.plugin, this.view);
|
||||
insertFileModal.open();
|
||||
}}
|
||||
>
|
||||
<div className="ToolIcon__icon" aria-hidden="true">
|
||||
{ICONS["add-file"]}
|
||||
</div>
|
||||
</label>
|
||||
{this.renderCustomPens(isMobile,appState)}
|
||||
{this.renderPinnedScriptButtons(isMobile,appState)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Notice, TFile } from "obsidian";
|
||||
import * as React from "react";
|
||||
import { ActionButton } from "./ActionButton";
|
||||
import { ICONS, saveIcon, stringToSVG } from "./ActionIcons";
|
||||
import { SCRIPT_INSTALL_FOLDER, CTRL_OR_CMD } from "../Constants";
|
||||
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";
|
||||
@@ -11,6 +11,10 @@ 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";
|
||||
import { ExportDialog } from "src/dialogs/ExportDialog";
|
||||
|
||||
declare const PLUGIN_VERSION:string;
|
||||
const dark = '<svg style="stroke:#ced4da;#212529;color:#ced4da;fill:#ced4da" ';
|
||||
@@ -48,7 +52,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);
|
||||
@@ -376,7 +380,7 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
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, e[CTRL_OR_CMD]);
|
||||
this.props.view.plugin.taskbone.getTextForView(this.props.view, isCTRL(e));
|
||||
}}
|
||||
icon={ICONS.ocr}
|
||||
view={this.props.view}
|
||||
@@ -384,14 +388,14 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
<ActionButton
|
||||
key={"openLink"}
|
||||
title={t("OPEN_LINK_CLICK")}
|
||||
action={() => {
|
||||
action={(e) => {
|
||||
const event = new MouseEvent("click", {
|
||||
ctrlKey: true,
|
||||
metaKey: false,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
ctrlKey: e.ctrlKey || !(DEVICE.isIOS || DEVICE.isMacOS),
|
||||
metaKey: e.metaKey || (DEVICE.isIOS || DEVICE.isMacOS),
|
||||
shiftKey: e.shiftKey,
|
||||
altKey: e.altKey,
|
||||
});
|
||||
this.props.view.handleLinkClick(this.props.view, event);
|
||||
this.props.view.handleLinkClick(event);
|
||||
}}
|
||||
icon={ICONS.openLink}
|
||||
view={this.props.view}
|
||||
@@ -402,11 +406,11 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
action={() => {
|
||||
const event = new MouseEvent("click", {
|
||||
ctrlKey: true,
|
||||
metaKey: false,
|
||||
shiftKey: true,
|
||||
altKey: true,
|
||||
metaKey: true,
|
||||
shiftKey: false,
|
||||
altKey: false,
|
||||
});
|
||||
this.props.view.handleLinkClick(this.props.view, event);
|
||||
this.props.view.handleLinkClick(event);
|
||||
}}
|
||||
icon={ICONS.openLinkProperties}
|
||||
view={this.props.view}
|
||||
@@ -435,42 +439,17 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
view={this.props.view}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"svg"}
|
||||
title={t("EXPORT_SVG")}
|
||||
key={"exportIMG"}
|
||||
title={t("EXPORT_IMAGE")}
|
||||
action={() => {
|
||||
this.props.view.saveSVG();
|
||||
new Notice(
|
||||
`File saved: ${getIMGFilename(
|
||||
this.props.view.file.path,
|
||||
"svg",
|
||||
)}`,
|
||||
);
|
||||
const view = this.props.view;
|
||||
if(!view.exportDialog) {
|
||||
view.exportDialog = new ExportDialog(view.plugin, view,view.file);
|
||||
view.exportDialog.createForm();
|
||||
}
|
||||
view.exportDialog.open();
|
||||
}}
|
||||
icon={ICONS.exportSVG}
|
||||
view={this.props.view}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"png"}
|
||||
title={t("EXPORT_PNG")}
|
||||
action={() => {
|
||||
this.props.view.savePNG();
|
||||
new Notice(
|
||||
`File saved: ${getIMGFilename(
|
||||
this.props.view.file.path,
|
||||
"png",
|
||||
)}`,
|
||||
);
|
||||
}}
|
||||
icon={ICONS.exportPNG}
|
||||
view={this.props.view}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"excalidraw"}
|
||||
title={t("EXPORT_EXCALIDRAW")}
|
||||
action={() => {
|
||||
this.props.view.exportExcalidraw();
|
||||
}}
|
||||
icon={ICONS.exportExcalidraw}
|
||||
icon={ICONS.ExportImage}
|
||||
view={this.props.view}
|
||||
/>
|
||||
<ActionButton
|
||||
@@ -499,6 +478,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")}
|
||||
@@ -514,7 +504,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);
|
||||
}}
|
||||
@@ -538,8 +532,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}
|
||||
@@ -584,47 +582,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, index) => (
|
||||
<fieldset key={`${group}-${index}`}>
|
||||
<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>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ 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";
|
||||
@@ -105,7 +106,7 @@ export default class Taskbone {
|
||||
if(this.apiKey === "") {
|
||||
await this.initialize();
|
||||
}
|
||||
const base64Image = await this.blobToBase64(image);
|
||||
const base64Image = await blobToBase64(image);
|
||||
const input = {
|
||||
records: [{
|
||||
image: base64Image
|
||||
@@ -132,16 +133,5 @@ export default class Taskbone {
|
||||
return content.records[0].text;
|
||||
}
|
||||
|
||||
|
||||
private async blobToBase64(blob: Blob): Promise<string> {
|
||||
const arrayBuffer = await blob.arrayBuffer()
|
||||
const bytes = new Uint8Array(arrayBuffer)
|
||||
var binary = '';
|
||||
var len = bytes.byteLength;
|
||||
for (var i = 0; i < len; i++) {
|
||||
binary += String.fromCharCode(bytes[i]);
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
268
src/settings.ts
@@ -7,18 +7,24 @@ 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,
|
||||
} from "./utils/Utils";
|
||||
import { image } from "html2canvas/dist/types/css/types/image";
|
||||
import { imageCache } from "./utils/ImageCache";
|
||||
|
||||
export interface ExcalidrawSettings {
|
||||
folder: string;
|
||||
@@ -36,15 +42,20 @@ export interface ExcalidrawSettings {
|
||||
drawingFilenameDateTime: string;
|
||||
useExcalidrawExtension: boolean;
|
||||
displaySVGInPreview: boolean;
|
||||
allowImageCache: boolean;
|
||||
displayExportedImageIfAvailable: boolean;
|
||||
previewMatchObsidianTheme: boolean;
|
||||
width: string;
|
||||
dynamicStyling: DynamicStyle;
|
||||
isLeftHanded: boolean;
|
||||
iframeMatchExcalidrawTheme: boolean;
|
||||
matchTheme: boolean;
|
||||
matchThemeAlways: boolean;
|
||||
matchThemeTrigger: boolean;
|
||||
defaultMode: string;
|
||||
defaultPenMode: "never" | "mobile" | "always";
|
||||
allowPinchZoom: boolean;
|
||||
allowWheelZoom: boolean;
|
||||
zoomToFitOnOpen: boolean;
|
||||
zoomToFitOnResize: boolean;
|
||||
zoomToFitMaxLevel: number;
|
||||
@@ -113,10 +124,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,
|
||||
@@ -133,15 +156,20 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
drawingFilenameDateTime: "YYYY-MM-DD HH.mm.ss",
|
||||
useExcalidrawExtension: true,
|
||||
displaySVGInPreview: true,
|
||||
allowImageCache: true,
|
||||
displayExportedImageIfAvailable: false,
|
||||
previewMatchObsidianTheme: false,
|
||||
width: "400",
|
||||
dynamicStyling: "colorful",
|
||||
isLeftHanded: false,
|
||||
iframeMatchExcalidrawTheme: true,
|
||||
matchTheme: false,
|
||||
matchThemeAlways: false,
|
||||
matchThemeTrigger: false,
|
||||
defaultMode: "normal",
|
||||
defaultPenMode: "never",
|
||||
allowPinchZoom: false,
|
||||
allowWheelZoom: false,
|
||||
zoomToFitOnOpen: true,
|
||||
zoomToFitOnResize: true,
|
||||
zoomToFitMaxLevel: 2,
|
||||
@@ -186,7 +214,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
library2: {
|
||||
type: "excalidrawlib",
|
||||
version: 2,
|
||||
source: "https://excalidraw.com",
|
||||
source: GITHUB_RELEASES+PLUGIN_VERSION,
|
||||
libraryItems: [],
|
||||
},
|
||||
//patchCommentBlock: true,
|
||||
@@ -200,19 +228,42 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
mdBorderColor: "Black",
|
||||
mdCSS: "",
|
||||
scriptEngineSettings: {},
|
||||
defaultTrayMode: false,
|
||||
defaultTrayMode: true,
|
||||
previousRelease: "0.0.0",
|
||||
showReleaseNotes: true,
|
||||
showNewVersionNotification: true,
|
||||
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;
|
||||
|
||||
@@ -238,6 +289,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);
|
||||
@@ -264,6 +328,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");
|
||||
@@ -508,6 +573,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")))
|
||||
@@ -524,6 +605,19 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(t("IFRAME_MATCH_THEME_NAME"))
|
||||
.setDesc(fragWithHTML(t("IFRAME_MATCH_THEME_DESC")))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(this.plugin.settings.iframeMatchExcalidrawTheme)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.iframeMatchExcalidrawTheme = value;
|
||||
this.applySettingsUpdate(true);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(t("MATCH_THEME_NAME"))
|
||||
.setDesc(fragWithHTML(t("MATCH_THEME_DESC")))
|
||||
@@ -565,9 +659,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;
|
||||
@@ -590,6 +685,36 @@ 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")))
|
||||
@@ -1014,6 +1139,25 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
|
||||
this.containerEl.createEl("h1", { text: t("EMBED_HEAD") });
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(t("EMBED_IMAGE_CACHE_NAME"))
|
||||
.setDesc(fragWithHTML(t("EMBED_IMAGE_CACHE_DESC")))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(this.plugin.settings.allowImageCache)
|
||||
.onChange((value) => {
|
||||
this.plugin.settings.allowImageCache = value;
|
||||
this.applySettingsUpdate();
|
||||
})
|
||||
)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("EMBED_IMAGE_CACHE_CLEAR"))
|
||||
.onClick(() => {
|
||||
imageCache.clear();
|
||||
})
|
||||
);
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(t("EMBED_PREVIEW_SVG_NAME"))
|
||||
.setDesc(fragWithHTML(t("EMBED_PREVIEW_SVG_DESC")))
|
||||
@@ -1290,6 +1434,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)
|
||||
@@ -1307,10 +1515,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"))
|
||||
@@ -1362,40 +1578,6 @@ 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();
|
||||
}),
|
||||
);
|
||||
|
||||
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("h2", { text: t("TASKBONE_HEAD") });
|
||||
this.containerEl.createEl("p", { text: t("TASKBONE_DESC") });
|
||||
let taskboneAPIKeyText: TextComponent;
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 = []) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ExcalidrawElement, ExcalidrawLinearElement, ExcalidrawTextElement, FillStyle, GroupId, StrokeSharpness, StrokeStyle } from "@zsviczian/excalidraw/types/element/types";
|
||||
import { ExcalidrawElement, ExcalidrawLinearElement, ExcalidrawTextElement, FillStyle, GroupId, RoundnessType, StrokeStyle } from "@zsviczian/excalidraw/types/element/types";
|
||||
|
||||
export type PathCommand = {
|
||||
type: string;
|
||||
@@ -53,7 +53,7 @@ type _ExcalidrawElementBase = Readonly<{
|
||||
fillStyle: FillStyle;
|
||||
strokeWidth: number;
|
||||
strokeStyle: StrokeStyle;
|
||||
strokeSharpness: StrokeSharpness;
|
||||
roundness: null | { type: RoundnessType; value?: number };
|
||||
roughness: number;
|
||||
opacity: number;
|
||||
width: number;
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
import { getTransformMatrix, transformPoints } from "./transform";
|
||||
import { pointsOnPath } from "points-on-path";
|
||||
import { randomId, getWindingOrder } from "./utils";
|
||||
import { ROUNDNESS } from "../Constants";
|
||||
|
||||
const SUPPORTED_TAGS = [
|
||||
"svg",
|
||||
@@ -352,7 +353,7 @@ const walkers = {
|
||||
y: result[13],
|
||||
width: result[0],
|
||||
height: result[5],
|
||||
strokeSharpness: isRound ? "round" : "sharp",
|
||||
roundness: isRound ? {type:ROUNDNESS.LEGACY} : null,
|
||||
};
|
||||
|
||||
scene.elements.push(rect);
|
||||
|
||||
9
src/types.d.ts
vendored
@@ -1,4 +1,4 @@
|
||||
import { ExcalidrawBindableElement, ExcalidrawElement, ExcalidrawImageElement, FileId, FillStyle, NonDeletedExcalidrawElement, StrokeSharpness, StrokeStyle } from "@zsviczian/excalidraw/types/element/types";
|
||||
import { ExcalidrawBindableElement, ExcalidrawElement, ExcalidrawImageElement, FileId, FillStyle, NonDeletedExcalidrawElement, RoundnessType, StrokeRoundness, StrokeStyle } from "@zsviczian/excalidraw/types/element/types";
|
||||
import { Point } from "@zsviczian/excalidraw/types/types";
|
||||
import { TFile, WorkspaceLeaf } from "obsidian";
|
||||
import { EmbeddedFilesLoader } from "./EmbeddedFileLoader";
|
||||
@@ -15,6 +15,10 @@ export type Packages = {
|
||||
excalidrawLib: any,
|
||||
}
|
||||
|
||||
export type ValueOf<T> = T[keyof T];
|
||||
|
||||
export type DynamicStyle = "none" | "gray" | "colorful";
|
||||
|
||||
export interface ExcalidrawAutomateInterface {
|
||||
plugin: ExcalidrawPlugin;
|
||||
elementsDict: {[key:string]:any}; //contains the ExcalidrawElements currently edited in Automate indexed by el.id
|
||||
@@ -28,7 +32,8 @@ export interface 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"
|
||||
|
||||
110
src/utils/DynamicStyling.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import { ColorMaster } from "colormaster";
|
||||
import { ExcalidrawAutomate } from "src/ExcalidrawAutomate";
|
||||
import ExcalidrawView from "src/ExcalidrawView";
|
||||
import { DynamicStyle } from "src/types";
|
||||
|
||||
export const setDynamicStyle = (
|
||||
ea: ExcalidrawAutomate,
|
||||
view: ExcalidrawView, //the excalidraw view
|
||||
color: string,
|
||||
dynamicStyle: DynamicStyle,
|
||||
) => {
|
||||
if(dynamicStyle === "none") {
|
||||
view.excalidrawContainer?.removeAttribute("style");
|
||||
setTimeout(()=>view.updateScene({appState:{dynamicStyle: ""}}));
|
||||
const toolspanel = view.toolsPanelRef?.current?.containerRef?.current;
|
||||
if(toolspanel) {
|
||||
let toolsStyle = toolspanel.getAttribute("style");
|
||||
toolsStyle = toolsStyle.replace(/\-\-color\-primary.*/,"");
|
||||
toolspanel.setAttribute("style",toolsStyle);
|
||||
}
|
||||
|
||||
|
||||
return;
|
||||
}
|
||||
const doc = view.ownerDocument;
|
||||
const isLightTheme =
|
||||
view?.excalidrawAPI?.getAppState?.()?.theme === "light" ||
|
||||
view?.excalidrawData?.scene?.appState?.theme === "light";
|
||||
|
||||
const darker = "#101010";
|
||||
const lighter = "#f0f0f0";
|
||||
const step = 10;
|
||||
const mixRatio = 0.8;
|
||||
|
||||
const invertColor = (c:string) => {
|
||||
const cm = ea.getCM(c);
|
||||
const lightness = cm.lightness;
|
||||
return cm.lightnessTo(Math.abs(lightness-100));
|
||||
}
|
||||
|
||||
const cmBG = () => isLightTheme
|
||||
? ea.getCM(color)
|
||||
: invertColor(color);
|
||||
|
||||
const bgLightness = cmBG().lightness;
|
||||
const isDark = cmBG().isDark();
|
||||
|
||||
//@ts-ignore
|
||||
const accentColorString = app.getAccentColor();
|
||||
const accent = () => ea.getCM(accentColorString);
|
||||
|
||||
const cmBlack = () => ea.getCM("#000000").lightnessTo(bgLightness);
|
||||
|
||||
const isGray = dynamicStyle === "gray";
|
||||
const gray1 = isGray
|
||||
? isDark ? cmBlack().lighterBy(15) : cmBlack().darkerBy(15)
|
||||
: isDark ? cmBG().lighterBy(15).mix({color:cmBlack(),ratio:0.6}) : cmBG().darkerBy(15).mix({color:cmBlack(),ratio:0.6});
|
||||
const gray2 = isGray
|
||||
? isDark ? cmBlack().lighterBy(5) : cmBlack().darkerBy(5)
|
||||
: isDark ? cmBG().lighterBy(5).mix({color:cmBlack(),ratio:0.6}) : cmBG().darkerBy(5).mix({color:cmBlack(),ratio:0.6});
|
||||
const text = cmBG().mix({color:isDark?lighter:darker, ratio:mixRatio});
|
||||
|
||||
const str = (cm: ColorMaster) => cm.stringHEX({alpha:false});
|
||||
const style = `--color-primary: ${str(accent())};` +
|
||||
`--color-primary-darker: ${str(accent().darkerBy(step))};` +
|
||||
`--color-primary-darkest: ${str(accent().darkerBy(step))};` +
|
||||
`--button-gray-1: ${str(gray1)};` +
|
||||
`--button-gray-2: ${str(gray2)};` +
|
||||
`--input-border-color: ${str(gray1)};` +
|
||||
`--input-bg-color: ${str(gray2)};` +
|
||||
`--input-label-color: ${str(text)};` +
|
||||
`--island-bg-color: ${gray2.alphaTo(0.93).stringHEX()};` +
|
||||
`--popup-secondary-bg-color: ${gray2.alphaTo(0.93).stringHEX()};` +
|
||||
`--icon-fill-color: ${str(text)};` +
|
||||
`--text-primary-color: ${str(text)};` +
|
||||
`--overlay-bg-color: ${gray2.alphaTo(0.6).stringHEX()};` +
|
||||
`--popup-bg-color: ${str(gray1)};` +
|
||||
`--color-gray-100: ${str(text)};` +
|
||||
`--color-gray-40: ${str(text)};` +
|
||||
`--color-gray-30: ${str(gray1)};` +
|
||||
`--color-gray-80: ${str(gray1)};` +
|
||||
`--sidebar-border-color: ${str(gray1)};` +
|
||||
`--color-primary-light: ${str(accent().lighterBy(step))};` +
|
||||
`--button-hover-bg: ${str(gray1)};` +
|
||||
`--sidebar-bg-color: ${gray2.alphaTo(0.93).stringHEX()};` +
|
||||
`--sidebar-shadow: ${str(gray1)};` +
|
||||
`--popup-text-color: ${str(text)};` +
|
||||
`--code-normal: ${str(text)};` +
|
||||
`--code-background: ${str(gray2)};` +
|
||||
`--h1-color: ${str(text)};` +
|
||||
`--h2-color: ${str(text)};` +
|
||||
`--h3-color: ${str(text)};` +
|
||||
`--h4-color: ${str(text)};` +
|
||||
`color: ${str(text)};` +
|
||||
`--select-highlight-color: ${str(gray1)};`;
|
||||
|
||||
view.excalidrawContainer?.setAttribute(
|
||||
"style",
|
||||
style
|
||||
)
|
||||
|
||||
setTimeout(()=>view.updateScene({appState:{dynamicStyle: style}}));
|
||||
const toolspanel = view.toolsPanelRef?.current?.containerRef?.current;
|
||||
if(toolspanel) {
|
||||
let toolsStyle = toolspanel.getAttribute("style");
|
||||
toolsStyle = toolsStyle.replace(/\-\-color\-primary.*/,"");
|
||||
toolspanel.setAttribute("style",toolsStyle+style);
|
||||
}
|
||||
|
||||
}
|
||||
51
src/utils/ExcalidrawViewUtils.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
|
||||
import { MAX_IMAGE_SIZE } from "src/Constants";
|
||||
import { TFile } from "obsidian";
|
||||
import { IMAGE_TYPES } from "src/Constants";
|
||||
import { ExcalidrawAutomate } from "src/ExcalidrawAutomate";
|
||||
|
||||
export const insertImageToView = async (
|
||||
ea: ExcalidrawAutomate,
|
||||
position: { x: number, y: number },
|
||||
file: TFile,
|
||||
scale?: boolean,
|
||||
):Promise<string> => {
|
||||
ea.clear();
|
||||
ea.style.strokeColor = "transparent";
|
||||
ea.style.backgroundColor = "transparent";
|
||||
const api = ea.getExcalidrawAPI();
|
||||
ea.canvas.theme = api.getAppState().theme;
|
||||
const id = await ea.addImage(
|
||||
position.x,
|
||||
position.y,
|
||||
file,
|
||||
scale,
|
||||
);
|
||||
await ea.addElementsToView(false, false, true);
|
||||
return id;
|
||||
}
|
||||
|
||||
export const insertIFrameToView = async (
|
||||
ea: ExcalidrawAutomate,
|
||||
position: { x: number, y: number },
|
||||
file?: TFile,
|
||||
link?: string,
|
||||
):Promise<string> => {
|
||||
ea.clear();
|
||||
ea.style.strokeColor = "transparent";
|
||||
ea.style.backgroundColor = "transparent";
|
||||
if(file && IMAGE_TYPES.contains(file.extension) || ea.isExcalidrawFile(file)) {
|
||||
return await insertImageToView(ea, position, file);
|
||||
} else {
|
||||
const id = ea.addIFrame(
|
||||
position.x,
|
||||
position.y,
|
||||
MAX_IMAGE_SIZE,
|
||||
MAX_IMAGE_SIZE,
|
||||
link,
|
||||
file,
|
||||
);
|
||||
await ea.addElementsToView(false, false, true);
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
import { normalizePath, Notice, TAbstractFile, TFile, TFolder, Vault } from "obsidian";
|
||||
import { ExcalidrawSettings } from "src/Settings";
|
||||
import { DataURL } from "@zsviczian/excalidraw/types/types";
|
||||
import { loadPdfJs, normalizePath, Notice, requestUrl, RequestUrlResponse, TAbstractFile, TFile, TFolder, Vault } from "obsidian";
|
||||
import { URLFETCHTIMEOUT } from "src/Constants";
|
||||
import { MimeType } from "src/EmbeddedFileLoader";
|
||||
import { ExcalidrawSettings } from "src/settings";
|
||||
import { errorlog, getDataURL } from "./Utils";
|
||||
|
||||
/**
|
||||
* Splits a full path including a folderpath and a filename into separate folderpath and filename components
|
||||
@@ -26,7 +30,7 @@ export function splitFolderAndFilename(filepath: string): {
|
||||
* @param data
|
||||
* @param filename
|
||||
*/
|
||||
export function download(encoding: string, data: any, filename: string) {
|
||||
export const download = (encoding: string, data: any, filename: string) => {
|
||||
const element = document.createElement("a");
|
||||
element.setAttribute("href", (encoding ? `${encoding},` : "") + data);
|
||||
element.setAttribute("download", filename);
|
||||
@@ -145,3 +149,59 @@ export async function checkAndCreateFolder(folderpath: string) {
|
||||
await vault.createFolder(folderpath);
|
||||
}
|
||||
|
||||
export const getURLImageExtension = (url: string):string => {
|
||||
const corelink = url.split("?")[0];
|
||||
return corelink.substring(corelink.lastIndexOf(".")+1);
|
||||
}
|
||||
|
||||
export const getMimeType = (extension: string):MimeType => {
|
||||
switch (extension) {
|
||||
case "png": return "image/png";
|
||||
case "jpeg": return "image/jpeg";
|
||||
case "jpg": return "image/jpeg";
|
||||
case "gif": return "image/gif";
|
||||
case "webp": return "image/webp";
|
||||
case "bmp": return "image/bmp";
|
||||
case "ico": return "image/x-icon";
|
||||
case "svg": return "image/svg+xml";
|
||||
case "md": return "image/svg+xml";
|
||||
default: return "application/octet-stream";
|
||||
}
|
||||
}
|
||||
|
||||
const getFileFromURL = async (url: string, mimeType: MimeType, timeout: number = URLFETCHTIMEOUT):Promise<RequestUrlResponse> => {
|
||||
try {
|
||||
return await Promise.race([
|
||||
(async () => new Promise<RequestUrlResponse>((resolve) => setTimeout(()=>resolve(null), timeout)))(),
|
||||
requestUrl({url: url, method: "get", contentType: mimeType, throw: false })
|
||||
])
|
||||
} catch (e) {
|
||||
errorlog({where: getFileFromURL, message: `URL did not load within timeout period of ${timeout}ms`, url: url});
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export const getDataURLFromURL = async (url: string, mimeType: MimeType, timeout: number = URLFETCHTIMEOUT):Promise<DataURL> => {
|
||||
const response = await getFileFromURL(url, mimeType, timeout);
|
||||
return response && response.status === 200
|
||||
? await getDataURL(response.arrayBuffer, mimeType)
|
||||
: url as DataURL;
|
||||
}
|
||||
|
||||
export const blobToBase64 = async (blob: Blob): Promise<string> => {
|
||||
const arrayBuffer = await blob.arrayBuffer()
|
||||
const bytes = new Uint8Array(arrayBuffer)
|
||||
var binary = '';
|
||||
var len = bytes.byteLength;
|
||||
for (var i = 0; i < len; i++) {
|
||||
binary += String.fromCharCode(bytes[i]);
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
export const getPDFDoc = async (f: TFile): Promise<any> => {
|
||||
//@ts-ignore
|
||||
if(typeof window.pdfjsLib === "undefined") await loadPdfJs();
|
||||
//@ts-ignore
|
||||
return await window.pdfjsLib.getDocument(app.vault.getResourcePath(f)).promise;
|
||||
}
|
||||
@@ -12,6 +12,9 @@ export const getElementsAtPointer = (
|
||||
if (type && e.type !== type) {
|
||||
return false;
|
||||
}
|
||||
if (e.locked) {
|
||||
return false;
|
||||
}
|
||||
const [x, y, w, h] = rotatedDimensions(e);
|
||||
return (
|
||||
x <= pointer.x &&
|
||||
|
||||
256
src/utils/ImageCache.ts
Normal file
@@ -0,0 +1,256 @@
|
||||
import { Notice, TFile } from "obsidian";
|
||||
import ExcalidrawPlugin from "src/main";
|
||||
|
||||
//@ts-ignore
|
||||
const DB_NAME = "Excalidraw " + app.appId;
|
||||
const STORE_NAME = "imageCache";
|
||||
|
||||
|
||||
type FileCacheData = { mtime: number; imageBase64: string };
|
||||
|
||||
type ImageKey = {
|
||||
filepath: string;
|
||||
blockref: string;
|
||||
sectionref: string;
|
||||
isDark: boolean;
|
||||
isSVG: boolean;
|
||||
scale: number;
|
||||
};
|
||||
|
||||
const getKey = (key: ImageKey): string => `${key.filepath}#${key.blockref}#${key.sectionref}#${key.isDark?1:0}#${key.isSVG?1:0}#${key.scale}`;
|
||||
|
||||
class ImageCache {
|
||||
private dbName: string;
|
||||
private storeName: string;
|
||||
private db: IDBDatabase | null;
|
||||
private isInitializing: boolean;
|
||||
public plugin: ExcalidrawPlugin;
|
||||
|
||||
constructor(dbName: string, storeName: string) {
|
||||
this.dbName = dbName;
|
||||
this.storeName = storeName;
|
||||
this.db = null;
|
||||
this.isInitializing = false;
|
||||
this.plugin = null;
|
||||
app.workspace.onLayoutReady(()=>this.initializeDB());
|
||||
}
|
||||
|
||||
private async initializeDB(): Promise<void> {
|
||||
if (this.isInitializing || this.db !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isInitializing = true;
|
||||
|
||||
try {
|
||||
const request = indexedDB.open(this.dbName);
|
||||
|
||||
request.onupgradeneeded = (event: IDBVersionChangeEvent) => {
|
||||
const db = (event.target as IDBOpenDBRequest).result;
|
||||
if (!db.objectStoreNames.contains(this.storeName)) {
|
||||
db.createObjectStore(this.storeName);
|
||||
}
|
||||
};
|
||||
|
||||
this.db = await new Promise<IDBDatabase>((resolve, reject) => {
|
||||
request.onsuccess = (event: Event) => {
|
||||
const db = (event.target as IDBOpenDBRequest).result;
|
||||
resolve(db);
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to open or create IndexedDB database: ${this.dbName}`));
|
||||
};
|
||||
});
|
||||
|
||||
// Pre-create the object store to reduce delay when accessing it later
|
||||
if (!this.db.objectStoreNames.contains(this.storeName)) {
|
||||
const version = this.db.version + 1;
|
||||
this.db.close();
|
||||
|
||||
const upgradeRequest = indexedDB.open(this.dbName, version);
|
||||
upgradeRequest.onupgradeneeded = (event: IDBVersionChangeEvent) => {
|
||||
const db = (event.target as IDBOpenDBRequest).result;
|
||||
db.createObjectStore(this.storeName);
|
||||
};
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
upgradeRequest.onsuccess = () => {
|
||||
const db = (upgradeRequest.result as IDBDatabase);
|
||||
db.close();
|
||||
resolve();
|
||||
};
|
||||
|
||||
upgradeRequest.onerror = () => {
|
||||
reject(new Error(`Failed to upgrade IndexedDB database: ${this.dbName}`));
|
||||
};
|
||||
});
|
||||
|
||||
this.db = await new Promise<IDBDatabase>((resolve, reject) => {
|
||||
const openRequest = indexedDB.open(this.dbName);
|
||||
openRequest.onsuccess = () => {
|
||||
const db = (openRequest.result as IDBDatabase);
|
||||
resolve(db);
|
||||
};
|
||||
openRequest.onerror = () => {
|
||||
reject(new Error(`Failed to open IndexedDB database: ${this.dbName}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
await this.purgeInvalidFiles();
|
||||
|
||||
} finally {
|
||||
this.isInitializing = false;
|
||||
console.log("Initialized Excalidraw Image Cache");
|
||||
}
|
||||
}
|
||||
|
||||
private async purgeInvalidFiles(): Promise<void> {
|
||||
const transaction = this.db!.transaction(this.storeName, "readwrite");
|
||||
const store = transaction.objectStore(this.storeName);
|
||||
const files = app.vault.getFiles();
|
||||
|
||||
const deletePromises: Promise<void>[] = [];
|
||||
|
||||
const request = store.openCursor();
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
request.onsuccess = (event: Event) => {
|
||||
const cursor = (event.target as IDBRequest<IDBCursorWithValue | null>).result;
|
||||
if (cursor) {
|
||||
const key = cursor.key as string;
|
||||
const filepath = key.split("#")[0];
|
||||
const fileExists = files.some((f: TFile) => f.path === filepath);
|
||||
const file = fileExists ? files.find((f: TFile) => f.path === filepath) : null;
|
||||
if (!file || (file && file.stat.mtime > cursor.value.mtime)) {
|
||||
deletePromises.push(
|
||||
new Promise<void>((resolve, reject) => {
|
||||
const deleteRequest = store.delete(cursor.primaryKey);
|
||||
deleteRequest.onsuccess = () => resolve();
|
||||
deleteRequest.onerror = () =>
|
||||
reject(new Error(`Failed to delete file with key: ${key}`));
|
||||
})
|
||||
);
|
||||
}
|
||||
cursor.continue();
|
||||
} else {
|
||||
Promise.all(deletePromises)
|
||||
.then(() => resolve())
|
||||
.catch((error) => reject(error));
|
||||
}
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error("Failed to purge invalid files from IndexedDB."));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private async getObjectStore(mode: IDBTransactionMode): Promise<IDBObjectStore> {
|
||||
const transaction = this.db!.transaction(this.storeName, mode);
|
||||
return transaction.objectStore(this.storeName);
|
||||
}
|
||||
|
||||
public async openDB(): Promise<IDBDatabase> {
|
||||
return new Promise<IDBDatabase>((resolve, reject) => {
|
||||
const request = indexedDB.open(this.dbName);
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error("Failed to open IndexedDB database."));
|
||||
};
|
||||
|
||||
request.onsuccess = () => {
|
||||
const db = request.result as IDBDatabase;
|
||||
resolve(db);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
private async getCacheData(key: string): Promise<FileCacheData | null> {
|
||||
const store = await this.getObjectStore("readonly");
|
||||
const request = store.get(key);
|
||||
|
||||
return new Promise<FileCacheData | null>((resolve, reject) => {
|
||||
request.onsuccess = () => {
|
||||
const result = request.result as FileCacheData;
|
||||
resolve(result || null);
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error("Failed to retrieve data from IndexedDB."));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
public async isCached(key_: ImageKey): Promise<boolean> {
|
||||
const key = getKey(key_);
|
||||
return this.getCacheData(key).then((cachedData) => {
|
||||
if (cachedData) {
|
||||
const file = app.vault.getAbstractFileByPath(key_.filepath.split("#")[0]);
|
||||
if (!file || !(file instanceof TFile)) return false;
|
||||
if (cachedData.mtime === file.stat.mtime) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
public isReady(): boolean {
|
||||
return !!this.db && !this.isInitializing && !!this.plugin && this.plugin.settings.allowImageCache;
|
||||
}
|
||||
|
||||
public async get(key_: ImageKey): Promise<string | undefined> {
|
||||
if (!this.isReady()) {
|
||||
return null; // Database not initialized yet
|
||||
}
|
||||
|
||||
const key = getKey(key_);
|
||||
return this.getCacheData(key).then((cachedData) => {
|
||||
const file = app.vault.getAbstractFileByPath(key_.filepath.split("#")[0]);
|
||||
if (!file || !(file instanceof TFile)) return undefined;
|
||||
if (cachedData && cachedData.mtime === file.stat.mtime) {
|
||||
return cachedData.imageBase64;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
}
|
||||
|
||||
public add(key_: ImageKey, imageBase64: string): void {
|
||||
if (!this.isReady()) {
|
||||
return; // Database not initialized yet
|
||||
}
|
||||
|
||||
const file = app.vault.getAbstractFileByPath(key_.filepath.split("#")[0]);
|
||||
if (!file || !(file instanceof TFile)) return;
|
||||
const data: FileCacheData = { mtime: file.stat.mtime, imageBase64 };
|
||||
|
||||
const transaction = this.db.transaction(this.storeName, "readwrite");
|
||||
const store = transaction.objectStore(this.storeName);
|
||||
const key = getKey(key_)
|
||||
store.put(data, key);
|
||||
}
|
||||
|
||||
public async clear(): Promise<void> {
|
||||
// deliberately not checking isReady() here
|
||||
if (!this.db || this.isInitializing) {
|
||||
return; // Database not initialized yet
|
||||
}
|
||||
|
||||
const transaction = this.db.transaction(this.storeName, "readwrite");
|
||||
const store = transaction.objectStore(this.storeName);
|
||||
const request = store.clear();
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
request.onsuccess = () => {
|
||||
new Notice("Image cache cleared.");
|
||||
resolve();
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
reject(new Error("Failed to clear data in IndexedDB."));
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const imageCache = new ImageCache(DB_NAME, STORE_NAME);
|
||||
60
src/utils/ModifierkeyHelper.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { DEVICE, isDarwin } from "src/Constants";
|
||||
export type ModifierKeys = {shiftKey:boolean, ctrlKey: boolean, metaKey: boolean, altKey: boolean};
|
||||
export type KeyEvent = PointerEvent | MouseEvent | KeyboardEvent | React.DragEvent | React.PointerEvent | React.MouseEvent | ModifierKeys;
|
||||
export type PaneTarget = "active-pane"|"new-pane"|"popout-window"|"new-tab"|"md-properties";
|
||||
export type ExternalDragAction = "insert-link"|"image-url"|"image-import"|"iframe";
|
||||
export type InternalDragAction = "link"|"image"|"image-fullsize"|"iframe";
|
||||
|
||||
export const labelCTRL = () => DEVICE.isIOS || DEVICE.isMacOS ? "CMD" : "CTRL";
|
||||
export const labelALT = () => DEVICE.isIOS || DEVICE.isMacOS ? "OPT" : "ALT";
|
||||
export const labelMETA = () => DEVICE.isIOS || DEVICE.isMacOS ? "CTRL" : (DEVICE.isWindows ? "WIN" : "META");
|
||||
export const labelSHIFT = () => "SHIFT";
|
||||
|
||||
export const isCTRL = (e:KeyEvent) => DEVICE.isIOS || DEVICE.isMacOS ? e.metaKey : e.ctrlKey;
|
||||
export const isALT = (e:KeyEvent) => e.altKey;
|
||||
export const isMETA = (e:KeyEvent) => DEVICE.isIOS || DEVICE.isMacOS ? e.ctrlKey : e.metaKey;
|
||||
export const isSHIFT = (e:KeyEvent) => e.shiftKey;
|
||||
|
||||
export const mdPropModifier = (ev: KeyEvent): boolean => !isSHIFT(ev) && isCTRL(ev) && !isALT(ev) && isMETA(ev);
|
||||
export const scaleToFullsizeModifier = (ev: KeyEvent) =>
|
||||
( isSHIFT(ev) && !isCTRL(ev) && !isALT(ev) && isMETA(ev)) ||
|
||||
(!isSHIFT(ev) && isCTRL(ev) && isALT(ev) && !isMETA(ev));
|
||||
|
||||
export const linkClickModifierType = (ev: KeyEvent):PaneTarget => {
|
||||
if(isCTRL(ev) && !isALT(ev) && isSHIFT(ev) && !isMETA(ev)) return "active-pane";
|
||||
if(isCTRL(ev) && !isALT(ev) && !isSHIFT(ev) && !isMETA(ev)) return "new-tab";
|
||||
if(isCTRL(ev) && isALT(ev) && !isSHIFT(ev) && !isMETA(ev)) return "new-pane";
|
||||
if(DEVICE.isDesktop && isCTRL(ev) && isALT(ev) && isSHIFT(ev) && !isMETA(ev) ) return "popout-window";
|
||||
if(isCTRL(ev) && isALT(ev) && isSHIFT(ev) && !isMETA(ev)) return "new-tab";
|
||||
if(mdPropModifier(ev)) return "md-properties";
|
||||
return "active-pane";
|
||||
}
|
||||
|
||||
export const externalDragModifierType = (ev: KeyEvent):ExternalDragAction => {
|
||||
if(DEVICE.isWindows && isSHIFT(ev) && isCTRL(ev) && !isALT(ev) && !isMETA(ev)) return "iframe";
|
||||
if(DEVICE.isMacOS && !isSHIFT(ev) && !isCTRL(ev) && isALT(ev) && !isMETA(ev)) return "iframe";
|
||||
if(DEVICE.isWindows && !isSHIFT(ev) && isCTRL(ev) && !isALT(ev) && !isMETA(ev)) return "insert-link";
|
||||
if(DEVICE.isMacOS && isSHIFT(ev) && !isCTRL(ev) && isALT(ev) && !isMETA(ev)) return "insert-link";
|
||||
if( isSHIFT(ev) && !isCTRL(ev) && !isALT(ev) && !isMETA(ev)) return "image-import";
|
||||
if(DEVICE.isWindows && !isSHIFT(ev) && !isCTRL(ev) && isALT(ev) && !isMETA(ev)) return "image-import";
|
||||
return "image-url";
|
||||
}
|
||||
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/468
|
||||
export const internalDragModifierType = (ev: KeyEvent):InternalDragAction => {
|
||||
if( !(DEVICE.isIOS || DEVICE.isMacOS) && isSHIFT(ev) && isCTRL(ev) && !isALT(ev) && !isMETA(ev)) return "iframe";
|
||||
if( (DEVICE.isIOS || DEVICE.isMacOS) && !isSHIFT(ev) && !isCTRL(ev) && !isALT(ev) && isMETA(ev)) return "iframe";
|
||||
if( isSHIFT(ev) && !isCTRL(ev) && !isALT(ev) && !isMETA(ev)) return "image";
|
||||
if(!isSHIFT(ev) && isCTRL(ev) && !isALT(ev) && !isMETA(ev)) return "image";
|
||||
if(scaleToFullsizeModifier(ev)) return "image-fullsize";
|
||||
return "link";
|
||||
}
|
||||
|
||||
export const emulateCTRLClickForLinks = (e:KeyEvent) => {
|
||||
return {
|
||||
shiftKey: e.shiftKey,
|
||||
ctrlKey: e.ctrlKey || !(DEVICE.isIOS || DEVICE.isMacOS),
|
||||
metaKey: e.metaKey || (DEVICE.isIOS || DEVICE.isMacOS),
|
||||
altKey: e.altKey
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,10 @@ import {
|
||||
App,
|
||||
normalizePath, Notice, WorkspaceLeaf
|
||||
} from "obsidian";
|
||||
import { DEVICE } from "src/Constants";
|
||||
import ExcalidrawPlugin from "../main";
|
||||
import { checkAndCreateFolder, splitFolderAndFilename } from "./FileUtils";
|
||||
import { isALT, isCTRL, isMETA, isSHIFT, KeyEvent, linkClickModifierType, ModifierKeys } from "./ModifierkeyHelper";
|
||||
|
||||
export const getParentOfClass = (element: HTMLElement, cssClass: string):HTMLElement | null => {
|
||||
let parent = element.parentElement;
|
||||
@@ -19,6 +21,56 @@ export const getParentOfClass = (element: HTMLElement, cssClass: string):HTMLEle
|
||||
};
|
||||
|
||||
|
||||
|
||||
export const getLeaf = (
|
||||
plugin: ExcalidrawPlugin,
|
||||
origo: WorkspaceLeaf,
|
||||
ev: ModifierKeys
|
||||
) => {
|
||||
const newTab = ():WorkspaceLeaf => {
|
||||
if(!plugin.settings.openInMainWorkspace) return app.workspace.getLeaf('tab');
|
||||
const [leafLoc, mainLeavesIds] = getLeafLoc(origo);
|
||||
if(leafLoc === 'main') return app.workspace.getLeaf('tab');
|
||||
return getNewOrAdjacentLeaf(plugin,origo);
|
||||
}
|
||||
const newTabGroup = ():WorkspaceLeaf => getNewOrAdjacentLeaf(plugin,origo);
|
||||
const newWindow = ():WorkspaceLeaf => app.workspace.openPopoutLeaf();
|
||||
|
||||
switch(linkClickModifierType(ev)) {
|
||||
case "active-pane": return origo;
|
||||
case "new-tab": return newTab();
|
||||
case "new-pane": return newTabGroup();
|
||||
case "popout-window": return newWindow();
|
||||
default: return newTab();
|
||||
}
|
||||
}
|
||||
|
||||
const getLeafLoc = (leaf: WorkspaceLeaf): ["main" | "popout" | "left" | "right" | "hover",any] => {
|
||||
//@ts-ignore
|
||||
const leafId = leaf.id;
|
||||
const layout = app.workspace.getLayout();
|
||||
const getLeaves = (l:any)=> l.children
|
||||
.filter((c:any)=>c.type!=="leaf")
|
||||
.map((c:any)=>getLeaves(c))
|
||||
.flat()
|
||||
.concat(l.children.filter((c:any)=>c.type==="leaf").map((c:any)=>c.id))
|
||||
|
||||
const mainLeavesIds = getLeaves(layout.main);
|
||||
|
||||
return [
|
||||
layout.main && mainLeavesIds.contains(leafId)
|
||||
? "main"
|
||||
: layout.floating && getLeaves(layout.floating).contains(leafId)
|
||||
? "popout"
|
||||
: layout.left && getLeaves(layout.left).contains(leafId)
|
||||
? "left"
|
||||
: layout.right && getLeaves(layout.right).contains(leafId)
|
||||
? "right"
|
||||
: "hover",
|
||||
mainLeavesIds
|
||||
];
|
||||
}
|
||||
|
||||
/*
|
||||
| Setting | Originating Leaf |
|
||||
| | Main Workspace | Hover Editor | Popout Window |
|
||||
@@ -28,32 +80,11 @@ export const getParentOfClass = (element: HTMLElement, cssClass: string):HTMLEle
|
||||
| !InMain && InAdjacent | 1.1 Reuse Leaf in Main Workspace | 3 Reuse Leaf in Current Hover Editor | 4 Reuse Leaf in Current Popout |
|
||||
| !InMain && !InAdjacent | 1.2 New Leaf in Main Workspace | 2 New Leaf in Current Hover Editor | 2 New Leaf in Current Popout |
|
||||
*/
|
||||
|
||||
export const getNewOrAdjacentLeaf = (
|
||||
plugin: ExcalidrawPlugin,
|
||||
leaf: WorkspaceLeaf
|
||||
): WorkspaceLeaf => {
|
||||
//@ts-ignore
|
||||
const leafId = leaf.id;
|
||||
const layout = app.workspace.getLayout();
|
||||
const getLeaves = (l:any)=> l.children
|
||||
.filter((c:any)=>c.type!=="leaf")
|
||||
.map((c:any)=>getLeaves(c))
|
||||
.flat()
|
||||
.concat(l.children.filter((c:any)=>c.type==="leaf").map((c:any)=>c.id))
|
||||
|
||||
const mainLeavesIds = getLeaves(layout.main);
|
||||
|
||||
const leafLoc =
|
||||
layout.main && mainLeavesIds.contains(leafId)
|
||||
? "main"
|
||||
: layout.floating && getLeaves(layout.floating).contains(leafId)
|
||||
? "popout"
|
||||
: layout.left && getLeaves(layout.left).contains(leafId)
|
||||
? "left"
|
||||
: layout.right && getLeaves(layout.right).contains(leafId)
|
||||
? "right"
|
||||
: "hover";
|
||||
const [leafLoc, mainLeavesIds] = getLeafLoc(leaf);
|
||||
|
||||
const getMainLeaf = ():WorkspaceLeaf => {
|
||||
let mainLeaf = app.workspace.getMostRecentLeaf();
|
||||
|
||||
221
src/utils/Pens.ts
Normal file
@@ -0,0 +1,221 @@
|
||||
import { PenStyle, PenType } from "src/PenTypes";
|
||||
|
||||
export const PENS:Record<PenType,PenStyle> = {
|
||||
"default": {
|
||||
type: "default",
|
||||
freedrawOnly: false,
|
||||
strokeColor: "#000000",
|
||||
backgroundColor: "transparent",
|
||||
fillStyle: "hachure",
|
||||
strokeWidth: 0,
|
||||
roughness: 0,
|
||||
penOptions: {
|
||||
highlighter: false,
|
||||
constantPressure: false,
|
||||
hasOutline: false,
|
||||
outlineWidth: 1,
|
||||
options: {
|
||||
thinning: 0.6,
|
||||
smoothing: 0.5,
|
||||
streamline: 0.5,
|
||||
easing: "easeOutSine",
|
||||
start: {
|
||||
cap: true,
|
||||
taper: 0,
|
||||
easing: "linear"
|
||||
},
|
||||
end: {
|
||||
cap: true,
|
||||
taper: 0,
|
||||
easing: "linear"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"highlighter": {
|
||||
type: "highlighter",
|
||||
freedrawOnly: true,
|
||||
strokeColor: "#FFC47C",
|
||||
backgroundColor: "#FFC47C",
|
||||
fillStyle: "solid",
|
||||
strokeWidth: 2,
|
||||
roughness: null,
|
||||
penOptions: {
|
||||
highlighter: true,
|
||||
constantPressure: true,
|
||||
hasOutline: true,
|
||||
outlineWidth: 4,
|
||||
options: {
|
||||
thinning: 1,
|
||||
smoothing: 0.5,
|
||||
streamline: 0.5,
|
||||
easing: "linear",
|
||||
start: {
|
||||
taper: 0,
|
||||
cap: true,
|
||||
easing: "linear"
|
||||
},
|
||||
end: {
|
||||
taper: 0,
|
||||
cap: true,
|
||||
easing: "linear"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"finetip": {
|
||||
type: "finetip",
|
||||
freedrawOnly: false,
|
||||
strokeColor: "#3E6F8D",
|
||||
backgroundColor: "transparent",
|
||||
fillStyle: "hachure",
|
||||
strokeWidth: 0.5,
|
||||
roughness: 0,
|
||||
penOptions: {
|
||||
highlighter: false,
|
||||
hasOutline: false,
|
||||
outlineWidth: 1,
|
||||
constantPressure: true,
|
||||
options: {
|
||||
smoothing: 0.4,
|
||||
thinning: -0.5,
|
||||
streamline: 0.4,
|
||||
easing: "linear",
|
||||
start: {
|
||||
taper: 5,
|
||||
cap: false,
|
||||
easing: "linear"
|
||||
},
|
||||
end: {
|
||||
taper: 5,
|
||||
cap: false,
|
||||
easing:"linear"
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
"fountain": {
|
||||
type: "fountain",
|
||||
freedrawOnly: false,
|
||||
strokeColor: "#000000",
|
||||
backgroundColor: "transparent",
|
||||
fillStyle: "hachure",
|
||||
strokeWidth: 2,
|
||||
roughness: 0,
|
||||
penOptions: {
|
||||
highlighter: false,
|
||||
constantPressure: false,
|
||||
hasOutline: false,
|
||||
outlineWidth: 1,
|
||||
options: {
|
||||
smoothing: 0.2,
|
||||
thinning: 0.6,
|
||||
streamline: 0.2,
|
||||
easing: "easeInOutSine",
|
||||
start: {
|
||||
taper: 150,
|
||||
cap: true,
|
||||
easing: "linear"
|
||||
},
|
||||
end: {
|
||||
taper: 1,
|
||||
cap: true,
|
||||
easing: "linear"
|
||||
},
|
||||
}
|
||||
}
|
||||
},
|
||||
"marker": {
|
||||
type: "marker",
|
||||
freedrawOnly: true,
|
||||
strokeColor: "#B83E3E",
|
||||
backgroundColor: "#FF7C7C",
|
||||
fillStyle: "dashed",
|
||||
strokeWidth: 2,
|
||||
roughness: 3,
|
||||
penOptions: {
|
||||
highlighter: false,
|
||||
constantPressure: true,
|
||||
hasOutline: true,
|
||||
outlineWidth: 4,
|
||||
options: {
|
||||
thinning: 1,
|
||||
smoothing: 0.5,
|
||||
streamline: 0.5,
|
||||
easing: "linear",
|
||||
start: {
|
||||
taper: 0,
|
||||
cap: true,
|
||||
easing: "linear"
|
||||
},
|
||||
end: {
|
||||
taper: 0,
|
||||
cap: true,
|
||||
easing: "linear"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"thick-thin": {
|
||||
type: "thick-thin",
|
||||
freedrawOnly: true,
|
||||
strokeColor: "#CECDCC",
|
||||
backgroundColor: "transparent",
|
||||
fillStyle: "hachure",
|
||||
strokeWidth: 0,
|
||||
roughness: null,
|
||||
penOptions: {
|
||||
highlighter: true,
|
||||
constantPressure: true,
|
||||
hasOutline: false,
|
||||
outlineWidth: 1,
|
||||
options: {
|
||||
thinning: 1,
|
||||
smoothing: 0.5,
|
||||
streamline: 0.5,
|
||||
easing: "linear",
|
||||
start: {
|
||||
taper: 0,
|
||||
cap: true,
|
||||
easing: "linear"
|
||||
},
|
||||
end: {
|
||||
cap: true,
|
||||
taper: true,
|
||||
easing: "linear",
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"thin-thick-thin": {
|
||||
type: "thin-thick-thin",
|
||||
freedrawOnly: true,
|
||||
strokeColor: "#CECDCC",
|
||||
backgroundColor: "transparent",
|
||||
fillStyle: "hachure",
|
||||
strokeWidth: 0,
|
||||
roughness: null,
|
||||
penOptions: {
|
||||
highlighter: true,
|
||||
constantPressure: true,
|
||||
hasOutline: false,
|
||||
outlineWidth: 1,
|
||||
options: {
|
||||
thinning: 1,
|
||||
smoothing: 0.5,
|
||||
streamline: 0.5,
|
||||
easing: "linear",
|
||||
start: {
|
||||
cap: true,
|
||||
taper: true,
|
||||
easing: "linear",
|
||||
},
|
||||
end: {
|
||||
cap: true,
|
||||
taper: true,
|
||||
easing: "linear",
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
App,
|
||||
Notice,
|
||||
request,
|
||||
requestUrl,
|
||||
TFile,
|
||||
} from "obsidian";
|
||||
import { Random } from "roughjs/bin/math";
|
||||
@@ -22,7 +23,8 @@ import { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/types";
|
||||
import { ExportSettings } from "../ExcalidrawView";
|
||||
import { compressToBase64, decompressFromBase64 } from "lz-string";
|
||||
import { getIMGFilename } from "./FileUtils";
|
||||
import ExcalidrawScene from "lib/svgToExcalidraw/elements/ExcalidrawScene";
|
||||
import ExcalidrawScene from "../svgToExcalidraw/elements/ExcalidrawScene";
|
||||
import { IMAGE_TYPES } from "../Constants";
|
||||
|
||||
declare const PLUGIN_VERSION:string;
|
||||
|
||||
@@ -442,6 +444,7 @@ export type LinkParts = {
|
||||
ref: string;
|
||||
width: number;
|
||||
height: number;
|
||||
page: number;
|
||||
};
|
||||
|
||||
export const getLinkParts = (fname: string, file?: TFile): LinkParts => {
|
||||
@@ -451,9 +454,10 @@ export const getLinkParts = (fname: string, file?: TFile): LinkParts => {
|
||||
original: fname,
|
||||
path: file && parts[1] === "" ? file.path : parts[1],
|
||||
isBlockRef: parts[2] === "^",
|
||||
ref: parts[3]?.replaceAll(REG_BLOCK_REF_CLEAN, ""),
|
||||
ref: parts[3]?.match(/^page=\d*$/i) ? parts[3] : parts[3]?.replaceAll(REG_BLOCK_REF_CLEAN, ""),
|
||||
width: parts[4] ? parseInt(parts[4]) : undefined,
|
||||
height: parts[5] ? parseInt(parts[5]) : undefined,
|
||||
page: parseInt(parts[3]?.match(/page=(\d*)/)?.[1])
|
||||
};
|
||||
};
|
||||
|
||||
@@ -671,4 +675,54 @@ export const getContainerElement = (
|
||||
return scene.elements.filter(el=>el.id === element.containerId)[0] ?? null;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
};
|
||||
|
||||
export const updateFrontmatterInString = (data:string, keyValuePairs: [string,string][]):string => {
|
||||
if(!data) return data;
|
||||
for(const kvp of keyValuePairs) {
|
||||
const r = new RegExp(`${kvp[0]}:\\s.*\\n`,"g");
|
||||
data = data.match(r)
|
||||
? data.replaceAll(r,`${kvp[0]}: ${kvp[1]}\n`)
|
||||
: data.replace(/^---\n/,`---\n${kvp[0]}: ${kvp[1]}\n`);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
const isHyperlink = (link:string) => link && !link.includes("\n") && !link.includes("\r") && link.match(/^https?:(\d*)?\/\/[^\s]*$/);
|
||||
|
||||
export const isContainer = (el: ExcalidrawElement) => el.type!=="arrow" && el.boundElements?.map((e) => e.type).includes("text");
|
||||
|
||||
export const hyperlinkIsImage = (data: string):boolean => {
|
||||
if(!isHyperlink(data)) false;
|
||||
const corelink = data.split("?")[0];
|
||||
return IMAGE_TYPES.contains(corelink.substring(corelink.lastIndexOf(".")+1));
|
||||
}
|
||||
|
||||
export const hyperlinkIsYouTubeLink = (link:string): boolean =>
|
||||
isHyperlink(link) &&
|
||||
(link.startsWith("https://youtu.be") || link.startsWith("https://www.youtube.com") || link.startsWith("https://youtube.com") || link.startsWith("https//www.youtu.be")) &&
|
||||
link.match(/(youtu.be\/|v=)([^?\/\&]*)/)!==null
|
||||
|
||||
export const getYouTubeThumbnailLink = async (youtubelink: string):Promise<string> => {
|
||||
//https://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
|
||||
//https://youtu.be/z8UkHGpykYU?t=60
|
||||
//https://www.youtube.com/watch?v=z8UkHGpykYU&ab_channel=VerbaltoVisual
|
||||
const parsed = youtubelink.match(/(youtu.be\/|v=)([^?\/\&]*)/);
|
||||
if(!parsed || !parsed[2]) return null;
|
||||
const videoId = parsed[2];
|
||||
|
||||
let url = `https://i.ytimg.com/vi/${videoId}/maxresdefault.jpg`;
|
||||
let response = await requestUrl({url, method: "get", contentType: "image/jpeg", throw: false });
|
||||
if(response && response.status === 200) return url;
|
||||
|
||||
url = `https://i.ytimg.com/vi/${videoId}/hq720.jpg`;
|
||||
response = await requestUrl({url, method: "get", contentType: "image/jpeg", throw: false });
|
||||
if(response && response.status === 200) return url;
|
||||
|
||||
url = `https://i.ytimg.com/vi/${videoId}/mqdefault.jpg`;
|
||||
response = await requestUrl({url, method: "get", contentType: "image/jpeg", throw: false });
|
||||
if(response && response.status === 200) return url;
|
||||
|
||||
|
||||
return `https://i.ytimg.com/vi/${videoId}/default.jpg`;
|
||||
}
|
||||
72
styles.css
@@ -21,6 +21,10 @@
|
||||
display: none;
|
||||
}
|
||||
|
||||
img.excalidraw-embedded-img {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
img.excalidraw-svg-right-wrap {
|
||||
float: right;
|
||||
margin: 0px 0px 20px 20px;
|
||||
@@ -67,6 +71,17 @@ button.ToolIcon_type_button[title="Export"] {
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
.excalidraw-prompt-button {
|
||||
width: 9em;
|
||||
}
|
||||
|
||||
.excalidraw-prompt-buttons-div {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
flex-wrap: nowrap;
|
||||
justify-content: space-evenly;
|
||||
}
|
||||
|
||||
li[data-testid] {
|
||||
border: 0 !important;
|
||||
margin: 0 !important;
|
||||
@@ -156,6 +171,7 @@ li[data-testid] {
|
||||
|
||||
.workspace-leaf-content .excalidraw-view {
|
||||
padding: 0px 1px; /*1px so on ipad swipe in from left and right still works*/
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.excalidraw-videoWrapper {
|
||||
@@ -184,7 +200,7 @@ li[data-testid] {
|
||||
|
||||
.excalidraw-release .modal {
|
||||
max-height: 80%;
|
||||
max-width: 100ch;
|
||||
max-width: 42em;
|
||||
}
|
||||
|
||||
.excalidraw .Island .scrollbar {
|
||||
@@ -276,7 +292,7 @@ textarea.excalidraw-wysiwyg {
|
||||
}
|
||||
|
||||
label.color-input-container > input {
|
||||
max-width: 8rem;
|
||||
max-width: 5rem;
|
||||
}
|
||||
|
||||
.excalidraw .FixedSideContainer_side_top {
|
||||
@@ -288,4 +304,56 @@ label.color-input-container > input {
|
||||
|
||||
.excalidraw-hidden {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.excalidraw .panelColumn .buttonList {
|
||||
max-width: 13rem;
|
||||
}
|
||||
|
||||
.excalidraw button {
|
||||
width: initial;
|
||||
}
|
||||
|
||||
.excalidraw input[type="color"] {
|
||||
width: 1.65rem;
|
||||
height: 1.65rem;
|
||||
}
|
||||
|
||||
.excalidraw input[type="color"]::-webkit-color-swatch {
|
||||
height: 1.65rem;
|
||||
}
|
||||
|
||||
|
||||
.excalidraw input[type="color"]::-webkit-color-swatch-wrapper {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.excalidraw-settings input {
|
||||
min-width: 10em;
|
||||
}
|
||||
|
||||
div.excalidraw-draginfo {
|
||||
position: absolute;
|
||||
z-index: 1000;
|
||||
color: var(--text-normal);
|
||||
padding: 3px;
|
||||
background: var(--color-base-40);
|
||||
display: block;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.excalidraw [data-radix-popper-content-wrapper] {
|
||||
position: absolute !important;
|
||||
}
|
||||
|
||||
.excalidraw__iframe-container .view-header {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.excalidraw__iframe-container input {
|
||||
background: initial;
|
||||
}
|
||||
|
||||
.excalidraw .HelpDialog__key {
|
||||
background-color: var(--color-gray-80) !important;
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
{
|
||||
"1.8.20": "1.1.6",
|
||||
"1.8.19": "1.0.0",
|
||||
"1.8.5": "1.0.0",
|
||||
"1.7.13": "0.15.6",
|
||||
"1.7.8": "0.15.5",
|
||||
"1.7.7": "0.15.4",
|
||||
|
||||