Compare commits

...

28 Commits

Author SHA1 Message Date
zsviczian
41b1a170f7 1.8.15-beta 2023-02-19 20:58:04 +01:00
zsviczian
e6d39eca75 upload modifiers table 2023-02-19 16:56:12 +01:00
zsviczian
8ca6a9fe96 1.8.14 2023-02-13 17:16:32 +01:00
zsviczian
48e47f333e 1.8.13 2023-02-12 15:41:18 +01:00
zsviczian
3091ed629a 1.8.12 2023-01-29 13:29:41 +01:00
zsviczian
a9193dd695 updated mindmap format description 2023-01-28 23:47:06 +01:00
zsviczian
3122e86e22 mindmap format script 2023-01-28 23:37:48 +01:00
zsviczian
a6efe27146 Merge pull request #968 from pandoralink/feature/mindmap-format
feat: add Mindmap format ea-script
2023-01-28 23:24:21 +01:00
zsviczian
adbec35e30 Merge pull request #989 from SamRidgeway/typo-fix
Fixes a typo in the fullscreen action
2023-01-28 23:23:35 +01:00
zsviczian
205a94d3a3 custom pen debug 2023-01-28 23:23:04 +01:00
zsviczian
6e88c8f0eb Pens and pinned scripts 2023-01-27 22:35:27 +01:00
Sam Ridgeway
32a05322d0 Fixes a typo in the fullscreen action 2023-01-27 09:39:14 -05:00
zsviczian
8738b74236 1.8.11 2023-01-22 14:19:41 +01:00
zsviczian
aa0ddd85fd handle link click cleanup duplicat function 2023-01-20 20:32:50 +01:00
zsviczian
bcd47ddb8e wheel, pinch, image url, grid 2023-01-19 22:24:15 +01:00
zsviczian
50f24b42cb 1.8.10 2023-01-15 16:49:28 +01:00
poplink
0a5d511c96 feat: add Mindmap format ea-script 2023-01-11 17:50:04 +08:00
zsviczian
70d93602f7 added new customized menu 2023-01-09 23:05:48 +01:00
zsviczian
68c7c9f55e 1.8.9 2023-01-08 14:29:56 +01:00
zsviczian
42f1fa88b9 added funding URL 2023-01-06 18:00:27 +01:00
zsviczian
3a2d064024 1.8.8 2023-01-06 17:57:05 +01:00
zsviczian
38cfdd4e0e corrected spelling of filename 2023-01-06 12:15:26 +01:00
zsviczian
fb93c0c352 publish updated scripts 2023-01-06 12:11:07 +01:00
zsviczian
f4fb1e3cc8 Alternative pen assets 2023-01-06 11:49:00 +01:00
zsviczian
5c11e5733e updated slideshow and deconstruct scripts 2023-01-02 16:09:21 +01:00
zsviczian
8d8f7a7866 1.8.7 2022-12-23 21:48:04 +01:00
zsviczian
da89e32213 1.8.6 2022-12-17 14:04:46 +01:00
zsviczian
b6d36e5076 Update manifest.json 2022-12-17 13:41:36 +01:00
59 changed files with 6221 additions and 2896 deletions

5
.gitignore vendored
View File

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

32
README-BUILD.md Normal file
View File

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

View File

@@ -48,6 +48,7 @@ The Obsidian-Excalidraw plugin integrates [Excalidraw](https://excalidraw.com/),
<a href="https://youtu.be/vlC1-iBvIfo" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/199207784-8bbe14e0-7d10-47d7-971d-20dce8dbd659.png" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;SVG import</a><br>
<a href="https://youtu.be/7gu4ETx7zro" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/202916770-28f2fa64-1ba2-4b40-a7fe-d721b42634f7.png" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;OCR</a><br>
<a href="https://youtu.be/U2LkBRBk4LY" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/159369910-6371f08d-b5fa-454d-9c6c-948f7e7a7d26.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Bind/unbind text from container, Frontmatter tags to customize export</a><br>
<a href="https://youtu.be/uZz5MgzWXiM" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/211054371-8872e01a-77d6-4afc-a0c2-86a55410a8d3.png" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Custom pen support</a><br>
</details>
<details><summary>Quality of life improvements</summary>
<a href="https://youtu.be/qbPIAZguJeo" target="_blank"><img src="https://user-images.githubusercontent.com/14358394/151705333-54e9ffd2-0bd7-4d02-b99e-0bd4e4708d4d.jpg" width="100" style="vertical-align: middle;"/>&nbsp;&nbsp;Mobile Support</a><br>
@@ -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
![](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/images/excalidraw-modifiers.png)
#### Hyperlinks
- Supports hyperlinks e.g.
- `https://zsolt.blog`,
- `[Obsidian](https://obsidian.md)`, and
@@ -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
View File

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

View File

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

View File

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

After

Width:  |  Height:  |  Size: 632 B

View File

@@ -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);

View File

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

View File

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

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@@ -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);

View File

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

View File

@@ -36,8 +36,8 @@ if(!lineEl || !["line","arrow"].contains(lineEl.type)) {
if(app.isMobile) {
ea.viewToggleFullScreen(true);
} else {
await contentEl.requestFullscreen();
await sleep(50);
await contentEl.webkitRequestFullscreen();
await sleep(500);
ea.setViewModeEnabled(true);
}
const deltaWidth = () => contentEl.clientWidth-api.getAppState().width;
@@ -64,7 +64,7 @@ const slideCount = Math.floor(lineEl.points.length/2)-1;
const getNextSlide = (forward) => {
slide = forward
? slide < slideCount ? slide + 1 : 0
: slide <= 0 ? slideCount : slide - 1;
: slide <= 0 ? slideCount : slide - 1;
return {pointA:lineEl.points[slide*2], pointB:lineEl.points[slide*2+1]}
}
@@ -129,7 +129,7 @@ const navigate = async (dir) => {
exitPresentation();
return;
}
if(slideNumberEl) slideNumberEl.innerText = (slide+1).toString();
if(slideNumberEl) slideNumberEl.innerText = `${slide+1}/${slideCount+1}`;
const nextRect = getSlideRect(nextSlide);
await scrollToNextRect(nextRect);
}
@@ -279,4 +279,4 @@ if(!app.isMobile) {
}
//navigate to the first slide on start
setTimeout(()=>navigate("fwd"));
setTimeout(()=>navigate("fwd"));

File diff suppressed because one or more lines are too long

View File

@@ -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/Alternative%20Pens.svg"/></div>|[[#Alternative Pens]]|
|<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]]|
@@ -56,6 +57,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/Grid%20Selected%20Images.svg"/></div>|[[#Grid selected images]]|
|<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]]|
@@ -102,6 +104,13 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/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 Layout
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Auto%20Layout.md
@@ -252,6 +261,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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 222 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

After

Width:  |  Height:  |  Size: 224 KiB

View File

@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "1.8.3-beta",
"version": "1.8.15-beta",
"minAppVersion": "0.16.0",
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
"author": "Zsolt Viczian",

View File

@@ -1,10 +1,11 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "1.8.5",
"minAppVersion": "1.0.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.8.14",
"minAppVersion": "1.0.0",
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
"author": "Zsolt Viczian",
"authorUrl": "https://zsolt.blog",
"fundingUrl": "https://ko-fi.com/zsolt",
"isDesktopOnly": false
}

View File

@@ -1,6 +1,6 @@
{
"name": "obsidian-excalidraw-plugin",
"version": "1.7.26",
"version": "1.8.10",
"description": "This is an Obsidian.md plugin that lets you view and edit Excalidraw drawings",
"main": "lib/index.js",
"types": "lib/index.d.ts",
@@ -18,52 +18,52 @@
"license": "MIT",
"dependencies": {
"@types/lz-string": "^1.3.34",
"@zsviczian/excalidraw": "0.13.0-obsidian-2",
"clsx": "^1.1.1",
"@zsviczian/excalidraw": "0.14.1-obsidian",
"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"

View File

@@ -1,6 +1,9 @@
//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";
import { App, MarkdownRenderer, Notice, requestUrl, RequestUrlResponse, TFile } from "obsidian";
import {
CASCADIA_FONT,
DEFAULT_MD_EMBED_CSS,
@@ -11,6 +14,7 @@ import {
FRONTMATTER_KEY_MD_STYLE,
IMAGE_TYPES,
nanoid,
URLFETCHTIMEOUT,
VIRGIL_FONT,
} from "./Constants";
import { createSVG } from "./ExcalidrawAutomate";
@@ -19,6 +23,7 @@ import { ExportSettings } from "./ExcalidrawView";
import { t } from "./lang/helpers";
import { tex2dataURL } from "./LaTeX";
import ExcalidrawPlugin from "./main";
import { getDataURLFromURL, getMimeType, getURLImageExtension } from "./utils/FileUtils";
import {
errorlog,
getDataURL,
@@ -36,6 +41,15 @@ import {
const THEME_FILTER = "invert(100%) hue-rotate(180deg) saturate(1.25)";
//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 declare type MimeType =
| "image/svg+xml"
| "image/png"
@@ -68,7 +82,8 @@ export class EmbeddedFile {
public linkParts: LinkParts;
private hostPath: string;
public attemptCounter: number = 0;
/*public isHyperlink: boolean = false;*/
public isHyperlink: boolean = false;
public hyperlink:DataURL;
constructor(plugin: ExcalidrawPlugin, hostPath: string, imgPath: string) {
this.plugin = plugin;
@@ -76,14 +91,15 @@ export class EmbeddedFile {
}
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 +127,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 +150,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 +171,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 +193,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,7 +207,7 @@ 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%"));
}
}
@@ -216,22 +234,33 @@ export class EmbeddedFilesLoader {
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,
};
let hasSVGwithBitmap = false;
const isExcalidrawFile = this.plugin.isExcalidrawFile(file);
const isExcalidrawFile = !isHyperlink && this.plugin.isExcalidrawFile(file);
if (
!isHyperlink &&
!(
IMAGE_TYPES.contains(file.extension) ||
isExcalidrawFile ||
@@ -240,7 +269,9 @@ export class EmbeddedFilesLoader {
) {
return null;
}
const ab = await app.vault.readBinary(file);
const ab = isHyperlink
? null
: await app.vault.readBinary(file);
const getExcalidrawSVG = async (isDark: boolean) => {
//debug({where:"EmbeddedFileLoader.getExcalidrawSVG",uid:this.uid,file:file.name});
@@ -292,64 +323,55 @@ export class EmbeddedFilesLoader {
? 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 extension = isHyperlink
? getURLImageExtension(hyperlink)
: file.extension;
if (!isExcalidrawFile) {
mimeType = getMimeType(extension);
}
let dataURL =
isHyperlink
? (
inFile instanceof EmbeddedFile
? await getDataURLFromURL(inFile.hyperlink, mimeType)
: null
)
: excalidrawSVG ??
(file.extension === "svg"
? await getSVGData(app, file)
: 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 = await getImageSize(dataURL);
return {
mimeType,
fileId: await generateIdFromFile(
isHyperlink? (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) => void,
depth:number
) {
if(depth > 4) {
@@ -428,6 +450,7 @@ export class EmbeddedFilesLoader {
plugin: ExcalidrawPlugin,
file: TFile,
linkParts: LinkParts,
depth: number,
): Promise<{dataURL: DataURL, hasSVGwithBitmap:boolean}> {
//1.
//get the markdown text
@@ -655,7 +678,7 @@ const getSVGData = async (app: App, file: TFile): Promise<DataURL> => {
return svgToBase64(svg) as DataURL;
};
const generateIdFromFile = async (file: ArrayBuffer): Promise<FileId> => {
export const generateIdFromFile = async (file: ArrayBuffer): Promise<FileId> => {
let id: FileId;
try {
const hashBuffer = await window.crypto.subtle.digest("SHA-1", file);

View File

@@ -38,8 +38,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, 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";
@@ -142,6 +142,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
@@ -315,10 +328,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(
@@ -406,8 +423,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`;
});
@@ -940,7 +958,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();
@@ -948,17 +966,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" ? 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,
};

View File

@@ -17,6 +17,7 @@ import {
FRONTMATTER_KEY_LINKBUTTON_OPACITY,
FRONTMATTER_KEY_ONLOAD_SCRIPT,
FRONTMATTER_KEY_AUTOEXPORT,
DEVICE,
} from "./Constants";
import { _measureText } from "./ExcalidrawAutomate";
import ExcalidrawPlugin from "./main";
@@ -40,8 +41,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 };
@@ -517,8 +518,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,
@@ -551,6 +553,18 @@ export class ExcalidrawData {
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);
}
//Load Equations
const REG_FILEID_EQUATION = /([\w\d]*):\s*\$\$(.*)(\$\$\s*\n)/gm;
res = data.matchAll(REG_FILEID_EQUATION);
@@ -1050,11 +1064,15 @@ 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;
outString += `${key}: [[${path}]]\n`;
}
}
}
outString += this.equations.size > 0 || this.files.size > 0 ? "\n" : "";
@@ -1076,6 +1094,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
@@ -1121,7 +1187,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();
@@ -1145,47 +1211,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);
}
}
@@ -1329,7 +1359,7 @@ export class ExcalidrawData {
public getOpenMode(): { viewModeEnabled: boolean; zenModeEnabled: boolean } {
const fileCache = this.app.metadataCache.getFileCache(this.file);
let mode = this.plugin.settings.defaultMode === "view-mobile"
? (this.plugin.device.isPhone ? "view" : "normal")
? (DEVICE.isPhone ? "view" : "normal")
: this.plugin.settings.defaultMode;
if (
fileCache?.frontmatter &&
@@ -1448,12 +1478,23 @@ 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
@@ -1499,6 +1540,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);

File diff suppressed because it is too large Load Diff

View File

@@ -4,7 +4,7 @@ import {
TFile,
Vault,
} from "obsidian";
import { CTRL_OR_CMD, RERENDER_EVENT } from "./Constants";
import { RERENDER_EVENT } from "./Constants";
import { EmbeddedFilesLoader } from "./EmbeddedFileLoader";
import { createPNG, createSVG } from "./ExcalidrawAutomate";
import { ExportSettings } from "./ExcalidrawView";
@@ -21,7 +21,7 @@ import {
svgToBase64,
} from "./utils/Utils";
import { isObsidianThemeDark } from "./utils/ObsidianUtils";
import { image } from "html2canvas/dist/types/css/types/image";
import { isCTRL, isMETA, linkClickModifierType } from "./utils/ModifierkeyHelper";
interface imgElementAttributes {
file?: TFile;
@@ -56,6 +56,7 @@ export const initializeMarkdownPostProcessor = (p: ExcalidrawPlugin) => {
*/
const getIMG = async (
imgAttributes: imgElementAttributes,
onCanvas: boolean = false,
): Promise<HTMLElement> => {
let file = imgAttributes.file;
if (!imgAttributes.file) {
@@ -80,11 +81,11 @@ 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);
const theme =
@@ -180,16 +181,17 @@ const getIMG = async (
return null;
}
svg = embedFontsInSVG(svg, plugin);
svg.removeAttribute("width");
svg.removeAttribute("height");
//svg.removeAttribute("width");
//svg.removeAttribute("height");
img.setAttribute("src", svgToBase64(svg.outerHTML));
return img;
};
const createImgElement = async (
attr: imgElementAttributes,
onCanvas: boolean = false,
) :Promise<HTMLElement> => {
const img = await getIMG(attr);
const img = await getIMG(attr,onCanvas);
img.setAttribute("fileSource", attr.fname);
if (attr.fwidth) {
img.setAttribute("w", attr.fwidth);
@@ -197,6 +199,8 @@ const createImgElement = async (
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) => {
@@ -212,19 +216,25 @@ const createImgElement = async (
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",
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);
@@ -237,15 +247,18 @@ const createImgElement = async (
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();
newImg.style.maxHeight = imgMaxHeigth;
newImg.style.maxWidth = imgMaxWidth;
if(!onCanvas) {
newImg.style.maxHeight = imgMaxHeigth;
newImg.style.maxWidth = imgMaxWidth;
}
newImg.setAttribute("fileSource",fileSource);
parent.append(newImg);
});
@@ -254,8 +267,9 @@ const createImgElement = async (
const createImageDiv = async (
attr: imgElementAttributes,
onCanvas: boolean = false
): Promise<HTMLDivElement> => {
const img = await createImgElement(attr);
const img = await createImgElement(attr, onCanvas);
return createDiv(attr.style, (el) => el.append(img));
};
@@ -399,27 +413,30 @@ const tmpObsidianWYSIWYG = async (
const markdownEmbed = internalEmbedDiv.hasClass("markdown-embed");
const markdownReadingView = internalEmbedDiv.hasClass("markdown-reading-view");
if (!internalEmbedDiv.hasClass("internal-embed") &&
( markdownEmbed || markdownReadingView)
) {
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(!isFrontmatterDiv) {
containerEl.removeChild(el);
if(el.parentElement === containerEl) containerEl.removeChild(el);
return;
}
internalEmbedDiv.empty();
const imgDiv = await createImageDiv(attr);
const onCanvas = internalEmbedDiv.hasClass("canvas-node-content");
const imgDiv = await createImageDiv(attr, onCanvas);
if(markdownEmbed) {
internalEmbedDiv.addClass("markdown-embed");
if(imgDiv.firstChild instanceof HTMLElement) {
if(onCanvas) {
internalEmbedDiv.removeClass("markdown-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.firstChild);
return;
}
internalEmbedDiv.appendChild(imgDiv);
return;
@@ -579,11 +596,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);
});

View File

@@ -0,0 +1,577 @@
import {
MarkdownPostProcessorContext,
MetadataCache,
TFile,
Vault,
} from "obsidian";
import { RERENDER_EVENT } from "./Constants";
import { EmbeddedFilesLoader } from "./EmbeddedFileLoader";
import { createPNG, createSVG } from "./ExcalidrawAutomate";
import { ExportSettings } from "./ExcalidrawView";
import ExcalidrawPlugin from "./main";
import {getIMGFilename,} from "./utils/FileUtils";
import {
embedFontsInSVG,
getEmbeddedFilenameParts,
getExportTheme,
getQuickImagePreview,
getExportPadding,
getWithBackground,
hasExportTheme,
svgToBase64,
} from "./utils/Utils";
import { isObsidianThemeDark } from "./utils/ObsidianUtils";
import { isCTRL, isMETA, linkClickModifierType } from "./utils/ModifierkeyHelper";
interface imgElementAttributes {
file?: TFile;
fname: string; //Excalidraw filename
fwidth: string; //Display width of image
fheight: string; //Display height of image
style: string; //css style to apply to IMG element
}
let plugin: ExcalidrawPlugin;
let vault: Vault;
let metadataCache: MetadataCache;
const getDefaultWidth = (plugin: ExcalidrawPlugin): string => {
const width = parseInt(plugin.settings.width);
if (isNaN(width) || width === 0 || width === null) {
return "400";
}
return plugin.settings.width;
};
export const initializeMarkdownPostProcessor_Legacy = (p: ExcalidrawPlugin) => {
plugin = p;
vault = p.app.vault;
metadataCache = p.app.metadataCache;
};
/**
* Generates an img element with the drawing encoded as a base64 SVG or a PNG (depending on settings)
* @param parts {imgElementAttributes} - display properties of the image
* @returns {Promise<HTMLElement>} - the IMG HTML element containing the image
*/
const getIMG = async (
imgAttributes: imgElementAttributes,
): Promise<HTMLElement> => {
let file = imgAttributes.file;
if (!imgAttributes.file) {
const f = vault.getAbstractFileByPath(imgAttributes.fname?.split("#")[0]);
if (!(f && f instanceof TFile)) {
return null;
}
file = f;
}
const filenameParts = getEmbeddedFilenameParts(imgAttributes.fname);
// https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/387
imgAttributes.style = imgAttributes.style.replaceAll(" ", "-");
const forceTheme = hasExportTheme(plugin, file)
? getExportTheme(plugin, file, "light")
: undefined;
const exportSettings: ExportSettings = {
withBackground: getWithBackground(plugin, file),
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
if (imgAttributes.fheight) {
style += `height:${imgAttributes.fheight}px;`;
}
img.setAttribute("style", style);
img.addClass(imgAttributes.style);
const theme =
forceTheme ??
(plugin.settings.previewMatchObsidianTheme
? isObsidianThemeDark()
? "dark"
: "light"
: !plugin.settings.exportWithTheme
? "light"
: undefined);
if (theme) {
exportSettings.withTheme = true;
}
const loader = new EmbeddedFilesLoader(
plugin,
theme ? theme === "dark" : undefined,
);
if (!plugin.settings.displaySVGInPreview) {
const width = parseInt(imgAttributes.fwidth);
const scale = width >= 2400
? 5
: width >= 1800
? 4
: width >= 1200
? 3
: width >= 600
? 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 quickPNG = !filenameParts.hasGroupref
? await getQuickImagePreview(plugin, file.path, "png")
: undefined;
const png =
quickPNG ??
(await createPNG(
filenameParts.hasGroupref
? filenameParts.filepath + filenameParts.linkpartReference
: file.path,
scale,
exportSettings,
loader,
theme,
null,
null,
[],
plugin,
0
));
if (!png) {
return null;
}
img.src = URL.createObjectURL(png);
return img;
}
if(!(filenameParts.hasBlockref || filenameParts.hasSectionref)) {
const quickSVG = await getQuickImagePreview(plugin, file.path, "svg");
if (quickSVG) {
img.setAttribute("src", svgToBase64(quickSVG));
return img;
}
}
const svgSnapshot = (
await createSVG(
filenameParts.hasGroupref || filenameParts.hasBlockref || filenameParts.hasSectionref
? filenameParts.filepath + filenameParts.linkpartReference
: file.path,
true,
exportSettings,
loader,
theme,
null,
null,
[],
plugin,
0,
getExportPadding(plugin, file),
)
).outerHTML;
let svg: SVGSVGElement = null;
const el = document.createElement("div");
el.innerHTML = svgSnapshot;
const firstChild = el.firstChild;
if (firstChild instanceof SVGSVGElement) {
svg = firstChild;
}
if (!svg) {
return null;
}
svg = embedFontsInSVG(svg, plugin);
svg.removeAttribute("width");
svg.removeAttribute("height");
img.setAttribute("src", svgToBase64(svg.outerHTML));
return img;
};
const createImageDiv = async (
attr: imgElementAttributes,
): 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);
}
let timer:NodeJS.Timeout;
const clickEvent = (ev:PointerEvent) => {
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,
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)=>{
timer = setTimeout(()=>clickEvent(ev),500);
pointerDownEvent = ev;
});
el.addEventListener("pointerup",()=>{
if(timer) clearTimeout(timer);
timer = null;
})
el.addEventListener("dblclick",clickEvent);
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 processReadingMode = async (
embeddedItems: NodeListOf<Element> | [HTMLElement],
ctx: MarkdownPostProcessorContext,
) => {
//We are processing a non-excalidraw file in reading mode
//Embedded files will be displayed in an .internal-embed container
//Iterating all the containers in the file to check which one is an excalidraw drawing
//This is a for loop instead of embeddedItems.forEach() because processInternalEmbed at the end
//is awaited, otherwise excalidraw images would not display in the Kanban plugin
for (const maybeDrawing of embeddedItems) {
//check to see if the file in the src attribute exists
const fname = maybeDrawing.getAttribute("src")?.split("#")[0];
if(!fname) continue;
const file = metadataCache.getFirstLinkpathDest(fname, ctx.sourcePath);
//if the embeddedFile exits and it is an Excalidraw file
//then lets replace the .internal-embed with the generated PNG or SVG image
if (file && file instanceof TFile && plugin.isExcalidrawFile(file)) {
if(isTextOnlyEmbed(maybeDrawing)) {
//legacy reference to a block or section as text
//should be embedded as legacy text
continue;
}
maybeDrawing.parentElement.replaceChild(
await processInternalEmbed(maybeDrawing,file),
maybeDrawing
);
}
}
};
const processInternalEmbed = async (internalEmbedEl: Element, file: TFile ):Promise<HTMLDivElement> => {
const attr: imgElementAttributes = {
fname: "",
fheight: "",
fwidth: "",
style: "",
};
const src = internalEmbedEl.getAttribute("src");
if(!src) return;
attr.fwidth = internalEmbedEl.getAttribute("width")
? internalEmbedEl.getAttribute("width")
: getDefaultWidth(plugin);
attr.fheight = internalEmbedEl.getAttribute("height");
let alt = internalEmbedEl.getAttribute("alt");
attr.style = "excalidraw-svg";
processAltText(src.split("#")[0],alt,attr);
const fnameParts = getEmbeddedFilenameParts(src);
attr.fname = file?.path + (fnameParts.hasBlockref||fnameParts.hasSectionref?fnameParts.linkpartReference:"");
attr.file = file;
return await createImageDiv(attr);
}
const processAltText = (
fname: string,
alt:string,
attr: imgElementAttributes
) => {
if (alt && !alt.startsWith(fname)) {
//2:width, 3:height, 4:style 12 3 4
const parts = alt.match(/[^\|\d]*\|?((\d*%?)x?(\d*%?))?\|?(.*)/);
attr.fwidth = parts[2] ?? attr.fwidth;
attr.fheight = parts[3] ?? attr.fheight;
if (parts[4] && !parts[4].startsWith(fname)) {
attr.style = `excalidraw-svg${`-${parts[4]}`}`;
}
if (
(!parts[4] || parts[4]==="") &&
(!parts[2] || parts[2]==="") &&
parts[0] && parts[0] !== ""
) {
attr.style = `excalidraw-svg${`-${parts[0]}`}`;
}
}
}
const isTextOnlyEmbed = (internalEmbedEl: Element):boolean => {
const src = internalEmbedEl.getAttribute("src");
if(!src) return true; //technically this does not mean this is a text only embed, but still should abort further processing
const fnameParts = getEmbeddedFilenameParts(src);
return !(fnameParts.hasArearef || fnameParts.hasGroupref) &&
(fnameParts.hasBlockref || fnameParts.hasSectionref)
}
const tmpObsidianWYSIWYG = async (
el: HTMLElement,
ctx: MarkdownPostProcessorContext,
) => {
const file = app.vault.getAbstractFileByPath(ctx.sourcePath);
if(!(file instanceof TFile)) return;
if(!plugin.isExcalidrawFile(file)) return;
//@ts-ignore
if (ctx.remainingNestLevel < 4) {
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
//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;
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;
}
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
});
});
};
/**
*
* @param el
* @param ctx
*/
export const markdownPostProcessor_Legacy = async (
el: HTMLElement,
ctx: MarkdownPostProcessorContext,
) => {
//check to see if we are rendering in editing mode or live preview
//if yes, then there should be no .internal-embed containers
const embeddedItems = el.querySelectorAll(".internal-embed");
if (embeddedItems.length === 0) {
tmpObsidianWYSIWYG(el, ctx);
return;
}
//If the file being processed is an excalidraw file,
//then I want to hide all embedded items as these will be
//transcluded text element or some other transcluded content inside the Excalidraw file
//in reading mode these elements should be hidden
const excalidrawFile = Boolean(ctx.frontmatter?.hasOwnProperty("excalidraw-plugin"));
if (excalidrawFile) {
el.style.display = "none";
return;
}
await processReadingMode(embeddedItems, ctx);
};
/**
* internal-link quick preview
* @param e
* @returns
*/
export const hoverEvent_Legacy = (e: any) => {
if (!e.linktext) {
plugin.hover.linkText = null;
return;
}
plugin.hover.linkText = e.linktext;
plugin.hover.sourcePath = e.sourcePath;
};
//monitoring for div.popover.hover-popover.file-embed.is-loaded to be added to the DOM tree
export const observer_Legacy = new MutationObserver(async (m) => {
if (m.length == 0) {
return;
}
if (!plugin.hover.linkText) {
return;
}
const file = metadataCache.getFirstLinkpathDest(
plugin.hover.linkText,
plugin.hover.sourcePath ? plugin.hover.sourcePath : "",
);
if (!file) {
return;
}
if (!(file instanceof TFile)) {
return;
}
if (file.extension !== "excalidraw") {
return;
}
const svgFileName = getIMGFilename(file.path, "svg");
const svgFile = vault.getAbstractFileByPath(svgFileName);
if (svgFile && svgFile instanceof TFile) {
return;
} //If auto export SVG or PNG is enabled it will be inserted at the top of the excalidraw file. No need to manually insert hover preview
const pngFileName = getIMGFilename(file.path, "png");
const pngFile = vault.getAbstractFileByPath(pngFileName);
if (pngFile && pngFile instanceof TFile) {
return;
} //If auto export SVG or PNG is enabled it will be inserted at the top of the excalidraw file. No need to manually insert hover preview
if (!plugin.hover.linkText) {
return;
}
if (m.length != 1) {
return;
}
if (m[0].addedNodes.length != 1) {
return;
}
if (
//@ts-ignore
!m[0].addedNodes[0].classNames !=
"popover hover-popover file-embed is-loaded"
) {
return;
}
const node = m[0].addedNodes[0];
node.empty();
//this div will be on top of original DIV. By stopping the propagation of the click
//I prevent the default Obsidian feature of openning the link in the native app
const img = await getIMG({
file,
fname: file.path,
fwidth: "300",
fheight: null,
style: "excalidraw-svg",
});
const div = createDiv("", async (el) => {
el.appendChild(img);
el.setAttribute("src", file.path);
el.onClickEvent((ev) => {
ev.stopImmediatePropagation();
const src = el.getAttribute("src");
if (src) {
plugin.openDrawing(
vault.getAbstractFileByPath(src) as TFile,
linkClickModifierType(ev)
);
} //.ctrlKey||ev.metaKey);
});
});
node.appendChild(div);
});

39
src/PenTypes.ts Normal file
View File

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

View File

@@ -13,7 +13,7 @@ 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;
}
@@ -245,6 +246,7 @@ export class ScriptEngine {
hint,
instructions,
),
scriptFile: file
});
/*} catch (e) {
new Notice(t("SCRIPT_EXECUTION_ERROR"), 4000);

View File

@@ -4,7 +4,28 @@ export function JSON_parse(x: string): any {
return JSON.parse(x.replaceAll("&#91;", "["));
}
export const isDarwin = /Mac|iPod|iPhone|iPad/.test(window.navigator.platform);
export const CTRL_OR_CMD = isDarwin ? "metaKey" : "ctrlKey";
export const DEVICE: {
isDesktop: boolean,
isPhone: boolean,
isTablet: boolean,
isMobile: boolean,
isLinux: boolean,
isMacOS: boolean,
isWindows: boolean,
isIOS: boolean,
isAndroid: boolean
} = {
isDesktop: !document.body.hasClass("is-tablet") && !document.body.hasClass("is-mobile"),
isPhone: document.body.hasClass("is-phone"),
isTablet: document.body.hasClass("is-tablet"),
isMobile: document.body.hasClass("is-mobile"), //running Obsidian Mobile, need to also check isTablet
isLinux: document.body.hasClass("mod-linux") && ! document.body.hasClass("is-android"),
isMacOS: document.body.hasClass("mod-macos") && ! document.body.hasClass("is-ios"),
isWindows: document.body.hasClass("mod-windows"),
isIOS: document.body.hasClass("is-ios"),
isAndroid: document.body.hasClass("is-android")
};
export const nanoid = customAlphabet(
"1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
8,
@@ -17,6 +38,7 @@ export const ROUNDNESS = { //should at one point publish @zsviczian/excalidraw/t
PROPORTIONAL_RADIUS: 2,
ADAPTIVE_RADIUS: 3,
} as const;
export const URLFETCHTIMEOUT = 1000;
export const PLUGIN_ID = "obsidian-excalidraw-plugin";
export const SCRIPT_INSTALL_CODEBLOCK = "excalidraw-script-install";
export const SCRIPT_INSTALL_FOLDER = "Downloaded";
@@ -46,7 +68,6 @@ export const FRONTMATTER_KEY_FONTCOLOR = "excalidraw-font-color";
export const FRONTMATTER_KEY_BORDERCOLOR = "excalidraw-border-color";
export const FRONTMATTER_KEY_MD_STYLE = "excalidraw-css";
export const FRONTMATTER_KEY_AUTOEXPORT = "excalidraw-autoexport"
export const LOCAL_PROTOCOL = "md://";
export const VIEW_TYPE_EXCALIDRAW = "excalidraw";
export const ICON_NAME = "excalidraw-icon";
export const MAX_COLORS = 5;

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

@@ -0,0 +1,196 @@
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 boundingBox: {
topX: number;
topY: number;
width: number;
height: number;
};
public embedScene: 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.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`);
}
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());
})
)
const themeMessage = () => `Export with ${this.theme} theme`;
const themeSetting = new Setting(this.contentEl)
.setName(themeMessage())
.setDesc(fragWithHTML("<b>Toggle on:</b> Export with light theme<br><b>Toggle off:</b> Export with dark theme"))
.addToggle(toggle =>
toggle
.setValue(this.theme === "dark" ? false : true)
.onChange(value => {
this.theme = value ? "light" : "dark";
themeSetting.setName(themeMessage());
})
)
const transparencyMessage = () => `Export with ${this.transparent ? "transparent ":""}background`;
const transparentSetting = new Setting(this.contentEl)
.setName(transparencyMessage())
.setDesc(fragWithHTML("<b>Toggle on:</b> Export with transparent background<br><b>Toggle off:</b> Export with background"))
.addToggle(toggle =>
toggle
.setValue(this.transparent)
.onChange(value => {
this.transparent = value;
transparentSetting.setName(transparencyMessage())
})
)
const saveSettingsMessage = () => this.saveSettings?"Save these settings as the preset for this image":"These are one-time settings"
const saveSettingsSetting= new Setting(this.contentEl)
.setName(saveSettingsMessage())
.setDesc(fragWithHTML("Saving these settings as preset will override general export settings for this image.<br><b>Toggle on: </b>Save as preset for this image<br><b>Toggle off: </b>Don't save as preset"))
.addToggle(toggle =>
toggle
.setValue(this.saveSettings)
.onChange(value => {
this.saveSettings = value;
saveSettingsSetting.setName(saveSettingsMessage())
})
)
this.contentEl.createEl("h1",{text:"Export settings"});
const embedSceneMessage = () => this.embedScene?"Embed scene":"Do not embed scene";
const embedSetting = new Setting(this.contentEl)
.setName(embedSceneMessage())
.setDesc(fragWithHTML("Embed the Excalidraw scene into the PNG or SVG image<br><b>Toggle on: </b>Embed scene<br><b>Toggle off: </b>Do not embed scene"))
.addToggle(toggle =>
toggle
.setValue(this.embedScene)
.onChange(value => {
this.embedScene = value;
embedSetting.setName(embedSceneMessage())
})
)
if(DEVICE.isDesktop) {
const saveToMessage = () => this.saveToVault?"Save image to your Vault":"Export image outside your Vault";
const saveToSetting = new Setting(this.contentEl)
.setName(saveToMessage())
.setDesc(fragWithHTML("<b>Toggle on: </b>Save image to your Vault in the same folder as this drawing<br><b>Toggle off: </b>Save image outside your Vault"))
.addToggle(toggle =>
toggle
.setValue(this.saveToVault)
.onChange(value => {
this.saveToVault = value;
saveToSetting.setName(saveToMessage())
})
)
}
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.exportPNG();
this.close();
};
const bSVG = div.createEl("button", { text: "SVG to File", cls: "excalidraw-prompt-button" });
bSVG.onclick = () => {
this.saveToVault
? this.view.saveSVG()
: this.view.exportSVG();
this.close();
};
const bExcalidraw = div.createEl("button", { text: "Excalidraw", cls: "excalidraw-prompt-button" });
bExcalidraw.onclick = () => {
this.view.exportExcalidraw();
this.close();
};
if(DEVICE.isDesktop) {
const bPNGClipboard = div.createEl("button", { text: "PNG to Clipboard", cls: "excalidraw-prompt-button" });
bPNGClipboard.onclick = () => {
this.view.exportPNGToClipboard();
this.close();
};
}
}
}

View File

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

View File

@@ -17,7 +17,95 @@ I develop this plugin as a hobby, spending my free time doing this. If you find
<div class="ex-coffee-div"><a href="https://ko-fi.com/zsolt"><img src="https://cdn.ko-fi.com/cdn/kofi3.png?v=3" height=45></a></div>
`,
"1.8.5":`
"1.8.14":`
## Fixed
- text element link gets deleted when the drawing is reloaded
`,
"1.8.13": `
## Fixed
- When changing a text element in markdown mode, the change seem to have showed up when switching back to Excalidraw mode, but then lost these changes when loading the file the next time.
- Scrolling through a page that has embedded drawings on Obsidian Mobile accidently opens the drawing in Excalidraw when touching the image. Now you need to press and hold to open the image in Excalidraw. [#1003](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1003)
- The scrollbar is no longer visible when presenting using the SlideShow script
- Stroke properties could not be changed when custom pen settings had "Stroke & fill applies to: All shapes". It works now.
## QoL
- Custom pens will remember the stroke changes until you press the pen preset button again.
- This is a bit hard to explain, let me try... Essentially, when you use a custom pen, it will keep the changes you made to the pen (like changing the stroke width) until you press the pen-prereset button again. So, for example, if you're using a mind mapping custom pen and change its color, and then switch to a different tool like text, when you switch back to the freedraw tool using the Excalidraw tools panel, the pen will still have the same color you set earlier, but if you press the mind mapping pen-preset button, it will default back to your custom pen settings including your preset color.
- Added new buttons to load current stroke color and background color in the pen settings dialog. Also added an edit box so you can configure any valid color string (including with transparency) for pen stroke and background colors. [#991](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/991)
`,
"1.8.11": `
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/rBarRfcSxNo" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
# New
- Support for referencing images from the internet in Excalidraw drawings, including YouTube thumbnail support. [#913](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/913)
- Link to images on the internet without creating a copy in your Vault by holding down the CTRL key while dropping the link or image.
- Automatic conversion of image URLs and YouTube links into image elements with original links added as a link on the element when pasting. Note, that if you only want to paste the plain text link (not the image), first double-click the canvas to start a new text element, then paste the link.
- Two new options added to plugin settings:
- Make mouse wheel zoom by default [#474](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/474)
- Allow pinch zoom in pen mode [#828](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/828)
- Update to the [Set Grid](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Set%20Grid.svg) script now saves the grid setting for the current file.
`,
"1.8.10": `
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/wTtaXmRJ7wg" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
# QoL improvements
- You can structure icons in the Obsidian tools panel by moving scripts to folders
![image|300](https://user-images.githubusercontent.com/14358394/212389592-306130d0-209a-49df-99bb-c538f2155b23.png)
- I added useful actions to the hamburger menu in both tray-mode and normal-mode.
![image|150](https://user-images.githubusercontent.com/14358394/212534508-9107fd19-27ab-4415-8abc-bc97c73afc0b.png)
- I added a new Export Image dialog. You can access the new export screen from the hamburger-menu
![image|200](https://user-images.githubusercontent.com/14358394/212534654-7a479e23-8d5d-452e-9a18-a9896278aa27.png)
- Links in help now point to Obsidian-Excalidraw relevant content.
- I added a welcome screen
![image|150](https://user-images.githubusercontent.com/14358394/212534568-3cd1e8a1-5b20-4a30-96e4-40d7dac57e33.png)
- I updated the alternative dark mode / dynamic styling [script](https://gist.github.com/zsviczian/c7223c5b4af30d5c88a0cae05300305c)
`,
"1.8.9":`
# Minor QoL improvements
- When you open a second drawing in the same Excalidraw view (i.e. by navigating a link) and make a change to this drawing, and then press UNDO, the entire drawing disappeared. Redo brought the image back, however, this behavior was frustrating. Not anymore...
- On iPad
- when you open the command palette, autozoom resized the drawing. If the Obsidian command palette or some other modal window is shown Excalidraw will not resize the view.
- when you add a link to the drawing using the Command Palette, sometimes the link was added in a far corner of the drawing outside the current view area. This should be fixed now.`,
"1.8.8":`
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/uZz5MgzWXiM" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
# New
- The plugin now includes support for [Perfect Freehand](https://perfect-freehand-example.vercel.app/) pen-options. I've also added a new [Alternative Pens](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Alternative%20Pens.md) script.
- Embed scene in exported PNG and SVG images [#860](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/860). This means that the export will be a normal PNG or SVG image with the added functionality that if someone loads the image into excalidraw.com it will open as a normal excalidraw file.
- I've added 2 new Command Palette actions (export PNG, export SVG with embedded scene).
- If you SHIFT click ${String.fromCharCode(96)} Save as PNG (or SVG)${String.fromCharCode(96)} in the workspace-tab menu, Excalidraw will embed the scene in the export.
- I updated the [Organic Line](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Organic%20Line.md) script. It has an improved thick-to-thin look and a new thin-to-thick-to-thin line type.
# Fixed
- Intelligent image width setting [#955](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/955). Before this change, when the embedded image was small, the image would be extended to meet the image width setting in plugin settings. From now on, if the image is smaller than max-width, it will only extend to max-width. You can still set 100% width using custom CSS. See more on that [here](https://github.com/zsviczian/obsidian-excalidraw-plugin#embedded-images).
# New in ExcalidrawAutomate
- I added the ${String.fromCharCode(96)} plaintext${String.fromCharCode(96)} parameter to ${String.fromCharCode(96)}ExcalidrawAutomate.create${String.fromCharCode(96)} . Using this, you can add some text below the frontmatter but above the ${String.fromCharCode(96)}# Text Elements${String.fromCharCode(96)} section. Use this for example to add metadata to your file. (e.g. I use this in my Daily Quote template to add a Dataview field for the ${String.fromCharCode(96)}Author::${String.fromCharCode(96)} and add the quote with a standard block reference, so I can easily reference it in other files. I also add the ${String.fromCharCode(96)}#quote${String.fromCharCode(96)} tag to the file using this.)
- The script running in the ScriptEngine now also receives the ${String.fromCharCode(96)}TFile${String.fromCharCode(96)} object for the script itself. You can access this object during execution via the ${String.fromCharCode(96)}utils.scriptFile${String.fromCharCode(96)} variable.
`,
"1.8.7":`
## New from Excalidraw.com
- Support shrinking text containers to their original height when text is removed [#6025](https://github.com/excalidraw/excalidraw/pull/6025)
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://user-images.githubusercontent.com/14358394/209404092-579d54e9-7003-48ef-8b82-84be08ba6246.mp4" title="Demo" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
## Fixed
- removed the white background when editing arrow-label [#6033](https://github.com/excalidraw/excalidraw/pull/6033)
- Minor style tweaks
- for embedding Excalidraw into Obsidian Canvas. e.g. dragging no longer accidentally creates an image copy of the drawing, and
- style tweaks on the Excalidraw canvas
## New
- If you set a different text color and sticky note border color, now if you change the border color, the text color will not be changed.
`,
"1.8.6":`
## New from Excalidraw.com:
- Better default radius for rectangles [#5553](https://github.com/excalidraw/excalidraw/pull/5553). Existing drawings will look unchanged, this applies only to new rectangles.
![image|200](https://user-images.githubusercontent.com/5153846/206264345-59fd7436-e87b-4bc9-ade8-9e6f6a6fd8c1.png)
@@ -34,8 +122,9 @@ I develop this plugin as a hobby, spending my free time doing this. If you find
> DEFAULT_ADAPTIVE_RADIUS = 32;
## New
- Improved embedding into Obsidian Canvas
- Improved embedding into Markdown documents
- For Obsidian 1.1.6 and above
- Improved embedding into Obsidian Canvas
- Improved embedding into Markdown documents
- Added setting under ${String.fromCharCode(96)}Display/Default mode when opening Excalidraw${String.fromCharCode(96)} to always open the drawing in view mode on Mobile, but in normal mode on desktop. [#939](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/939)
## Fixed
@@ -162,637 +251,4 @@ Fix:
## New - power user features
- Force the embedded image to always scale to 100%. Note: this is a very niche feature with a very particular behavior that I built primarily for myself (even more so than other features in Excalidraw Obsidian - also built primarily for myself 😉)... This will reset your embedded image to 100% size every time you open the Excalidraw drawing, or in case you have embedded an Excalidraw drawing on your canvas inserted using this function, every time you update the embedded drawing, it will be scaled back to 100% size. This means that even if you resize the image on the drawing, it will reset to 100% the next time you open the file or you modify the original embedded object. This feature is useful when you decompose a drawing into separate Excalidraw files, but when combined onto a single canvas you want the individual pieces to maintain their actual sizes. I use this feature to construct Book-on-a-Page summaries from atomic drawings.
- I added an action to the command palette to temporarily disable/enable Excalidraw autosave. When autosave is disabled, Excalidraw will still save your drawing when changing to another Obsidian window, but it will not save every 10 seconds. On a mobile device (but also on a desktop) this can lead to data loss if you terminate Obsidian abruptly (i.e. swipe the application away, or close Obsidian without first closing the drawing). Use this feature if you find Excalidraw laggy.`,
"1.7.25":`## Fixed
- Tool buttons did not "stick" the first time you clicked them.
- Tray (in tray mode) was higher when the help button was visible. The tray in tablet mode was too large and the help button was missing.
- ExcalidrawAutomate ${String.fromCharCode(96)}getCM(color:TInput): ColorMaster;${String.fromCharCode(96)} function will now properly convert valid [css color names](https://www.w3schools.com/colors/colors_names.asp) to ColorMaster objects.
- The downloaded script icons in the Excalidraw-Obsidian menu were not always correct
- The obsidian mobile navigation bar at the bottom overlapped with Excalidraw
## New
- Created ExcalidrawAutomate hook for styling script when the canvas color changes. See sample [onCanvasColorChangeHook](https://gist.github.com/zsviczian/c7223c5b4af30d5c88a0cae05300305c) implementation following the link.
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/LtR04fNTKTM" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
${String.fromCharCode(96, 96, 96)}typescript
/**
* If set, this callback is triggered whenever the active canvas color changes
*/
onCanvasColorChangeHook: (
ea: ExcalidrawAutomate,
view: ExcalidrawView, //the Excalidraw view
color: string,
) => void = null;
${String.fromCharCode(96, 96, 96)}
`,
"1.7.24":`
# New and improved
- **Updated Chinese translation**. Thanks, @tswwe!
- **Improved update for TextElement links**: Until now, when you attached a link to a file to a TextElement using the "Create Link" command, this link did not get updated when the file was renamed or moved. Only links created as markdown links in the TextElement text were updated. Now both approaches work. Keep in mind however, that if you have a link in the TextElemenet text, it will override the link attached to the text element using the create link command. [#566](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/566)
- **Transclusion filters markdown comments**: Text transclusion in a TextElement using the ${String.fromCharCode(96)}![[file]]${String.fromCharCode(96)} or ${String.fromCharCode(96)}![[file#section]]${String.fromCharCode(96)} format did not filter out markdown comments in the file placed ${String.fromCharCode(96)}%% inside a comment block %%${String.fromCharCode(96)}. Now they do.
- **Remove leading '>' from trancluded quotes**: Added a new option in settings under **Links and Transclusion** to remove the leading ${String.fromCharCode(96)}> ${String.fromCharCode(96)} characters from quotes you transclude as a text element in your drawing.
![image](https://user-images.githubusercontent.com/14358394/194755306-6e7bf5f3-4228-44a1-9363-c3241b34865e.png)
- **Added support for ${String.fromCharCode(96)}webp${String.fromCharCode(96)}, ${String.fromCharCode(96)}bmp${String.fromCharCode(96)}, and ${String.fromCharCode(96)}ico${String.fromCharCode(96)} images**. This extends the already supported formats (${String.fromCharCode(96)}jpg${String.fromCharCode(96)}, ${String.fromCharCode(96)}gif${String.fromCharCode(96)}, ${String.fromCharCode(96)}png${String.fromCharCode(96)}, ${String.fromCharCode(96)}svg${String.fromCharCode(96)}).
- **Added command palette action to reset images to original size**. Select a single image or embedded Excalidraw drawing on your canvas and choose ${String.fromCharCode(96)}Set selected image element size to 100% of original${String.fromCharCode(96)} from the command palette. This function is especially helpful when you combine atomic drawings on a single canvas, keeping each atomic piece in its original excalidraw file (i.e. the way I create [book on a page summaries](https://www.youtube.com/playlist?list=PL6mqgtMZ4NP1-mbCYc3T7mr-unmsIXpEG))
- The ${String.fromCharCode(96)}async getOriginalImageSize(imageElement: ExcalidrawImageElement): Promise<{width: number; height: number}>${String.fromCharCode(96)} function is also avaiable via ExcalidrawAutomate. You may use this function to resize images to custom scales (e.g. 50% size, or to fit a certain bounding rectangle).
# Fixed
- **Upgraded perfect freehand package to resolve unwanted dots on end of lines** [#5727](https://github.com/excalidraw/excalidraw/pull/5727)
- **Pinch zoom in View mode opens images** resulting in a very annoying behavior [#837](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/837)
- **Embedded files** such as transcluded markdown documents and images **did not honor the Obsidian "New Link Format" setting** (shortest path, relative path, absolute path). [#829](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/829)
- **Fixed error with dataview queries involving Excalidraw files**: In case you created a task on an Excalidraw canvas (${String.fromCharCode(96)}docA.md${String.fromCharCode(96)}) by typing ${String.fromCharCode(96)}- [ ] Task [[owner]] #tag${String.fromCharCode(96)}, and then you created a Dataview tasklist in another document (${String.fromCharCode(96)}docB.md${String.fromCharCode(96)}) such that the query criteria matched the task in ${String.fromCharCode(96)}docA.md${String.fromCharCode(96)}, then the task from ${String.fromCharCode(96)}docA.md${String.fromCharCode(96)} only appeared as an empty line when viewing ${String.fromCharCode(96)}docB.md${String.fromCharCode(96)}. If you now embedded ${String.fromCharCode(96)}docB.md${String.fromCharCode(96)} into a third markdown document (${String.fromCharCode(96)}docC.md${String.fromCharCode(96)}), then instead of the contents of ${String.fromCharCode(96)}docB.md${String.fromCharCode(96)} Obsidian rendered ${String.fromCharCode(96)}docA.md${String.fromCharCode(96)}. [#835](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/835)
`,
"1.7.22":`
# Fixed
- Text size in sticky notes increased when opening the drawing and when editing a sticky note [#824](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/824)
- ToDo rendering did not work properly when there were parsed links in the text
- Horizontal text alignment in sticky notes did not honor text alignment setting when resizing text. The text was always aligned center even when text alignment was left or right. [#5720](https://github.com/excalidraw/excalidraw/issues/5720)
`,
"1.7.21":`
# New from Excalidraw.com
- Image-mirroring in export preview and in exported SVG [#5700](https://github.com/excalidraw/excalidraw/pull/5700), [#811](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/811), [#617](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/617)
# New
- Ctrl+s will force-save your drawing and update all your transclusions
- Added setting to parse ${String.fromCharCode(96)}- [ ] ${String.fromCharCode(96)} and ${String.fromCharCode(96)}- [x] ${String.fromCharCode(96)} todo items. Parsing is disabled by default. This feature can be found under "Links and Transclusions" in Plugin Settings. [#819](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/819)
![image](https://user-images.githubusercontent.com/14358394/192145020-94bdd115-d24f-47c7-86fe-1417c53980c4.png)
<iframe src="https://user-images.githubusercontent.com/14358394/192151120-3c61c822-0352-4ba7-9900-b38078fb373c.mp4" title="Demo" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
- Added new scripts to the script library
- [Rename Image](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Rename%20Image.md)
- [Text Arch](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Text%20Arch.md)
<iframe src="https://user-images.githubusercontent.com/14358394/192151105-78c0115b-4e30-4296-b647-e3c05851a48f.mp4" title="Demo" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
# Fixed
- Fixed toast message to display script name on press and hold on mobile and iPad.
- Fixed save error when the embedded image file is not found (i.e. it was moved, renamed, or deleted)
`,
"1.7.20":`
# New from Excalidraw.com
- support segment midpoints in line editor [#5641](https://github.com/excalidraw/excalidraw/pull/5641)
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://user-images.githubusercontent.com/11256141/187417807-3efeb673-6c96-4744-be0e-70119b0c6839.mp4" title="Demo" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
# Fixed
- When editing a line or arrow and selecting a tool on the toolbar, the tool jumps back to the selection tool and you need to click again to select the tool [#5703](https://github.com/excalidraw/excalidraw/issues/5703)
- Minor improvement of autosave, hopefully decreasing occasional lagging
`,
"1.7.19":`
# QoL improvements
- Reintroduced the help button. I also added the help button to the Tray (in Tray Mode) and moved help to the canvas action panel (in non-TrayMode) because in Obsidian 0.16.0 the status bar hides the help icon.
- Resetting the canvas with the "Reset Canvas" button will now preserve your custom color palette.
- I updated the [Set background color of unlclosed line object](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md) script. The script will now add background color to open freedraw objects as well. You no longer need to convert freedraw objects to lines before setting the background color. Check the Script Engine library to download the update.
# New in Excalidraw Automate
- I added the [ColorMaster](https://github.com/lbragile/ColorMaster#readme) library to ExcalidrawAutomate. You can get a CM object by calling ${String.fromCharCode(96)}ExcalidrawAutomate.getCM(<your color comes here>)${String.fromCharCode(96)}. Color master introduces many new ways to manipulate colors from script. I will publish scripts that make use of this new functionality including supporting videos on my YouTube channel in the coming days.
`,
"1.7.18":`
## Critical fix
- duplicating text elements, adding text elements from the library, and pasting excalidraw text elements results in a corrupted file!!`,
"1.7.17":`
## Fixed
- Block transclusions sometimes got lost when switching between RAW mode and PREVIEW mode. [#769](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/769)
## New
- Added feature to disable "new Excalidraw version" notification [#770](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/770)
- Added option to export both light- and dark-themed images at the same time. If this is enabled Excalidraw will create two files "filename.dark.png" and "filename.light.png" (or .svg depending on your other settings). See practical use case here: [Aadam's Notes](https://notes.aadam.dev/SBYNtPHqsTW9Ck1Kuoxsu/)
- Added custom export padding for PNG images. Use the frontmatter key ${String.fromCharCode(96)}excalidraw-export-padding${String.fromCharCode(96)} to set the padding at a file level, or set padding for all your files in plugin settings. The new feature replaces the old "SVG Padding" option and applies to both SVG and PNG exports.
## ExcalidrawAutomate
- Added ${String.fromCharCode(96)}padding${String.fromCharCode(96)} to the createPNG function call.
${String.fromCharCode(96, 96, 96)}typescript
async createPNG(
templatePath?: string,
scale: number = 1,
exportSettings?: ExportSettings,
loader?: EmbeddedFilesLoader,
theme?: string,
padding?: number,
)
${String.fromCharCode(96, 96, 96)}
`,
"1.7.16":`
## Fixed
- Excalidraw canvas is empty after saving the drawing and re-opening it at a later time. If you accidentally paste Excalidraw elements from the clipboard as the contents of a text element, in certain situations this can corrupt the Excalidraw file and as a result, Excalidraw will load an empty-looking drawing the next time. Changing to markdown view, these files can be repaired, however, to avoid accidental data loss, I have prevented pasting of excalidraw clipboard contents as text elements. [#768](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/768)
## New
- Add zoom % display in tray-mode [737](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/737)
`,
"1.7.15":`
## Fixed
- Canvas turns white when adding point for curved line [#760](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/760), [#738](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/738), [#5602](https://github.com/excalidraw/excalidraw/issues/5602)
`,
"1.7.14": `
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/yZQoJg2RCKI" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
## New
- The ${String.fromCharCode(96)}Copy markdown link for selected element to clipboard${String.fromCharCode(96)} action in the Obsidian menu is now more intelligent. If multiple elements are selected it will copy the Element Reference for the largest element.
- When referencing an element in a link pointing to an Excalidraw file using the elementId or the section header as the block reference e.g. ${String.fromCharCode(96)}[[file#^elementID]]${String.fromCharCode(96)}, you can now add the ${String.fromCharCode(96)}group=${String.fromCharCode(96)} prefix, e.g. ${String.fromCharCode(96)}[[file#^group=elementID]]${String.fromCharCode(96)} and the ${String.fromCharCode(96)}area=${String.fromCharCode(96)} prefix, e.g. ${String.fromCharCode(96)}[[file#area=Section heading]]${String.fromCharCode(96)}.
- If the ${String.fromCharCode(96)}group=${String.fromCharCode(96)} prefix is found, Excalidraw will select the group of elements in the same group as the element referenced by the elementID or heading section.
- If the ${String.fromCharCode(96)}area=${String.fromCharCode(96)} prefix is found, excalidraw will insert a cutout of the image around the referenced element.
- The ${String.fromCharCode(96)}area=${String.fromCharCode(96)} selector is not supported when embedding Excalidraw as PNG into your markdown documents.
- I added "Toggle left-handed mode" to the Command Palette. The action is only visible if tray-mode is enabled. It will move the tray from left to right and back. [749](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/749)
## Fixed
- Zooming with CTRL+Wheel will no longer trigger hover preview.
- When editing text in a text element CTRL+C will not launch the hover preview in case the mouse pointer is over the text element being edited. Hover preview will only show if the element is not in editing mode.
- ExcalidrawAutomate did not reliably save changes. This caused issues for example in the "Add link to an existing file and open" script. [#747](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/747)
- Create a new folder not working when clicking on a link in Erxcalidraw that points to a file that is in a folder that does not yet exist. [741](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/741)
- Downgraded to React 17 due to various stability issues, including [#738](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/738) and [#747](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/747)
## New in Excalidraw Automate
- I added two new Excalidraw Automate functions
${String.fromCharCode(96, 96, 96)}typescript
/**
* Gets the groupId for the group that contains all the elements, or null if such a group does not exist
* @param elements
* @returns null or the groupId
*/
getCommonGroupForElements(elements: ExcalidrawElement[]): string;
/**
* Gets all the elements from elements[] that share one or more groupIds with element.
* @param element
* @param elements - typically all the non-deleted elements in the scene
* @returns
*/
getElementsInTheSameGroupWithElement(element: ExcalidrawElement, elements: ExcalidrawElement[]): ExcalidrawElement[];
${String.fromCharCode(96, 96, 96)}`,
"1.7.13": `
## Fix from Excalidraw.com
- Resize multiple elements from center ([#5560](https://github.com/excalidraw/excalidraw/pull/5560))
## Obsidian 0.16.0 compatibility (getting ready, because 0.16.0 will be available to insiders soon)
- ${String.fromCharCode(96)}Install or update Excalidraw Scripts${String.fromCharCode(96)} was only available via the page header button. Because the page header is hidden by default, the install script action is now available through the pane menu and through the command palette as well.
- ${String.fromCharCode(96)}Open selected text as link${String.fromCharCode(96)} page header button is now also available via the pane menu
- ${String.fromCharCode(96)}Open in Adjacent Pane${String.fromCharCode(96)} and ${String.fromCharCode(96)}Open in Main Workspace${String.fromCharCode(96)} Excalidraw plugin settings is fixed
`,
"1.7.12": `
## New from Excalidraw.com:
- Showing a mid-point for lines and arrows. By touching the mid-point you can easily add an additional point to a two-point line. This is especially helpful when working on a tablet with touch input. ([#5534](https://github.com/excalidraw/excalidraw/pull/5534))
- Lock angle when editing a line or an arrow with SHIFT pressed. Pressing SHIFT will restrict the edited point to snap to certain discrete angles. ([#5527](https://github.com/excalidraw/excalidraw/pull/5527))
## Fixed:
- Clicking Obsidian search-results pointing to an element on the canvas works again ([#734](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/734))
- The feature to allow resizing and rotation of lines and arrows consisting of 3 or more points by showing the bounding box when selected is back ([#5554](https://github.com/excalidraw/excalidraw/pull/5554))
## New
- You can now use the following frontmatter key to allow/prevent automatic export of PNG/SVG images at a file level. This frontmatter will override export settings for the given file. ([#732](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/732)
${String.fromCharCode(96)}excalidraw-autoexport: none|both|svg|png${String.fromCharCode(96)}
`,
"1.7.11": `
## Fixed
- Markdown files embed into the Excalidraw canvas crashed when the embedded markdown file included a nested Markdown embed with a block reference (i.e. the markdown document you are dropping into Excalidraw included a quote you referenced from another file using a ${String.fromCharCode(96)}[[other-file#^blockref]]${String.fromCharCode(96)} block or section reference.
- Horizontal flipping of arrows and lines broke in 1.7.10. ([#726](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/726))
`,
"1.7.10": `
## New from Excalidraw.com
- Improved handling of arrows and lines. ([#5501](https://github.com/excalidraw/excalidraw/pull/5501))
## Fixed
- When opening a document in view-mode or zen-mode the panel buttons no longer flash up for a moment before switching to the desired mode. ([#479](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/479))
- The "blinding white screen" no longer flashes up while loading the scene if the scene is dark ([#241](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/241))
## Under the hood
- Finalized migration to React 18 (no longer showing an error about React 17 compatibility mode in console log)
`,
"1.7.9": `
## New features and fixes from Excalidraw.com:
- The right-click context menu is now scrollable on smaller screens ([#4030](https://github.com/excalidraw/excalidraw/pull/4030), [#5520](https://github.com/excalidraw/excalidraw/pull/5520))
- Holding down the shift key while rotating an object will rotate it at discrete angles. Rotation is continuous without the SHIFT key. ([#5500](https://github.com/excalidraw/excalidraw/pull/5500))
- Improved cursor alignment when resizing an element proportionally (maintain aspect ratio) by holding SHIFT during resizing. ([#5513](https://github.com/excalidraw/excalidraw/pull/5515))
- Improved freedraw performance during editing (now has proper canvas caching), and no more blurry freedraw shapes when exporting on a higher scale. ([#5481](https://github.com/excalidraw/excalidraw/pull/5481))
- Sidebar stencil library now correctly scrolls vertically ([#5459](https://github.com/excalidraw/excalidraw/pull/5459))
## New in Obsidian:
- Fullscreen mode on iPad. When there are multiple work panes open, clicking the fullscreen action in the Excalidraw Obsidian menu will hide the other work panes and make Excalidraw fullscreen.
## Fixes in Obsidian:
- Drag&Drop an image from a web browser into Excalidraw ([#697](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/697))
- On Obsidian Mobile 1.3.0, when the drawing included an embedded image, switching from markdown-view to Excalidraw-view caused the drawing to disappear (it had to be recovered from backup or synchronization history). ([#715](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/715))
- When working on a mobile device (tablet and phone) and using two work panes (one for drawing and the other for editing a markdown document) if you switched focus from the drawing to the markdown document auto-zoom changed the zoom level of the drawing. ([#723](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/723)), ([#705](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/705))
- Actions on the Command Palette to create a new drawing in a new pane or reusing an existing adjacent pane; on the main workspace or in the Hover Editor or Popout window, were not working well. See related settings in plugin settings under "Links and transclusions" ([#718](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/718))
- There was a problem with links with section references when the header contained space characters ([#704](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/704))
- I added additional controls to avoid the fantom warnings about a problem with saving the Excalidraw file. Hopefully, from now on, you'll see this error less frequently ([#701](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/701))
`,
"1.7.8": `
# Optimized for Obsidian 0.15.5
- I reworked how the plugin treats the "More options" menu because the old approach was interfering with Obsidian
- Did thorough testing of handling of work panes on link click. There are two settings (open in the adjacent pane, and open in the main workspace), and three broad scenarios (Excalidraw in a work pane in the main Obsidian window, Excalidraw in a hover editor, and Excalidraw in an Obsidian popout window). All should work correctly now.
`,
"1.7.7": `
# New
- Optimized for Obsidian 0.15.4
- On a desktop, you can now use the META key when clicking on a link and it will open the link in a new popout Window.
- ([#685](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/685)) Markdown embeds will now display correctly in Excalidraw even if they include photos and recursive markdown embeds. Unfortunately due to the limitations of Safari the inversion of colors on iPads in dark mode will not work well.
See an 18 second long demo video [here](https://user-images.githubusercontent.com/14358394/177213263-2a7ef1ca-0614-4190-8955-e830ca6b424b.mp4).
# Fixed
- ([#683](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/683)) Copy/Paste Markdown embeds to create another instance of the embed, thus you can reference different sections of the document in your drawing (something I broke in 1.7.6)
- ([#684](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/684)) Transclusions incorrectly did not pick up subsections of a section. To understand this change, imagine for example the following document:
${String.fromCharCode(96, 96, 96)}markdown
# A
abc
# B
xyz
## b1
123
## b2
456
# C
${String.fromCharCode(96, 96, 96)}
When you transclude ${String.fromCharCode(96)}![[document#B]]${String.fromCharCode(96)} you expect the following result
${String.fromCharCode(96, 96, 96)}markdown
B
xyz
b1
123
b2
456
${String.fromCharCode(96, 96, 96)}
Until this fix you only got
${String.fromCharCode(96, 96, 96)}markdown
B
xyz
${String.fromCharCode(96, 96, 96)}`,
"1.7.6": `
This release is the same as 1.7.5 except for two minor fixes
- a fix for ExcaliBrain, becuase 1.7.5 broke ExcaliBrain.
- I left out the release note from 1.7.5.
# New
- Deployed sidebar for libraries panel from excalidraw.com ([#5274](https://github.com/excalidraw/excalidraw/pull/5274)). You can dock the library to the right side depending on the screen real estate available (i.e. does not work on mobiles).
# Fixed
- When copying 2 identical images from one drawing to another, the second image got corrupted in the process ([#672]https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/672)).
- When making a copy of an equation in a drawing and then without first closing/opening the file, immediately copying the new equation to another drawing, the equation did not get displayed until the file was closed and reopened.
- Copying a markdown embed from one drawing to another, in the destination the markdown embed appeared without the section/block reference and without the width & height (i.e. these settings had to be done again)
- Improved the parsing of section references in embeds. When you had ${String.fromCharCode(96)}&${String.fromCharCode(96)} in the section name in a markdown file, when embedding that markdown document into Excalidraw, the section reference did not work as expected ([#681 ](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/681)).
- Improved the logic for autosave to better detect changes to the document, and to reduce too frequent export of ${String.fromCharCode(96)}.png${String.fromCharCode(96)} and/or ${String.fromCharCode(96)}.svg${String.fromCharCode(96)} files, when auto export is enabled in plugin settings.
`,
"1.7.5": `
# New
- Deployed sidebar for libraries panel from excalidraw.com ([#5274](https://github.com/excalidraw/excalidraw/pull/5274)). You can dock the library to the right side depending on the screen real estate available (i.e. does not work on mobiles).
# Fixed
- When copying 2 identical images from one drawing to another, the second image got corrupted in the process ([#672]https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/672)).
- When making a copy of an equation in a drawing and then without first closing/opening the file, immediately copying the new equation to another drawing, the equation did not get displayed until the file was closed and reopened.
- Copying a markdown embed from one drawing to another, in the destination the markdown embed appeared without the section/block reference and without the width & height (i.e. these settings had to be done again)
- Improved the parsing of section references in embeds. When you had ${String.fromCharCode(96)}&${String.fromCharCode(96)} in the section name in a markdown file, when embedding that markdown document into Excalidraw, the section reference did not work as expected ([#681 ](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/681)).
- Improved the logic for autosave to better detect changes to the document, and to reduce too frequent export of ${String.fromCharCode(96)}.png${String.fromCharCode(96)} and/or ${String.fromCharCode(96)}.svg${String.fromCharCode(96)} files, when auto export is enabled in plugin settings.
`,
"1.7.4": `
- Obsidian 0.15.3 support dragging and dropping work panes between Obsidian windows.
- Addressed Obsidian changes affecting the more-options menu.
- Addressed incompatibility with Obsidian Mobile 1.2.2.
`,
"1.7.3": `
Obsidian 0.15.3 support for dragging and dropping work panes between Obsidian windows.
`,
"1.7.2": `
Due to some of the changes to the code, I highly recommend restarting Obsidian after installing this update to Excalidraw.
# Fixed
- Stability improvements
- Opening links in new panes and creating new drawings from the file explorer works properly again
# New feature
- Two new command palette actions:
- Create a new drawing - IN A POPOUT WINDOW
- Create a new drawing - IN A POPOUT WINDOW - and embed into active document
![image|600](https://user-images.githubusercontent.com/14358394/175137800-88789f5d-f8e8-4371-a356-84f443aa6a50.png)
- Added setting to prefer opening the link in the popout window or in the main workspace.
![image|800](https://user-images.githubusercontent.com/14358394/175076326-1c8eee53-e512-4025-aedb-07881a732c69.png)
`,
"1.7.1": `
Support for Obsidian 0.15.0 popout windows. While there are no new features (apart from the popout window support) under the hood there were some major changes required to make this happen.
`,
"1.7.0": `
This is the first test version of Excalidraw Obsidian supporting Obsidian 0.15.0 popout windows. The current technical solution is not really sustainable, it's more of a working concept. I don't expect any real big issues with this version - on the contrary, this works much better with Obsidian 0.15.0 popout windows, but some of the features aren't working as expected in the Obsidian popouts yet. Also as a consequence of Obsidian 0.15.0 compatibility, multiple hover previews are no longer supported.
`,
"1.6.34": `
With 0.15.1 Obsidian is implementing some exciting, but significant changes to how windows are managed. I need to make some heavy/invasive changes to Excalidraw to adapt. The next version of the Excalidraw Plugin will require Obsidian 0.15.1 or newer. If you are not signed up for Obsidian Insider Builds, you will need to wait few weeks until the new Obsidian version will be made public.
# Fixed
- Error saving when the attachments folder exists but with a different letter case (i.e. ATTACHMENTS instead of attachments) [658](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/658). I added more error tolerance. As a general rule, however, I recommend treating file paths as case-sensitive as some platforms like iOS or LINUX have case-sensitive filenames, and synchronizing your Vault to these platforms will cause you headaches in the future.
- Text detached from the container if you immediately clicked the text-align buttons on the properties pane while still editing the text in the container for the very first time. [#657](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/657).
- Can't add text to the second container if the first container has text and the second container is centered around the first one. [#5300](https://github.com/excalidraw/excalidraw/issues/5300)
`,
"1.6.33": `
# Fixed
- Under some special circumstances when you embedded a drawing (guest) into another drawing (host), the host did not update when you modified the guest, until you closed Excalidraw completely and reopened the host. [#637](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/637)
# New
- ExcalidrawAutomate ${String.fromCharCode(96)}addLabelToLine${String.fromCharCode(96)} adds a text label to a line or arrow. Currently this function only works with simple straight 2-point (start & end) lines.
${String.fromCharCode(96, 96, 96)}typescript
addLabelToLine(lineId: string, label: string): string
${String.fromCharCode(96, 96, 96)}
- ExcalidrawAutomate ${String.fromCharCode(96)}ConnectObjects${String.fromCharCode(96)} now returns the ID of the arrow that was created.`,
"1.6.32": `
## Fixed
- Filenames of embedded images and markdown documents did not get updated if the drawing was open in a work-pane while you changed the filename of the embedded file (image or markdown document) [632](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/632).
- When you created a new text element and immediately dragged it, sometimes autosave interrupted the drag action and Excalidraw dropped the element you were dragging [630](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/630)
- In some edge cases when you had the drawing open on your desktop and you also opened the same image on your tablet, Sync seemed to work in the background but the changes did not appear on the desktop until you closed and opened the drawing again. [629](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/629)
- LaTeX support: Excalidraw must download a javascript library from one of the hosting sites for MathJax tex2svg. It seems that some people do not have access to the URL recommended in the first place by [MathJax](https://docs.mathjax.org/en/latest/web/start.html). If LaTeX formulas do not render correctly in Excalidraw, try changing the source server under Compatibility Settings in Excalidraw Plugin Settings. [628](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/628)`,
"1.6.31": `
Minor update:
## Fixes
- Color picker hotkeys were not working. They are working again [627](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/627)
- I updated MathJax (LaTeX) to the newest (3.2.1) release.`,
"1.6.30": `
## Fixed
- The load stencil library button stopped working after 1.6.29 due to an error in the core Excalidraw package. It is now fixed. [#625](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/625).
- On iPad (probably other Obsidian mobile devices as well) after opening the command palette the positioning of the pointer was off. From now on, the pointer is automatically re-calibrated every 5 seconds.
- I improved shared-vault collaboration sync. If the open file has not been saved for the last 5 minutes (i.e. you are not working on the drawing actively), and a newer remote version of the file is received via sync, then the remote file will simply overwrite the local file (i.e. the behavior of Excalidraw Obsidian prior to implementing Shared (Multiplayer) Vault Synchronization support in 1.6.29). This solution will support active collaboration when parties participating are actively editing the drawing, but also caters to the scenario when you open a drawing on one device (e.g. your desktop) and once you are finished editing you do not close the drawing, but simply put your PC to sleep... then later you edit the same drawing on your tablet. When you turn your desktop PC on the next time, the changes you've made on your tablet will be synchronized by Obsidian sync. In this case the changes from your tablet should be honored. If you have not edited the open drawing for more then 5 minutes (like in this scenario) there is no value in running the file comparison between the local version and the received one. This approach reduces the probability of running into sync conflicts.`,
"1.6.29": `
## New
- I implemented sync support inspired by the new [Obsidian Multiplayer Sync](https://youtu.be/ZyCPhbd51eo) feature (available in insider build v0.14.10).
- To manage expectations, this is not real-time collaboration like on Excalidraw.com. Synchronization is delayed by the frequency of the autosave timer (every 10 secs) and the speed of Obsidian sync. Also if a file has conflicting versions, Obsidian sync may delay the delivery of the changed file.
- Even if you are not using multiplayer Obsidian Vaults, you may benefit from the improved synchronization, for example when using the freedraw tool on your tablet or phone, and in parallel editing the same drawing (e.g. typing text) on your desktop. I frequently do this in a mind-mapping scenario.
- If the same Excalidraw sketch is open on multiple devices then Excalidraw will try to merge changes into the open drawing, thus parallel modifications on different devices are possible. If the same element is edited by multiple parties at the same time, then the foreign (received) version will be honored and the local changes lost.
## Fixed:
- Default embed width setting stopped working. [#622](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/622)
- The link tooltip gets stuck on screen after Excalidraw closes [#621](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/621)
- Layout error when using the Workspaces core plugin. [#28](https://github.com/zsviczian/excalibrain/issues/28)`,
"1.6.28": `
## New
- When dropping a link from a DataView query into Excalidraw the link will honor your "New link format" preferences in Obsidian. It will add the "shortest path when possible", if that is your setting. If the link includes a block or section reference, then the link will automatically include an alias, such that only the filename is displayed (shortest path possible allowing) [#610](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/610)
- If Excalidraw is in a Hover Editor and you open a link in another pane by CTRL+SHIFT+Click then the new page will open in the main workspace, and not in a split pane in the hover editor.
## Fixed
- New text elements get de-selected after auto-save [#609](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/609)
- Update opacity of bound text when the opacity of the container is updated [#5142](https://github.com/excalidraw/excalidraw/pull/5142)
- ExcalidrawAutomate: openFileInNewOrAdjacentLeaf() function. This also caused an error when clicking a link in Excalidraw in a hover window, when there were no leaves in the main workspace view.`,
"1.6.27": `
## New Features
- While these new features are benefitial for all Excalidraw Automation projects, the current changes are mainly in support of the [ExcaliBrain](https://youtu.be/O2s-h5VKCas) integration. See detailed [Release Notes](https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.6.27) on GitHub.
`,
"1.6.26": `
## Fixed
- Dragging multiple files onto the canvas will now correctly [#589](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/589)
- add multiple links
- or if you hold the CTRL/(SHIFT on Mac) while dropping the files, then adding multiple images
- Dropped images and links were not selectable with the selection tool until the file was saved. This is now fixed.
- Display the linked block/section on link-hover instead of the full page. [#597](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/597)
- Hover preview without CTRL/CMD works again. Requires configuration in plugin settings. [#595](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/595)
- If you embed the same markdown document into a drawing multiple times, you can now display different sections of the document in each embedded object. [#601](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/601).
- If you make a copy of an equation and edit this copy, the original equation will remain unchanged [#593](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/593)
## New Features
- When you drag files from Dataview-results onto the canvas the obsidian:// urls will be converted into wiki links.[#599](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/599)
- I added one more frontmatter key: ${String.fromCharCode(96)}excalidraw-linkbutton-opacity: ${String.fromCharCode(96)} This sets the opacity of the blue link-button in the top right corner of the element, overriding the respective setting in plugin settings. Valid values are numbers between 0 and 1, where 0 means the button is fully transparent.
## New Excalidraw Automate Features
- As part of building the new [ExcaliBrain](https://youtu.be/O2s-h5VKCas) plugin, I've added a number of integration features. See the GitHub [Release Notes](https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.6.26) for details.
`,
"1.6.25": `
## Fixed
- Pinch-zoom in view mode was broken ([#5001](https://github.com/excalidraw/excalidraw/pull/5001))
- The add image button on iPad was not working ([#5038](https://github.com/excalidraw/excalidraw/pull/5038) & [#584](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/584))
## New Features
- If Excalidraw is open in a [hover-editor](https://github.com/nothingislost/obsidian-hover-editor) when opening a link in a new pane Excalidraw will now open the link in the main workspace and not by splitting the view inside the hover-editor.
- Excalidraw ScriptEngine settings
- Script Engine settings now render HTML descriptions
- If the ${String.fromCharCode(96)}height${String.fromCharCode(96)} property of a text setting is set, the corresponding text input field will be rendered as a textArea with the specified height.
`,
"1.6.24": `
## Fixed
- Link fixes:
- Shift+Click on an element link (i.e. a link attached to a rectangle, ellipse, etc) did not open the link in a new leaf.
- Clicking a link and opening it in a new leaf will now make the new leaf active and focused after the click.
- Pointer calibration:
- Opening an Excalidraw drawing with the [hover-editor](https://github.com/nothingislost/obsidian-hover-editor) and dragging the editor to another location corrupted the calibration of the pointer in Excalidraw. Similarly, when rearranging workspace panes by dragging, Excalidraw lost pointer calibration.
## New Features
### From Excalidraw.com
- Element locking: The lock and unlock action is in the context menu.
### Plugin
- Any element that has a link, ctrl/cmd+clicking anywhere on the object will trigger the link action. You no longer have to go to the link icon. ([#541](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/541#issuecomment-1075578365))
`,
"1.6.23": `
## Fixed:
- I have received some user feedback about cases where the text separated from the sticky note. This version comes with a cleanup algorithm that will try to automatically resolve these issues.
- Autosave did not notice changes in a very obscure case, when you opened a drawing, resized an element, and without deselecting the element you immediately closed the drawing. ([565](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/565))
- CTRL+Enter to create a task did not work in hover-editor when opened from Excalidraw. Now it does! Thanks @pjeby! ([567](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/567))
## New Features
- If you have the [Obsidian-Latex](https://github.com/xldenis/obsidian-latex) plugin installed, from now Excalidraw will also process the ${String.fromCharCode(
96,
)}preambles.sty${String.fromCharCode(
96,
)} file. ( [563](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/563))
- I added a new setting ${String.fromCharCode(
96,
)}Embed & Export >> If found, use the already exported image for preview${String.fromCharCode(
96,
)}. This setting works in conjunction with the ${String.fromCharCode(
96,
)}Auto-export SVG/PNG${String.fromCharCode(
96,
)} settings. If an exported image that matches the file name of the drawing is available, use that image instead of generating a preview image on the fly. This will result in faster previews especially when you have many embedded objects in the drawing, however, it may happen that your latest changes are not displayed and that the image will not automatically match your Obsidian theme in case you have changed the Obsidian theme since the export was created. This setting only applies to embedding images into markdown documents. For a number of reasons, the same approach cannot be used to expedite the loading of drawings with many embedded objects. See release notes for a [demo video](https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.6.22).
`,
"1.6.22": `
## Fixed:
- "Create a new drawing - IN THE CURRENT ACTIVE PANE - and embed into active document" did not work as intended when an Excalidraw pane was already open. [#559](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/559)
- [Obsidian-hover-editor](https://github.com/nothingislost/obsidian-hover-editor) related improvements [#555](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/555):
- hovering triggered many hover preview windows in quick succession, and in some cases raised dozens of errors in the Developer Console
- hover-editors were not visible in Excalidraw fullscreen mode
## Minor new features:
- Activating the eraser with key "e" will toggle the active tool and back. So for example if you are drawing a freedraw shape, you can press "e" to delete a few strokes, then press "e" again to continue drawing. On desktop PCs many styluses allow you to configure the pen button to trigger keypress "e".
- New setting to enable penMode by default.
- I increased the file size limit for images you paste into Excalidraw from 2MB to 20MB. You should however avoid very large images as they will impact the overall performance of the canvas. ([#557](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/557))
`,
"1.6.21": `
Before I move on to implementing further features, I spent this week with further stabilizing and debugging the plugin. Hopefully this will result in a smoother, better experince for you all.
## Fixed
- Links in drawings (e.g. text elements or embedded images) were sometimes not updating when the source file was moved or renamed in your Vault. The issue happend when you had the drawing and the linked file open in panes next to each other. This has led to broken links. ([#546](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/546))
- To remove complexity and potential error, I have hidden the autosave settings. From now, autosave is now always enabled. Excalidraw will attempt to save your drawing every 10 seconds, or if you are actively engaged in drawing a shape at that very moment (e.g. you are busy with a freedraw line), then autosave will save the drawing at the earliest next opportunity. I imlemented further triggers to save the drawing when there are changes in the drawing and you click outside the drawing canvas. There was a rare error involving text elements, that when happened blocked saving of the file. This error is now properly handeled. Also from now, you will receive a warning message if for any reason save encountered problems.
- If you have two heading sections in your drawing, e.g. ${String.fromCharCode(
96,
)}# Section abc${String.fromCharCode(96)} and ${String.fromCharCode(
96,
)}# Section abc def${String.fromCharCode(
96,
)}, then referencing ${String.fromCharCode(
96,
)}[[#Section abc]]${String.fromCharCode(
96,
)} in a link will highlight both text elements when clicking the link. These section references now work as expected. ([#530](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/530))`,
"1.6.20": `
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/U2LkBRBk4LY" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
## Fixed
- ${String.fromCharCode(96)}ExcalidrawAutomate.create()${String.fromCharCode(
96,
)} threw an error [539](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/539)
## New Features
### From excalidraw.com
- Bind/unbind text to/from container [4935](https://github.com/excalidraw/excalidraw/pull/4935)
### Plugin
Frontmatter tags to customize image export at a file level [519](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/519). If these keys are present they will override the default excalidraw embed and export settings.
- ${String.fromCharCode(
96,
)}excalidraw-export-transparent: true${String.fromCharCode(96)}
- true == Transparent / false == with background.
- ${String.fromCharCode(96)}excalidraw-export-dark${String.fromCharCode(96)}
- true == Dark mode / false == light mode.
- ${String.fromCharCode(96)}excalidraw-export-svgpadding${String.fromCharCode(
96,
)}
- This only affects export to SVG. Specify the export padding for the image
- ${String.fromCharCode(96)}excalidraw-export-pngscale${String.fromCharCode(96)}
- 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.
`,
"1.6.19": `
This is a minor update fixing left-handed mode on iOS, and deploying improvements to the new Excalidraw Eraser.
`,
"1.6.18": `
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/4N6efq1DtH0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
## Fixed
- Modifying properties of a text element in tray mode. [496](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/496)
- Friendly page aliases with iframely should work more reliably now.
- I further improved resilience of loading from a damaged Excalidraw.md file.
## New Features
### From excalidraw.com
- Added Eraser [4887](https://github.com/excalidraw/excalidraw/pull/4887)
### Plugin
- New setting for default transcluded-text line-wrap length. This is the default value for "wrapAt" in ${String.fromCharCode(
96,
)}![[file#^block]]{wrapAt}${String.fromCharCode(
96,
)}. Wrapping text using this feature will insert linebreaks in the transcluded text. An alternative approach is to transclude text inside sticky notes, in which case Excalidraw will automatically take care of text wrapping depending on the sticky note's width. [228](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/228)
- New command palette action to toggle fullscreen mode, so you can assign a hotkey.
- I added basic support for left-handed users. Enable it in plugin settings under the "Display" section. Currently, only affects the position of the tray in tray-mode. [510](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/510)
- More flexible filename settings. ⚠ Due to the change, current settings may behave slightly differently compared to before. ⚠ [470](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/470)
`,
"1.6.17": `
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/Etskjw7a5zo" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
## Fixed
- Freedraw shape's background color was missing in the SVG export. [#443](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/443)
- In rare cases, when you only changed the background color of the drawing or edited the dimensions of an embedded markdown document, or changed an existing LaTeX formula, and then moved to another document in the vault, these changes did not get saved. [#503](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/503)
- I resolved an Excalidraw Automate glitch with word wrapping in containers. EA generated containers with fixed line breaks. The same error also affected the conversion of drawings from the "legacy" Excalidraw.com file format.
- When you allow/disable autosave in settings, this change will immediately take effect for all open Excalidraw workspace leaves. Until now autosave was activated only after you closed and reopened the Excalidraw view. [#502](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/502)
- When you create a text element containing a ${String.fromCharCode(
96,
96,
96,
)}[[markdown link]]${String.fromCharCode(
96,
96,
96,
)} in raw mode, the new link was parsed nonetheless, and sometimes the link disappeared, leaving only the parsed text without the actual link. Creating links in raw-mode now works correctly.
## New Features
- The most recent 5 custom colors from the canvas are now added as color options to the element stroke and element background palette. [#4843](https://github.com/excalidraw/excalidraw/pull/4843)
- Vertical text alignment for text in sticky notes [#4852](https://github.com/excalidraw/excalidraw/pull/4852)
- Markdown embeds into Excalidraw now receive default styling, including that of tables, blockquotes, and code blocks. I also added a new setting and corresponding frontmatter-key to set the border-color for the embedded markdown document. You can override plugin settings at the document level by adding ${String.fromCharCode(
96,
96,
96,
)}excalidraw-border-color: steelblue${String.fromCharCode(
96,
96,
96,
)} to the markdown document you want to embed into your drawing. Valid values are css-color-name|#HEXcolor|any-other-html-standard-format.
- In Obsidian search, when the text you were searching for is found in an Excalidraw document, clicking the link in search-results will open the drawing with the matching text element selected and zoomed.
- Excalidraw now supports linking to text elements on the canvas and linking to non-text objects.
1) You can reference text headings just the same as markdown headings in a document
i.e. you have a text element that includes a valid markdown heading:
${String.fromCharCode(96, 96, 96)}markdown
# My Heading
details...
${String.fromCharCode(96, 96, 96)}
or
${String.fromCharCode(96, 96, 96)}markdown
text element text
# my reference
${String.fromCharCode(96, 96, 96)}
You can reference these like this respectively: ${String.fromCharCode(
96,
96,
96,
)}[[#My Heading|display alias]]${String.fromCharCode(
96,
96,
96,
)} and ${String.fromCharCode(
96,
96,
96,
)}[[#my reference|alias]]${String.fromCharCode(96, 96, 96)}
![image](https://user-images.githubusercontent.com/14358394/156890231-5a23bcb3-40a4-4ad7-b366-74c328620159.png)
2) You can also reference element ids similar to block references
- Links take this form ${String.fromCharCode(
96,
96,
96,
)}[[#^elementID|alias]]${String.fromCharCode(96, 96, 96)}
- Linking is supported by a new action on the Obsidian Tools Panel
![image](https://user-images.githubusercontent.com/14358394/156894011-6442c3d6-aaff-43a8-bd77-513e450484ba.png)
[Release Notes on GitHub](https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.6.17)
`,
"1.6.16": `
<div class="excalidraw-videoWrapper"><div>
<iframe src="https://www.youtube.com/embed/gMIKXyhS-dM" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></div>
## Fixed
- CMD+Drag from the Obsidian File Manager does not work on Mac. You can now use SHIFT+Drag to embed an image or markdown document into a scene. ([#468](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/468))
- Excalidraw Compressed JSON is now cut to smaller chunks (64 characters per paragraph, instead of the earlier 1024 characters). This should address search performance issues. ([#484](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/484))
## New Features
- I added the Obsidian Tools Panel
- Click the Obsidian button to access the panel.
- The tools panel contains key plugin commands and user / downloaded Excalidraw scripts.
- Drag the panel with the handle at the top. Single click on the top to collapse the panel.
- On Mobile press and hold the drag handle before dragging, to avoid activating the Obsidian slide in menus.
- On Mobile long touch individual buttons on the panel to access tooltips.
- Reinstall Excalidraw scripts to get the icons.
- If you hold down SHIFT while resizing a sticky note, the text size will scale instead of text wrapping. ([Excalidraw tweet](https://twitter.com/aakansha1216/status/1496116528890417155?s=20&t=taXjA6I9Nd0T-C0wYBsG5g))
- SVG export now includes links ([#4791](https://github.com/excalidraw/excalidraw/pull/4791))
- Added full screen mode for Obsidian Mobile
- Release notes
- disable popup in settings
- access release notes via the command palette, or the button on the tools panel
[Release Notes on GitHub](https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.6.16)
[![support-membership](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/support-tiers.jpg)](https://ko-fi.com/zsolt)
`,
};

View File

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

View File

@@ -12,8 +12,9 @@ import {
import ExcalidrawView from "../ExcalidrawView";
import ExcalidrawPlugin from "../main";
import { sleep } from "../utils/Utils";
import { getNewOrAdjacentLeaf } from "../utils/ObsidianUtils";
import { getLeaf, getNewOrAdjacentLeaf } from "../utils/ObsidianUtils";
import { checkAndCreateFolder, splitFolderAndFilename } from "src/utils/FileUtils";
import { KeyEvent, PaneTarget } from "src/utils/ModifierkeyHelper";
export class Prompt extends Modal {
private promptEl: HTMLInputElement;
@@ -370,8 +371,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 +387,8 @@ export class NewFileActions extends Modal {
if (!file) {
return;
}
const leaf = this.newWindow
//@ts-ignore
? app.workspace.openPopoutLeaf()
: this.newPane
? getNewOrAdjacentLeaf(this.plugin, this.view.leaf)
: this.view.leaf;
const leaf = getLeaf(this.plugin,this.view.leaf,this.keys)
leaf.openFile(file, {active:true});
//this.app.workspace.setActiveLeaf(leaf, true, true);
}
createForm(): void {

View File

@@ -528,6 +528,12 @@ export const EXCALIDRAW_SCRIPTENGINE_INFO: SuggesterInfo[] = [
desc: "Opens a suggester. Displays the displayItems and returns the corresponding item from items[]\nYou need to await the result of suggester.\nIf the user cancels (ESC), suggester will return undefined\nHint and instructions are optional\n\n<code>interface Instruction {command: string;purpose: string;}</code>",
after: "",
},
{
field: "scriptFile",
code: "scriptFile: TFile",
desc: "The TFile of the currently running script",
after: "",
},
];
export const FRONTMATTER_KEYS_INFO: SuggesterInfo[] = [

View File

@@ -1,48 +1,55 @@
import {
DEVICE,
FRONTMATTER_KEY_CUSTOM_LINK_BRACKETS,
FRONTMATTER_KEY_CUSTOM_PREFIX,
FRONTMATTER_KEY_CUSTOM_URL_PREFIX,
} from "src/Constants";
import { labelALT, labelCTRL, labelMETA, labelSHIFT } from "src/utils/ModifierkeyHelper";
// English
export default {
// main.ts
INSTALL_SCRIPT: "Install this script",
UPDATE_SCRIPT: "An update is available - Click to install",
INSTALL_SCRIPT: "Install the script",
UPDATE_SCRIPT: "Update available - Click to install",
CHECKING_SCRIPT:
"Checking if a newer version is available - Click to reinstall now",
"Checking for newer version - Click to reinstall",
UNABLETOCHECK_SCRIPT:
"Update check was unsuccessful - Click to reinstall now",
"Update check failed - Click to reinstall",
UPTODATE_SCRIPT:
"Script is installed and up to date - Click to reinstall now",
"Script is up to date - Click to reinstall",
OPEN_AS_EXCALIDRAW: "Open as Excalidraw Drawing",
TOGGLE_MODE: "Toggle between Excalidraw and Markdown mode",
CONVERT_NOTE_TO_EXCALIDRAW: "Convert empty note to Excalidraw Drawing",
CONVERT_EXCALIDRAW: "Convert *.excalidraw to *.md files",
CREATE_NEW: "New Excalidraw drawing",
CREATE_NEW: "Create new drawing",
CONVERT_FILE_KEEP_EXT: "*.excalidraw => *.excalidraw.md",
CONVERT_FILE_REPLACE_EXT: "*.excalidraw => *.md (Logseq compatibility)",
DOWNLOAD_LIBRARY: "Export stencil library as an *.excalidrawlib file",
OPEN_EXISTING_NEW_PANE: "Open an existing drawing - IN A NEW PANE",
OPEN_EXISTING_NEW_PANE: "Open existing drawing - IN A NEW PANE",
OPEN_EXISTING_ACTIVE_PANE:
"Open an existing drawing - IN THE CURRENT ACTIVE PANE",
TRANSCLUDE: "Transclude (embed) a drawing",
TRANSCLUDE_MOST_RECENT: "Transclude (embed) the most recently edited drawing",
"Open existing drawing - IN THE CURRENT ACTIVE PANE",
TRANSCLUDE: "Embed a drawing",
TRANSCLUDE_MOST_RECENT: "Embed the most recently edited drawing",
TOGGLE_LEFTHANDED_MODE: "Toggle left-handed mode",
NEW_IN_NEW_PANE: "Create a new drawing - IN A NEW PANE",
NEW_IN_ACTIVE_PANE: "Create a new drawing - IN THE CURRENT ACTIVE PANE",
NEW_IN_POPOUT_WINDOW: "Create a new drawing - IN A POPOUT WINDOW",
NEW_IN_NEW_PANE: "Create new drawing - IN AN ADJACENT WINDOW",
NEW_IN_NEW_TAB: "Create new drawing - IN A NEW TAB",
NEW_IN_ACTIVE_PANE: "Create new drawing - IN THE CURRENT ACTIVE WINDOW",
NEW_IN_POPOUT_WINDOW: "Create new drawing - IN A POPOUT WINDOW",
NEW_IN_NEW_PANE_EMBED:
"Create a new drawing - IN A NEW PANE - and embed into active document",
"Create new drawing - IN AN ADJACENT WINDOW - and embed into active document",
NEW_IN_NEW_TAB_EMBED:
"Create new drawing - IN A NEW TAB - and embed into active document",
NEW_IN_ACTIVE_PANE_EMBED:
"Create a new drawing - IN THE CURRENT ACTIVE PANE - and embed into active document",
NEW_IN_POPOUT_WINDOW_EMBED: "Create a new drawing - IN A POPOUT WINDOW - and embed into active document",
EXPORT_SVG: "Save as SVG next to the current file",
EXPORT_PNG: "Save as PNG next to the current file",
TOGGLE_LOCK: "Toggle Text Element edit RAW/PREVIEW",
DELETE_FILE: "Delete selected Image or Markdown file from Obsidian Vault",
"Create new drawing - IN THE CURRENT ACTIVE WINDOW - and embed into active document",
NEW_IN_POPOUT_WINDOW_EMBED: "Create new drawing - IN A POPOUT WINDOW - and embed into active document",
EXPORT_SVG: "Save as SVG next to current file",
EXPORT_PNG: "Save as PNG next to current file",
EXPORT_SVG_WITH_SCENE: "Save as SVG with embedded Excalidraw Scene next to current file",
EXPORT_PNG_WITH_SCENE: "Save as PNG with embedded Excalidraw Scene next to current file",
TOGGLE_LOCK: "Toggle Text Element between edit RAW and PREVIEW",
DELETE_FILE: "Delete selected image or Markdown file from Obsidian Vault",
INSERT_LINK_TO_ELEMENT:
"Copy markdown link for selected element to clipboard. CTRL/CMD+Click to copy group link. SHIFT+click to copy an area link.",
`Copy markdown link for selected element to clipboard. ${labelCTRL()}+CLICK to copy 'group=' link. ${labelSHIFT()}+CLICK to copy an 'area=' link. ${labelALT()}+CLICK to watch a help video.`,
INSERT_LINK_TO_ELEMENT_GROUP:
"Copy 'group=' markdown link for selected element to clipboard.",
INSERT_LINK_TO_ELEMENT_AREA:
@@ -56,7 +63,7 @@ export default {
IMPORT_SVG: "Import an SVG file as Excalidraw strokes (limited SVG support, TEXT currently not supported)",
INSERT_MD: "Insert markdown file from vault",
INSERT_LATEX:
"Insert LaTeX formula (e.g. \\binom{n}{k} = \\frac{n!}{k!(n-k)!})",
`Insert LaTeX formula (e.g. \\binom{n}{k} = \\frac{n!}{k!(n-k)!}). ${labelALT()}+CLICK to watch a help video.`,
ENTER_LATEX: "Enter a valid LaTeX expression",
READ_RELEASE_NOTES: "Read latest release notes",
RUN_OCR: "OCR: Grab text from freedraw scribble and pictures to clipboard",
@@ -69,18 +76,14 @@ export default {
//ExcalidrawView.ts
INSTALL_SCRIPT_BUTTON: "Install or update Excalidraw Scripts",
OPEN_AS_MD: "Open as Markdown",
SAVE_AS_PNG: "Save as PNG into Vault (CTRL/CMD+CLICK to export)",
SAVE_AS_SVG: "Save as SVG into Vault (CTRL/CMD+CLICK to export)",
SAVE_AS_PNG: `Save as PNG into Vault (${labelCTRL()}+CLICK to export; SHIFT to embed scene)`,
SAVE_AS_SVG: `Save as SVG into Vault (${labelCTRL()}+CLICK to export; SHIFT to embed scene)`,
OPEN_LINK: "Open selected text as link\n(SHIFT+CLICK to open in a new pane)",
EXPORT_EXCALIDRAW: "Export to an .Excalidraw file",
LINK_BUTTON_CLICK_NO_TEXT:
"Select a an ImageElement, or select a TextElement that contains an internal or external link.\n" +
"SHIFT CLICK this button to open the link in a new pane.\n" +
"CTRL/CMD CLICK the Image or TextElement on the canvas has the same effect!",
"Select a an 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)",
@@ -196,6 +199,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 +220,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 +228,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 +257,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,7 +292,7 @@ FILENAME_HEAD: "Filename",
"Use the <code>http://iframely.server.crestify.com/iframely?url=</code> to get title of page when dropping a link into Excalidraw",
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:
@@ -311,7 +324,7 @@ 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. " +
@@ -361,7 +374,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 +410,10 @@ 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.",
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.",
@@ -432,7 +449,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 +458,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",

View File

@@ -74,8 +74,6 @@ export default {
"您也可以直接在画布中按住 CTRL/CMD 并点击图形或文本元素来打开链接。",
FILENAME_INVALID_CHARS:
'文件名不能含有以下符号: * " \\ < > : | ? #',
FILE_DOES_NOT_EXIST:
"文件不存在。按住 ALT或 ALT + SHIFT并点击链接来创建新文件。",
FORCE_SAVE:
"立刻保存该绘图(并更新嵌入了该绘图的面板)。\n详见插件设置中的定期保存选项",
RAW: "文本元素正以原文RAW模式显示链接。\n点击切换到预览PREVIEW模式",

View File

@@ -16,7 +16,8 @@ import {
request,
MetadataCache,
FrontMatterCache,
Command
Command,
requireApiVersion
} from "obsidian";
import {
BLANK_DRAWING,
@@ -35,7 +36,6 @@ import {
JSON_parse,
nanoid,
DARK_BLANK_DRAWING,
CTRL_OR_CMD,
SCRIPT_INSTALL_CODEBLOCK,
SCRIPT_INSTALL_FOLDER,
VIRGIL_FONT,
@@ -96,6 +96,7 @@ import {
markdownPostProcessor,
observer,
} from "./MarkdownPostProcessor";
import { FieldSuggester } from "./dialogs/FieldSuggester";
import { ReleaseNotes } from "./dialogs/ReleaseNotes";
import { decompressFromBase64 } from "lz-string";
@@ -104,6 +105,8 @@ import * as React from "react";
import { ScriptInstallPrompt } from "./dialogs/ScriptInstallPrompt";
import { check } from "prettier";
import Taskbone from "./ocr/Taskbone";
import { hoverEvent_Legacy, initializeMarkdownPostProcessor_Legacy, markdownPostProcessor_Legacy, observer_Legacy } from "./MarkdownPostProcessor_Legacy";
import { isCTRL, PaneTarget } from "./utils/ModifierkeyHelper";
declare module "obsidian" {
@@ -157,7 +160,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 }> =
null; //fileId, path
public equationsMaster: Map<FileId, string> = null; //fileId, formula
public mathjax: any = null;
@@ -168,23 +171,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 }
>();
this.equationsMaster = new Map<FileId, string>();
}
@@ -208,18 +200,6 @@ 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);
@@ -238,7 +218,11 @@ export default class ExcalidrawPlugin extends Plugin {
//Compatibility mode with .excalidraw files
this.registerExtensions(["excalidraw"], VIEW_TYPE_EXCALIDRAW);
this.addMarkdownPostProcessor();
if(requireApiVersion("1.1.6")) {
this.addMarkdownPostProcessor();
} else {
this.addLegacyMarkdownPostProcessor();
}
this.registerInstallCodeblockProcessor();
this.addThemeObserver();
this.experimentalFileTypeDisplayToggle(this.settings.experimentalFileType);
@@ -417,7 +401,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 +447,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 +461,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 () => {
@@ -608,6 +593,18 @@ export default class ExcalidrawPlugin extends Plugin {
this.observer.observe(document, { childList: true, subtree: true });
}
private addLegacyMarkdownPostProcessor() {
initializeMarkdownPostProcessor_Legacy(this);
this.registerMarkdownPostProcessor(markdownPostProcessor_Legacy);
// internal-link quick preview
this.registerEvent(this.app.workspace.on("hover-link", hoverEvent_Legacy));
//monitoring for div.popover.hover-popover.file-embed.is-loaded to be added to the DOM tree
this.observer = observer_Legacy;
this.observer.observe(document, { childList: true, subtree: true });
}
private addThemeObserver() {
this.themeObserver = new MutationObserver(async (m: MutationRecord[]) => {
if (!this.settings.matchThemeTrigger) {
@@ -709,7 +706,7 @@ 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",
isCTRL(e)?"new-pane":"active-pane",
); //.ctrlKey||e.metaKey);
});
@@ -857,6 +854,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 +882,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) {
@@ -913,6 +918,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"),
@@ -955,6 +972,24 @@ export default class ExcalidrawPlugin extends Plugin {
},
});
this.addCommand({
id: "export-svg-scene",
name: t("EXPORT_SVG_WITH_SCENE"),
checkCallback: (checking: boolean) => {
if (checking) {
return (
Boolean(this.app.workspace.getActiveViewOfType(ExcalidrawView))
);
}
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (view) {
view.saveSVG(undefined,true);
return true;
}
return false;
},
});
this.addCommand({
id: "run-ocr",
name: t("RUN_OCR"),
@@ -1035,6 +1070,24 @@ export default class ExcalidrawPlugin extends Plugin {
},
});
this.addCommand({
id: "export-png-scene",
name: t("EXPORT_PNG_WITH_SCENE"),
checkCallback: (checking: boolean) => {
if (checking) {
return (
Boolean(this.app.workspace.getActiveViewOfType(ExcalidrawView))
);
}
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
if (view) {
view.savePNG(undefined, true);
return true;
}
return false;
},
});
this.forceSaveCommand = this.addCommand({
id: "save",
hotkeys: [{modifiers: ["Ctrl"], key:"s"}], //See also Poposcope
@@ -2109,16 +2162,18 @@ export default class ExcalidrawPlugin extends Plugin {
public openDrawing(
drawingFile: TFile,
location: "active-pane"|"new-pane"|"popout-window",
location: PaneTarget,
active: boolean = false,
subpath?: string
) {
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 +2185,7 @@ export default class ExcalidrawPlugin extends Plugin {
!subpath || subpath === ""
? {active}
: { active, eState: { subpath } }
);
/* leaf.setViewState({
type: VIEW_TYPE_EXCALIDRAW,
state: { file: drawingFile.path, eState: {subpath}},
});*/
)
}
public async getBlankDrawing(): Promise<string> {
@@ -2236,7 +2286,7 @@ 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> {

View File

@@ -3,7 +3,8 @@ import ExcalidrawView from "../ExcalidrawView";
type ButtonProps = {
title: string;
action: Function;
action: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
longpress?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
icon: JSX.Element;
view: ExcalidrawView;
};
@@ -14,6 +15,7 @@ type ButtonState = {
export class ActionButton extends React.Component<ButtonProps, ButtonState> {
toastMessageTimeout: number = 0;
longpressTimeout: number = 0;
constructor(props: ButtonProps) {
super(props);
@@ -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">

View File

@@ -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="currentColor"
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="currentColor"
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="currentColor"
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="currentColor"
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="currentColor"
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="currentColor"
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"
@@ -441,6 +545,95 @@ export const ICONS = {
/>
</g>
</svg>
),
obsidian: (
<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>
)
};
@@ -462,6 +655,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,"")

View File

@@ -1,125 +1,251 @@
import { AppState } from "@zsviczian/excalidraw/types/types";
import { AppState, ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/types";
import clsx from "clsx";
import { TFile } from "obsidian";
import * as React from "react";
import { VIEW_TYPE_EXCALIDRAW } from "src/Constants";
import { PenSettingsModal } from "src/dialogs/PenSettingsModal";
import ExcalidrawView from "src/ExcalidrawView";
import { PenStyle } from "src/PenTypes";
import { PENS } from "src/utils/Pens";
import ExcalidrawPlugin from "../main";
import { ICONS, penIcon, stringToSVG } from "./ActionIcons";
declare const PLUGIN_VERSION:string;
export const setPen = (pen: PenStyle, api: any) => {
const st = api.getAppState();
api.updateScene({
appState: {
currentStrokeOptions: pen.penOptions,
...(!pen.strokeWidth || (pen.strokeWidth === 0)) ? null : {currentItemStrokeWidth: pen.strokeWidth},
...pen.backgroundColor ? {currentItemBackgroundColor: pen.backgroundColor} : null,
...pen.strokeColor ? {currentItemStrokeColor: pen.strokeColor} : null,
...pen.fillStyle === "" ? null : {currentItemFillStyle: pen.fillStyle},
...pen.roughness ? null : {currentItemRoughness: pen.roughness},
...pen.freedrawOnly && !st.resetCustomPen //switching from custom pen to next custom pen
? {
resetCustomPen: {
currentItemStrokeWidth: st.currentItemStrokeWidth,
currentItemBackgroundColor: st.currentItemBackgroundColor,
currentItemStrokeColor: st.currentItemStrokeColor,
currentItemFillStyle: st.currentItemFillStyle,
currentItemRoughness: st.currentItemRoughness,
}}
: null,
}
})
}
export const resetStrokeOptions = (resetCustomPen:any, api: ExcalidrawImperativeAPI, clearCurrentStrokeOptions: boolean) => {
api.updateScene({
appState: {
...resetCustomPen ? {
currentItemStrokeWidth: resetCustomPen.currentItemStrokeWidth,
currentItemBackgroundColor: resetCustomPen.currentItemBackgroundColor,
currentItemStrokeColor: resetCustomPen.currentItemStrokeColor,
currentItemFillStyle: resetCustomPen.currentItemFillStyle,
currentItemRoughness: resetCustomPen.currentItemRoughness,
}: null,
resetCustomPen: null,
...clearCurrentStrokeOptions ? {currentStrokeOptions: null} : null,
}
});
}
export class ObsidianMenu {
plugin: ExcalidrawPlugin;
toolsRef: React.MutableRefObject<any>;
private clickTimestamp:number[];
private activePen: PenStyle;
constructor(
private plugin: ExcalidrawPlugin,
private toolsRef: React.MutableRefObject<any>,
private view: ExcalidrawView
) {
this.clickTimestamp = Array.from({length: Object.keys(PENS).length}, () => 0);
}
constructor(plugin: ExcalidrawPlugin, toolsRef: React.MutableRefObject<any>) {
this.plugin = plugin;
this.toolsRef = toolsRef;
renderCustomPens = (isMobile: boolean, appState: AppState) => {
return(
appState.customPens?.map((key,index)=>{
const pen = this.plugin.settings.customPens[index]
//Reset stroke setting when changing to a different tool
if(
appState.resetCustomPen &&
appState.activeTool.type !== "freedraw" &&
appState.currentStrokeOptions === pen.penOptions
) {
setTimeout(()=> resetStrokeOptions(appState.resetCustomPen, this.view.excalidrawAPI, false))
}
//if Pen settings are loaded, select custom pen when activating the freedraw element
if (
!appState.resetCustomPen &&
appState.activeTool.type === "freedraw" &&
appState.currentStrokeOptions === pen.penOptions &&
pen.freedrawOnly
) {
setTimeout(()=>setPen(this.activePen,this.view.excalidrawAPI));
}
if(
this.activePen &&
appState.resetCustomPen &&
appState.activeTool.type === "freedraw" &&
appState.currentStrokeOptions === pen.penOptions &&
pen.freedrawOnly
) {
this.activePen.strokeWidth = appState.currentItemStrokeWidth;
this.activePen.backgroundColor = appState.currentItemBackgroundColor;
this.activePen.strokeColor = appState.currentItemStrokeColor;
this.activePen.fillStyle = appState.currentItemFillStyle;
this.activePen.roughness = appState.currentItemRoughness;
}
return (
<label
key={index}
className={clsx(
"ToolIcon ToolIcon_type_floating",
"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>
)
})
)
}
renderPinnedScriptButtons = (isMobile: boolean, appState: AppState) => {
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;
let longpressTimout = 0;
return (
<label
key = {index}
className={clsx(
"ToolIcon ToolIcon_type_floating",
"ToolIcon_size_medium",
{
"is-mobile": isMobile,
},
)}
onClick={() => {
if(longpressTimout) {
window.clearTimeout(longpressTimout);
longpressTimout = 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={()=>{
longpressTimout = window.setTimeout(
() => {
longpressTimout = 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
)
}}
>
<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_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">
{ICONS.obsidian}
</div>
</label>
{this.renderCustomPens(isMobile,appState)}
{this.renderPinnedScriptButtons(isMobile,appState)}
</>
);
};
}

View File

@@ -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,8 @@ 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";
declare const PLUGIN_VERSION:string;
const dark = '<svg style="stroke:#ced4da;#212529;color:#ced4da;fill:#ced4da" ';
@@ -376,7 +378,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 +386,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 +404,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}
@@ -514,7 +516,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 +544,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 +594,72 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
return "";
}
const groups = new Set<string>();
Object.keys(this.state.scriptIconMap)
.filter((k) => filterCondition(k))
.forEach(k => groups.add(this.state.scriptIconMap[k].group))
const scriptlist = Array.from(groups).sort((a,b)=>a>b?1:-1);
scriptlist.push(scriptlist.shift());
return (
<fieldset>
<legend>{isDownloaded ? "Downloaded" : "User"} Scripts</legend>
<div className="buttonList buttonListIcon">
{Object.keys(this.state.scriptIconMap)
.filter((k) => filterCondition(k))
.sort()
.map((key: string) => (
<ActionButton
key={key}
title={
isDownloaded
? this.state.scriptIconMap[key].name.replace(
`${SCRIPT_INSTALL_FOLDER}/`,
"",
)
: this.state.scriptIconMap[key].name
}
action={async () => {
const f =
this.props.view.app.vault.getAbstractFileByPath(key);
if (f && f instanceof TFile) {
this.props.view.plugin.scriptEngine.executeScript(
this.props.view,
await this.props.view.plugin.app.vault.read(f),
this.props.view.plugin.scriptEngine.getScriptName(f)
);
<>
{scriptlist.map(group => (
<fieldset>
<legend>{isDownloaded ? group : (group === "" ? "User" : "User/"+group)}</legend>
<div className="buttonList buttonListIcon">
{Object.entries(this.state.scriptIconMap)
.filter(([k,v])=>v.group === group)
.sort()
.map(([key,value])=>(
<ActionButton
key={key}
title={value.name}
action={async () => {
const view = this.props.view;
const plugin = view.plugin;
const f = app.vault.getAbstractFileByPath(key);
if (f && f instanceof TFile) {
plugin.scriptEngine.executeScript(
view,
await app.vault.read(f),
plugin.scriptEngine.getScriptName(f),
f
);
}
}}
longpress={async () => {
const view = this.props.view;
const api = view.excalidrawAPI as ExcalidrawImperativeAPI;
const plugin = view.plugin;
await plugin.loadSettings();
const index = plugin.settings.pinnedScripts.indexOf(key)
if(index > -1) {
plugin.settings.pinnedScripts.splice(index,1);
api?.setToast({message:`Pin removed: ${value.name}`, duration: 3000, closable: true});
} else {
plugin.settings.pinnedScripts.push(key);
api?.setToast({message:`Pinned: ${value.name}`, duration: 3000, closable: true})
}
await plugin.saveSettings();
app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW).forEach(v=> {
if (v.view instanceof ExcalidrawView) v.view.updatePinnedScripts()
})
}}
icon={
value.svgString
? stringToSVG(value.svgString)
: (
ICONS.cog
)
}
}}
icon={
this.state.scriptIconMap[key].svgString
? stringToSVG(this.state.scriptIconMap[key].svgString)
: (
ICONS.cog
)
}
view={this.props.view}
/>
))}
</div>
</fieldset>
view={this.props.view}
/>
))}
</div>
</fieldset>
))}
</>
);
}
}

View File

@@ -11,10 +11,12 @@ import { VIEW_TYPE_EXCALIDRAW } from "./Constants";
import ExcalidrawView from "./ExcalidrawView";
import { t } from "./lang/helpers";
import type ExcalidrawPlugin from "./main";
import { PenStyle } from "./PenTypes";
import {
getDrawingFilename,
getEmbedFilename,
} from "./utils/FileUtils";
import { PENS } from "./utils/Pens";
import {
fragWithHTML,
setLeftHandedMode,
@@ -45,6 +47,8 @@ export interface ExcalidrawSettings {
matchThemeTrigger: boolean;
defaultMode: string;
defaultPenMode: "never" | "mobile" | "always";
allowPinchZoom: boolean;
allowWheelZoom: boolean;
zoomToFitOnOpen: boolean;
zoomToFitOnResize: boolean;
zoomToFitMaxLevel: number;
@@ -115,6 +119,9 @@ export interface ExcalidrawSettings {
mathjaxSourceURL: string;
taskboneEnabled: boolean;
taskboneAPIkey: string;
pinnedScripts: string[];
customPens: PenStyle[];
numberOfCustomPens: number;
}
export const DEFAULT_SETTINGS: ExcalidrawSettings = {
@@ -142,6 +149,8 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
matchThemeTrigger: false,
defaultMode: "normal",
defaultPenMode: "never",
allowPinchZoom: false,
allowWheelZoom: false,
zoomToFitOnOpen: true,
zoomToFitOnResize: true,
zoomToFitMaxLevel: 2,
@@ -200,19 +209,34 @@ 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",
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,
};
export class ExcalidrawSettingTab extends PluginSettingTab {
plugin: ExcalidrawPlugin;
private requestEmbedUpdate: boolean = false;
private requestReloadDrawings: boolean = false;
private requestUpdatePinnedPens: boolean = false;
private reloadMathJax: boolean = false;
//private applyDebounceTimer: number = 0;
@@ -238,6 +262,11 @@ 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.requestReloadDrawings) {
const exs =
app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW);
@@ -264,6 +293,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");
@@ -591,6 +621,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")))
@@ -1291,6 +1351,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)
@@ -1308,10 +1432,6 @@ 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("FIELD_SUGGESTER_NAME"))
@@ -1363,40 +1483,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;

View File

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

View File

@@ -1,5 +1,9 @@
import { normalizePath, Notice, TAbstractFile, TFile, TFolder, Vault } from "obsidian";
import { DataURL } from "@zsviczian/excalidraw/types/types";
import { 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
@@ -145,3 +149,41 @@ 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;
}

View File

@@ -0,0 +1,47 @@
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";
export type InternalDragAction = "link"|"image"|"image-fullsize";
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(!isSHIFT(ev) && isCTRL(ev) && !isALT(ev) && !isMETA(ev)) return "insert-link";
if(!isSHIFT(ev) && !isCTRL(ev) && !isALT(ev) && isMETA(ev)) return "insert-link";
if( isSHIFT(ev) && !isCTRL(ev) && !isALT(ev) && !isMETA(ev)) return "image-import";
if(!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( 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";
}

View File

@@ -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
View 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",
}
}
}
},
}

View File

@@ -3,6 +3,7 @@ import {
App,
Notice,
request,
requestUrl,
TFile,
} from "obsidian";
import { Random } from "roughjs/bin/math";
@@ -22,7 +23,9 @@ 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";
import { dataURLToFile } from "@zsviczian/excalidraw/types/data/blob";
declare const PLUGIN_VERSION:string;
@@ -671,4 +674,52 @@ 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 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`;
}

View File

@@ -67,6 +67,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 +167,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 +196,7 @@ li[data-testid] {
.excalidraw-release .modal {
max-height: 80%;
max-width: 100ch;
max-width: 42em;
}
.excalidraw .Island .scrollbar {
@@ -276,7 +288,7 @@ textarea.excalidraw-wysiwyg {
}
label.color-input-container > input {
max-width: 8rem;
max-width: 5rem;
}
.excalidraw .FixedSideContainer_side_top {
@@ -288,4 +300,40 @@ 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;
}

1713
yarn.lock

File diff suppressed because it is too large Load Diff