Compare commits

...

49 Commits

Author SHA1 Message Date
Zsolt Viczian
45c6c4680a 1.0.10 release 2021-05-10 20:15:52 +02:00
Zsolt Viczian
d7cf04cef8 1.0.10-test 2021-05-09 17:36:52 +02:00
zsviczian
0cb4c0c4d2 Update readme.md 2021-05-08 22:15:33 +02:00
zsviczian
f13c5a2df5 Update readme.md 2021-05-08 22:15:12 +02:00
zsviczian
f5e0d56d99 Update readme.md 2021-05-08 22:13:46 +02:00
Zsolt Viczian
7ac04c0f74 ko-fi 2021-05-08 22:12:57 +02:00
zsviczian
934eea794b Update README.md 2021-05-08 20:45:55 +02:00
Zsolt Viczian
045ee288d5 updated navigation 2021-05-08 20:42:11 +02:00
Zsolt Viczian
7455405425 added navigation 2021-05-08 20:33:04 +02:00
zsviczian
9c52a7d851 Set theme jekyll-theme-leap-day 2021-05-08 20:29:49 +02:00
zsviczian
c9a7930a04 Update dataviewjs_familytree.md 2021-05-08 20:27:41 +02:00
zsviczian
fdee55ccf0 Update readme.md 2021-05-08 20:27:23 +02:00
Zsolt Viczian
b4d9469b7d docs v1.0 2021-05-08 20:26:09 +02:00
zsviczian
caecd7422b Update dataviewjs.md 2021-05-08 19:49:26 +02:00
zsviczian
7ed33646e0 Update dataviewjs.md 2021-05-08 19:49:09 +02:00
zsviczian
d491e24605 Update readme.md 2021-05-08 19:44:09 +02:00
zsviczian
65baf16d8a Update readme.md 2021-05-08 19:43:22 +02:00
Zsolt Viczian
5bc756288c Merge branch 'master' of https://github.com/zsviczian/obsidian-excalidraw-plugin 2021-05-08 19:42:52 +02:00
Zsolt Viczian
dd41cd1eeb . 2021-05-08 19:42:40 +02:00
zsviczian
0e8ff2f5cf Update readme.md 2021-05-08 19:40:16 +02:00
Zsolt Viczian
aa78e7ea54 docs testing 2021-05-08 19:36:50 +02:00
zsviczian
18c0badc25 Rename AutomateHowTo.md to readme.md 2021-05-08 19:31:17 +02:00
zsviczian
34f08766f4 Set theme jekyll-theme-hacker 2021-05-08 19:27:54 +02:00
Zsolt Viczian
8cbc0f1d53 experimenting with docs 2021-05-08 19:25:43 +02:00
Zsolt Viczian
dc8223b6fa . 2021-05-08 09:56:07 +02:00
Zsolt Viczian
b445a62f50 . 2021-05-08 09:10:20 +02:00
Zsolt Viczian
3dcc156e46 . 2021-05-08 09:08:50 +02:00
Zsolt Viczian
ba5c132f17 . 2021-05-08 09:06:53 +02:00
Zsolt Viczian
a6671ff35b updated insert new drawing example 2021-05-08 09:06:33 +02:00
Zsolt Viczian
3a48db940d updated documentation 2021-05-08 07:57:31 +02:00
Zsolt Viczian
524626cb5b updated ExcalidrawAutomate documentation 2021-05-08 07:56:00 +02:00
Zsolt Viczian
bd06d08071 Merge branch 'master' of https://github.com/zsviczian/obsidian-excalidraw-plugin 2021-05-08 07:51:33 +02:00
Zsolt Viczian
76ca98e3ed 1.0.9 minor fix to theme in ExcalidrawAutomate 2021-05-08 07:51:15 +02:00
zsviczian
ce523e5887 Update README.md 2021-05-08 07:46:10 +02:00
zsviczian
e5f94b3fba Update AutomateHowTo.md 2021-05-08 07:26:07 +02:00
Zsolt Viczian
ddb01297a7 1.0.8 release 2021-05-07 20:33:51 +02:00
zsviczian
be4b363cb6 Update README.md 2021-05-07 20:33:30 +02:00
zsviczian
359bb54752 Update AutomateHowTo.md 2021-05-07 19:11:13 +02:00
Zsolt Viczian
d15278e70e tooltip edit 2021-05-06 23:23:59 +02:00
Zsolt Viczian
4be1ff89fe Force-Save tooltip 2021-05-06 23:20:42 +02:00
Zsolt Viczian
c962168c52 solved #46, #45, #44, #41, #40, #38, #37 2021-05-06 23:15:07 +02:00
Zsolt Viczian
660f6e03b1 trying to resolve issue with slidingPanes 2021-05-06 22:44:57 +02:00
Zsolt Viczian
a26e565d04 TransclusionIndex working 2021-05-06 20:56:48 +02:00
Zsolt Viczian
0debaace4e parser 2021-05-06 09:16:16 +02:00
Zsolt Viczian
126086f9f1 Merge branch 'master' of https://github.com/zsviczian/obsidian-excalidraw-plugin 2021-05-06 06:22:14 +02:00
Zsolt Viczian
baf2cdd5d8 save on close 2021-05-06 06:21:42 +02:00
zsviczian
793302a1f5 Update README.md 2021-05-05 22:28:33 +02:00
zsviczian
0d361340c1 Update AutomateHowTo.md 2021-05-05 20:54:00 +02:00
zsviczian
e192da8668 Update AutomateHowTo.md 2021-05-05 20:53:24 +02:00
26 changed files with 1245 additions and 87 deletions

View File

@@ -6,6 +6,7 @@ With a little work, using Excalidraw Automate you can generate simple mindmaps,
You can access Excalidraw Automate via the ExcalidrawAutomate object. I recommend staring your Automate scripts with the following code.
*Use CTRL+Shift+V to paste code into Obsidian!*
```javascript
const ea = ExcalidrawAutomate;
ea.reset();
@@ -22,7 +23,26 @@ The second line resets ExcalidrawAutomate to defaults. This is important as you
You can change styling between adding different elements. My logic for separating element styling and creation is based on the assumption that you will probably set a stroke color, stroke style, stroke roughness, etc. and draw most of your elements using this. There would be no point in setting all these parameters each time you add an element.
### Before we dive deeper, here's a simple example script
### Before we dive deeper, here are two a simple example scripts
#### Create a new drawing with custom name, in a custom folder, using a template
This simple script gives you significant additional flexibility over Excalidraw Plugin settings to name your drawings, place them into folders, and to apply templates.
*Use CTRL+Shift+V to paste code into Obsidian!*
```javascript
<%*
const ea = ExcalidrawAutomate;
ea.reset();
await ea.create({
filename : tp.date.now("HH.mm"),
foldername : tp.date.now("YYYY-MM-DD"),
templatePath: "Excalidraw/Template1.excalidraw",
onNewPane : false
});
%>
```
#### Create a simple drawing
*Use CTRL+Shift+V to paste code into Obsidian!*
```javascript
<%*
const ea = ExcalidrawAutomate;
@@ -43,7 +63,7 @@ The script will generate the following drawing:
## Attributes and functions at a glance
Here's the interface implemented by ExcalidrawAutomate:
*Use CTRL+Shift+V to paste code into Obsidian!*
```javascript
ExcalidrawAutomate: {
style: {
@@ -301,7 +321,31 @@ async createPNG(templatePath?:string)
Returns a blob containing a PNG image of the generated drawing.
## Examples
### Insert new drawing into currently edited document
This template will prompt you for the title of the drawing. It will create a new drawing with the provided title, and in the folder of the document you were editing. It will then transclude the new drawing at the cursor location and open the new drawing in a new workspace leaf by splitting the current leaf.
*Use CTRL+Shift+V to paste code into Obsidian!*
```javascript
<%*
const defaultTitle = tp.date.now("HHmm")+' '+tp.file.title;
const title = await tp.system.prompt("Title of the drawing?", defaultTitle);
const folder = tp.file.folder(true);
const transcludePath = (folder== '/' ? '' : folder + '/') + title + '.excalidraw';
tR = String.fromCharCode(96,96,96)+'excalidraw\n[['+transcludePath+']]\n'+String.fromCharCode(96,96,96);
const ea = ExcalidrawAutomate;
ea.reset();
ea.setTheme(1); //set Theme to dark
await ea.create({
filename : title,
foldername : folder,
//templatePath: 'Excalidraw/Template.excalidraw', //uncomment if you want to use a template
onNewPane : true
});
%>
```
### Connect objects
*Use CTRL+Shift+V to paste code into Obsidian!*
```javascript
<%*
const ea = ExcalidrawAutomate;
@@ -317,6 +361,8 @@ Returns a blob containing a PNG image of the generated drawing.
```
### Using a template
This example is similar to the first one, but rotated 90°, and using a template, plus specifying a filename and folder to save the drawing, and opening the new drawing in a new pane.
*Use CTRL+Shift+V to paste code into Obsidian!*
```javascript
<%*
const ea = ExcalidrawAutomate;
@@ -337,7 +383,7 @@ This example is similar to the first one, but rotated 90°, and using a template
### Generating a simple mindmap from a text outline
This is a slightly more elaborate example. This will generate an a mindmap from a tabulated outline.
![Drawing 2021-05-05 20 14 04](https://user-images.githubusercontent.com/14358394/117189615-afe07580-adde-11eb-81da-fa4bd84d4970.png)
![Drawing 2021-05-05 20 52 34](https://user-images.githubusercontent.com/14358394/117194124-00a69d00-ade4-11eb-8b75-5e18a9cbc3cd.png)
Example input:
```
@@ -355,6 +401,8 @@ Example input:
```
The script:
*Use CTRL+Shift+V to paste code into Obsidian!*
```javascript
<%*
const IDX = Object.freeze({"depth":0, "text":1, "parent":2, "size":3, "children": 4, "objectId":5});
@@ -414,13 +462,13 @@ offsets = [0];
for(i=0;i<=linecount;i++) {
depth = tree[i][IDX.depth];
if (depth == 1) ea.style.strokeColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
tree[i][IDX.objectId] = ea.addText(depth*width,((tree[i][IDX.size]/2)+offsets[depth])*height,tree[i][IDX.text],{startArrowHead: 'dot',box:true});
tree[i][IDX.objectId] = ea.addText(depth*width,((tree[i][IDX.size]/2)+offsets[depth])*height,tree[i][IDX.text],{box:true});
//set child offset equal to parent offset
if((depth+1)>offsets.length) offsets.push(offsets[depth]);
else offsets[depth+1] = offsets[depth];
offsets[depth] += tree[i][IDX.size];
if(tree[i][IDX.parent]!=-1) {
ea.connectObjects(tree[tree[i][IDX.parent]][IDX.objectId],"right",tree[i][IDX.objectId],"left",);
ea.connectObjects(tree[tree[i][IDX.parent]][IDX.objectId],"right",tree[i][IDX.objectId],"left",{startArrowHead: 'dot'});
}
}

View File

@@ -1,23 +1,27 @@
# Obsidian Excalidraw Plugin
The Obsidian-Excalidraw plugin integrates [Excalidraw](https://excalidraw.com/), a feature rich sketching tool, into Obsidian. You can store and edit Excalidraw files in your vault and you can transclude drawings into your documents. For a showcase of Excalidraw features, please read my blog post [here](https://www.zsolt.blog/2021/03/showcasing-excalidraw.html).
The Obsidian-Excalidraw plugin integrates [Excalidraw](https://excalidraw.com/), a feature rich sketching tool, into Obsidian. You can store and edit Excalidraw files in your vault and you can transclude drawings into your documents. For a showcase of Excalidraw features, please read my blog post [here](https://www.zsolt.blog/2021/03/showcasing-excalidraw.html) and/or watch the videos below.
**See details of the 1.0.6 and 1.0.7 release including a short video, further below**
## Pleas find release notes for new releases below How-to videos.
![image](https://user-images.githubusercontent.com/14358394/115983515-d06c2c80-a5a1-11eb-8d12-c7df91d18107.png)
## Key features
- The plugin adds the following actions to the **command palette**:
- To create a new drawing
- To find and edit existing drawings in your vault,
- To embed (transclude) a drawing into a document, and
- To export a drawing as PNG or SVG.
- You can also use the **file explorer** in your vault to open Excalidraw files.
- Use the **ribbon button** to create a new drawing, do CTRL+Click to open on a new page.
- Open settings to set up a **default folder** for new drawings.
- Set up a **Template** by creating a drawing, customizing it the way you like it, and specifying the file as the template in settings.
- The plugin saves drawings to your vault as a file with the *.excalidraw* file extension.
- You can customize the **size and position of the embedded image** using the `[[image.excalidraw|100]]`, `[[image.excalidraw|100x100]]`, `[[image.excalidraw|100|left]]`, `[[image.excalidraw|right-wrap]]`, formatting options. `[[<filename.excalidraw>|<width>x<height>|<alignment>]]`. You can add your custom alignment via css. Any text that appears in `<alignment>` will be added as style to the SVG element and the wrapper DIV element. Check below and styles.css for more insight.
- You can setup Excalidraw to **automatically export SVG and/or PNG** files for your drawings, and to keep those in sync with your drawing.
- The plugin adds the following actions to the **command palette**:
- Create a new drawing
- Find and edit existing drawings in your vault,
- Transclude (embed) a drawing into a document, and
- Export a drawing as PNG or SVG.
- You can also use the **file explorer** in your vault to open existing Excalidraw files.
- Use the **ribbon button** to create a new drawing, CTRL+Click to open on a new page.
- Open settings to set up
- a **default folder** for new drawings,
- a **Template** by first creating a drawing, customizing it the way you like it, and specifying the file as the template in settings,
- Excalidraw to **automatically export SVG and/or PNG** files for your drawings, and to keep those in sync with your drawing,
- default width of embedded drawings
- You can also ustomize the **size and position of the embedded image** using the `[[image.excalidraw|100]]`, `[[image.excalidraw|100x100]]`, `[[image.excalidraw|100|left]]`, `[[image.excalidraw|right-wrap]]`, formatting options. `[[<filename.excalidraw>|<width>x<height>|<alignment>]]`. You can add your custom alignment via css. Any text that appears in `<alignment>` will be added as style to the SVG element and the wrapper DIV element. Check below and styles.css for more insight.
- Includes full [Templater](https://silentvoid13.github.io/Templater/) and [Dataview](https://blacksmithgu.github.io/obsidian-dataview/docs/api/intro/) support through ExcalidrawAutomate. Read detailed help + examples: [here](https://zsviczian.github.io/obsidian-excalidraw-plugin/)
- REQUIRES AN OBSIDIAN SYNC SUBSCRIPTION: Temporary hack/workaround to enable Obsidian Sync for Excalidraw files. This enables almost real-time two-way sync for Excalidraw files between your devices. You can draw on your iPad with your pencil, on your Android with your stylus, and the image will be available in Obsidian on your desktop as well and vice versa.
## How to?
Part 1: Intro to Obsidian-Excalidraw - Start a new drawing (3:12)
@@ -44,10 +48,11 @@ Part 6: Intro to Obsidian-Excalidraw: Embedding drawings (2:08)
[![Part 6: Intro to Obsidian-Excalidraw: Embedding drawings](https://user-images.githubusercontent.com/14358394/115983954-bbdd6380-a5a4-11eb-9243-f0151451afcd.jpg)](https://youtu.be/JQeJ-Hh-xAI)
## 1.0.6 and 1.0.7 update
## Release Notes
### 1.0.6 and 1.0.7 update
[![1.0.6 Update](https://user-images.githubusercontent.com/14358394/116312909-58725200-a7ad-11eb-89b9-c67cb48ffebb.jpg)](https://youtu.be/ipZPbcP2B0M)
### SVG styling when embedding using a code block
#### SVG styling when embedding using a code block
- 1.0.7 adds further flexibility to styling
- new formatting option for the code block embedding
- Valid values: `left`, `right`, `left-wrap`, `right-wrap`... but anything after the last `|` character will be added to the class of the SVG element and the wrapper DIV element.
@@ -71,20 +76,48 @@ div.excalidraw-svg-left {
text-align: left;
}
```
### 1.0.8 + 1.0.9 (minor fixes) update
[![Obsidian-Excalidraw 1.0.8 update](https://user-images.githubusercontent.com/14358394/117492534-029e6680-af72-11eb-90a3-086e67e70c1c.jpg)](https://youtu.be/AtEhmHJjnxM)
#### QoL improvements
- Adds context menu to File Explorer to create new drawings
- Adds a new command to the palette: “Transclude (embed) the most recently edited Excalidraw drawing”
- Automatically update file-links in transclusions when you rename or move your drawing
- Saves drawing and updates all active pre-views when drawing loses focus
- File is closed and removed when you select “Delete file” from more options
- Saves drawing when exiting Obsidian
- Fixes pen positioning bug with sliding panes after panes scroll
#### ExcalidrawAutomte full Templater and DataviewJS support
You now have ultimate flexibility over your Excalidraw templates using Templater and Dataview.
- Detailed documentation available [here](https://zsviczian.github.io/obsidian-excalidraw-plugin/)
- I created few examples from the simple to the more complex
- Simple use-case: Creating a drawing using a custom template and following a file and folder naming convention of your choice.
- Complex use-case: Create a mindmap from a tabulated outline.
![Drawing 2021-05-05 20 52 34](https://user-images.githubusercontent.com/14358394/117194124-00a69d00-ade4-11eb-8b75-5e18a9cbc3cd.png)
### 1.0.10 update
[![Obsidian-Excalidraw 1.0.10 update](https://user-images.githubusercontent.com/14358394/117579017-60a58800-b0f1-11eb-8553-7820964662aa.jpg)](https://youtu.be/W7pWXGIe4rQ)
#### Temporary workaround - use it only if you are ok with hacky solutions
- I implemented a temporary workaround to enable Obsidian Sync for Excalidraw files. This enables almost real-time two-way sync between your devices. You can draw on your iPad with your pencil, on your Android with your stylus, and the image will be available in Obsidian as well and vice versa.
- By enabling this feature Excalidraw will sync drawings to a sync folder where drawings are stored in an ".md" file. This will allow Obsidian sync to synchronize Excalidraw drawings as well... Whenever your drawing changes, the corresponding file in the sync folder will also get updated. Similarly, whenever a file is synchronized to the sync folder by Obsidian sync, Excalidraw will sync it with the .excalidraw file in your vault.
- Because this is a temporary workaround until Obsidian sync is ready, I didn't implement extensive application logic to manage sync. Sync might get confused requiring some manual intervention.
#### QoL improvement
- I added an autosave feature. Your active drawing gets saved every 30 seconds if you've made changes to it. Drawings otherwise get saved when the window loses focus, or when you close the drawing, etc. Autosave limits the risk of accidental data loss on mobiles when you "swipe out" Obsidian to close it.
## Known issues
- On mobile (iOS and Android): As you draw left to right it opens left sidebar. Draw right to left, opens right sidebar. Draw down, opens commands palette. So seems open is emulating the gestures, even when drawing towards the center. I understand that the issue will be resolved in the next release of Obsidian mobile.
- I have seen two cases when adding a stencil library did not work. In both cases, the end solution was a reinstall of Obsidian. The root cause is not clear, but maybe because of the incremental updates of Obsidian from an early version.
- Sync does not support .excalidraw files. This issue will be addressed in a later release of Obsidian sync. Until then, here are two hacks you can play with:
- You have the option to use OneDrive, Google Drive, iCloud, DropBox, etc. to sync your vault between devices.
- You can also use Obsidian Sync in conjunction with "Obsidian Git" (find it in community plugins). Be sure to set up git to ignore all files except for .excalidraw by adding the following to `.gitignore`. Obsidian Git does not work on mobile, but on Android you can use an app like MGIT to sync your `.excalidraw` files from/to the git repository.
```
#ignore all kind of files
*.*
#except excalidraw files
!*.excalidraw
```
- Mobile support
- Positioning of the pen gets misaligned after you open the command palette.
- Partially mitigated in 1.0.10 by the introduction of autosave: Your drawing will not be saved when you terminate the mobile app by closing the Obsidian task.
### Resolved known issues:
- Resolved with 1.0.10 Temporary workaround:
- Sync does not support .excalidraw files. This issue will be addressed in a later release of Obsidian sync. Until then, you can use my temporary workaround.
- Resolved with Obsidian mobile 0.18:
- On mobile (iOS and Android): As you draw left to right it opens left sidebar. Draw right to left, opens right sidebar. Draw down, opens commands palette. So seems open is emulating the gestures, even when drawing towards the center.
## Tips and tricks
- If you want to sketch in fullscreen, I recommend installing the [Fullscreen Focus Mode](https://github.com/razumihin/obsidian-fullscreen-plugin) plugin.

View File

@@ -0,0 +1,45 @@
# [◀ Excalidraw Automate How To](../readme.md)
## Attributes and functions overivew
Here's the interface implemented by ExcalidrawAutomate:
```javascript
ExcalidrawAutomate: {
style: {
strokeColor: string;
backgroundColor: string;
angle: number;
fillStyle: FillStyle;
strokeWidth: number;
storkeStyle: StrokeStyle;
roughness: number;
opacity: number;
strokeSharpness: StrokeSharpness;
fontFamily: FontFamily;
fontSize: number;
textAlign: string;
verticalAlign: string;
startArrowHead: string;
endArrowHead: string;
}
canvas: {theme: string, viewBackgroundColor: string};
setFillStyle: Function;
setStrokeStyle: Function;
setStrokeSharpness: Function;
setFontFamily: Function;
setTheme: Function;
addRect: Function;
addDiamond: Function;
addEllipse: Function;
addText: Function;
addLine: Function;
addArrow: Function;
connectObjects: Function;
addToGroup: Function;
toClipboard: Function;
create: Function;
createPNG: Function;
createSVG: Function;
clear: Function;
reset: Function;
};
```

15
docs/API/canvas_style.md Normal file
View File

@@ -0,0 +1,15 @@
# [◀ Excalidraw Automate How To](../readme.md)
## Canvas style settings
Sets the properties of the canvas.
### theme, setTheme()
String. Valid values are "light" and "dark".
`setTheme()` accepts a number:
- 0: "light"
- any other number: "dark"
### viewBackgroundColor
String. This is the fill color of an object. [CSS Legal Color Values](https://www.w3schools.com/cssref/css_colors_legal.asp)
Allowed values are [HTML color names](https://www.w3schools.com/colors/colors_names.asp), hexadecimal RGB strings e.g. `#FF0000` for red, or `transparent`.

91
docs/API/element_style.md Normal file
View File

@@ -0,0 +1,91 @@
# [◀ Excalidraw Automate How To](../readme.md)
## Element style settings
As you will notice, some styles have setter functions. This is to help you navigate the allowed values for the property. You do not need to use the setter function however, you can use set the value directly as well.
### strokeColor
String. The color of the line. [CSS Legal Color Values](https://www.w3schools.com/cssref/css_colors_legal.asp)
Allowed values are [HTML color names](https://www.w3schools.com/colors/colors_names.asp), hexadecimal RGB strings, or e.g. `#FF0000` for red.
### backgroundColor
String. This is the fill color of an object. [CSS Legal Color Values](https://www.w3schools.com/cssref/css_colors_legal.asp)
Allowed values are [HTML color names](https://www.w3schools.com/colors/colors_names.asp), hexadecimal RGB strings e.g. `#FF0000` for red, or `transparent`.
### angle
Number. Rotation in radian. 90° == `Math.PI/2`.
### fillStyle, setFillStyle()
```typescript
type FillStyle = "hachure" | "cross-hatch" | "solid";
setFillStyle (val:number);
```
fillStyle is a string.
`setFillStyle()` accepts a number:
- 0: "hachure"
- 1: "cross-hatch"
- any other number: "solid"
### strokeWidth
Number, sets the width of the stroke.
### strokeStyle, setStrokeStyle()
```typescript
type StrokeStyle = "solid" | "dashed" | "dotted";
setStrokeStyle (val:number);
```
strokeStyle is a string.
`setStrokeStyle()` accepts a number:
- 0: "solid"
- 1: "dashed"
- any other number: "dotted"
### roughness
Number. Called sloppiness in Excalidraw. Three values are accepted:
- 0: Architect
- 1: Artist
- 2: Cartoonist
### opacity
Number between 0 and 100. The opacity of an object, both stroke and fill.
### strokeSharpness, setStrokeSharpness()
```typescript
type StrokeSharpness = "round" | "sharp";
setStrokeSharpness(val:nmuber);
```
strokeSharpness is a string.
"round" lines are curvey, "sharp" lines break at the turning point.
`setStrokeSharpness()` accepts a number:
- 0: "round"
- any other number: "sharp"
### fontFamily, setFontFamily()
Number. Valid values are 1,2 and 3.
`setFontFamily()` will also accept a number and return the name of the font.
- 1: "Virgil, Segoe UI Emoji"
- 2: "Helvetica, Segoe UI Emoji"
- 3: "Cascadia, Segoe UI Emoji"
### fontSize
Number. Default value is 20 px
### textAlign
String. Alignment of the text horizontally. Valid values are "left", "center", "right".
This is relevant when setting a fix width using the `addText()` function.
### verticalAlign
String. Alignment of the text vertically. Valid values are "top" and "middle".
This is relevant when setting a fix height using the `addText()` function.
### startArrowHead, endArrowHead
String. Valid values are "arrow", "bar", "dot", and "none". Specifies the beginning and ending of an arrow.
This is relavant when using the `addArrow()` and the `connectObjects()` functions.

58
docs/API/introduction.md Normal file
View File

@@ -0,0 +1,58 @@
# [◀ Excalidraw Automate How To](../readme.md)
## Introduction to the API
You can access Excalidraw Automate via the ExcalidrawAutomate object. I recommend staring your Automate scripts with the following code.
*Use CTRL+Shift+V to paste code into Obsidian!*
```javascript
const ea = ExcalidrawAutomate;
ea.reset();
```
The first line creates a practical constant so you can avoid writing ExcalidrawAutomate 100x times.
The second line resets ExcalidrawAutomate to defaults. This is important as you will not know which template you executed before, thus you won't know what state you left Excalidraw in.
### Basic logic of using Excalidraw Automate
1. Set the styling of the elements you want to draw
2. Add elements. As you add elements, each new element is added one layer above the previous, thus in case of overlapping objects the later one will be on the top of the prior one.
3. Call `await ea.create();` to instantiate the drawing
You can change styling between adding different elements. My logic for separating element styling and creation is based on the assumption that you will probably set a stroke color, stroke style, stroke roughness, etc. and draw most of your elements using this. There would be no point in setting all these parameters each time you add an element.
### Before we dive deeper, here are two a simple example scripts
#### Create a new drawing with custom name, in a custom folder, using a template
This simple script gives you significant additional flexibility over Excalidraw Plugin settings to name your drawings, place them into folders, and to apply templates.
*Use CTRL+Shift+V to paste code into Obsidian!*
```javascript
<%*
const ea = ExcalidrawAutomate;
ea.reset();
await ea.create({
filename : tp.date.now("HH.mm"),
foldername : tp.date.now("YYYY-MM-DD"),
templatePath: "Excalidraw/Template1.excalidraw",
onNewPane : false
});
%>
```
#### Create a simple drawing
*Use CTRL+Shift+V to paste code into Obsidian!*
```javascript
<%*
const ea = ExcalidrawAutomate;
ea.reset();
ea.addRect(-150,-50,450,300);
ea.addText(-100,70,"Left to right");
ea.addArrow([[-100,100],[100,100]]);
ea.style.strokeColor = "red";
ea.addText(100,-30,"top to bottom",{width:200,textAligh:"center"});
ea.addArrow([[200,0],[200,200]]);
await ea.create();
%>
```
The script will generate the following drawing:
![FristDemo](https://user-images.githubusercontent.com/14358394/116825643-6e5a8b00-ab90-11eb-9e3a-37c524620d0d.png)

65
docs/API/objects.md Normal file
View File

@@ -0,0 +1,65 @@
# [◀ Excalidraw Automate How To](../readme.md)
## Adding objects
These functions will add objects to your drawing. The canvas is infinite, and it accepts negative and positive X and Y values. X values increase left to right, Y values increase top to bottom.
![coordinates](https://user-images.githubusercontent.com/14358394/116825632-6569b980-ab90-11eb-827b-ada598e91e46.png)
### addRect(), addDiamond(), addEllipse()
```typescript
addRect(topX:number, topY:number, width:number, height:number):string
addDiamond(topX:number, topY:number, width:number, height:number):string
addEllipse(topX:number, topY:number, width:number, height:number):string
```
Returns the `id` of the object. The `id` is required when connecting objects with lines. See later.
### addText()
```typescript
addText(topX:number, topY:number, text:string, formatting?:{width:number, height:number,textAlign: string, verticalAlign:string, box: boolean, boxPadding: number}):string
```
Adds text to the drawing.
Formatting parameters are optional:
- If `width` and `height` are not specified, the function will calculate the width and height based on the fontFamily, the fontSize and the text provided.
- In case you want to position a text in the center compared to other elements on the drawing, you can provide a fixed height and width, and you can also specify `textAlign` and `verticalAlign` as described above. e.g.: `{width:500, textAlign:"center"}`
- If you want to add a box around the text, set `{box:true}`
Returns the `id` of the object. The `id` is required when connecting objects with lines. See later. If `{box:true}` then returns the id of the enclosing box.
### addLine()
```typescript
addLine(points: [[x:number,y:number]]):void
```
Adds a line following the points provided. Must include at least two points `points.length >= 2`. If more than 2 points are provided the interim points will be added as breakpoints. The line will break with angles if `strokeSharpness` is set to "sharp" and will be curvey if it is set to "round".
### addArrow()
```typescript
addArrow(points: [[x:number,y:number]],formatting?:{startArrowHead:string,endArrowHead:string,startObjectId:string,endObjectId:string}):void
```
Adds an arrow following the points provided. Must include at least two points `points.length >= 2`. If more than 2 points are provided the interim points will be added as breakpoints. The line will break with angles if element `style.strokeSharpness` is set to "sharp" and will be curvey if it is set to "round".
`startArrowHead` and `endArrowHead` specify the type of arrow head to use, as described above. Valid values are "none", "arrow", "dot", and "bar". e.g. `{startArrowHead: "dot", endArrowHead: "arrow"}`
`startObjectId` and `endObjectId` are the object id's of connected objects. I recommend using `connectObjects` instead calling addArrow() for the purpose of connecting objects.
### connectObjects()
```typescript
declare type ConnectionPoint = "top"|"bottom"|"left"|"right";
connectObjects(objectA: string, connectionA: ConnectionPoint, objectB: string, connectionB: ConnectionPoint, formatting?:{numberOfPoints: number,startArrowHead:string,endArrowHead:string, padding: number}):void
```
Connects two objects with an arrow.
`objectA` and `objectB` are strings. These are the ids of the objects to connect. These IDs are returned by addRect(), addDiamond(), addEllipse() and addText() when creating those objects.
`connectionA` and `connectionB` specify where to connect on the object. Valid values are: "top", "bottom", "left", and "right".
`numberOfPoints` set the number of interim break points for the line. Default value is zero, meaning there will be no breakpoint in between the start and the end points of the arrow. When moving objects on the drawing, these breakpoints will influence how the line is rerouted by Excalidraw.
`startArrowHead` and `endArrowHead` work as described for `addArrow()` above.
### addToGroup()
```typescript
addToGroup(objectIds:[]):void
```
Groups objects listed in `objectIds`.

43
docs/API/utility.md Normal file
View File

@@ -0,0 +1,43 @@
# [◀ Excalidraw Automate How To](../readme.md)
## Utility functions
### clear()
`clear()` will clear objects from cache, but will retain element style settings.
### reset()
`reset()` will first call `clear()` and then reset element style to defaults.
### toClipboard()
```typescript
async toClipboard(templatePath?:string)
```
Places the generated drawing to the clipboard. Useful when you don't want to create a new drawing, but want to paste additional items onto an exising drawing.
### create()
```typescript
async create(params?:{filename: string, foldername:string, templatePath:string, onNewPane: boolean})
```
Creates the drawing and opens it.
`filename` is the filename without extension of the drawing to be created. If `null`, then Excalidraw will generate a filename.
`foldername` is the folder where the file should be created. If `null` then the default folder for new drawings will be used according to Excalidraw settings.
`templatePath` the filename including full path and extension for a template file to use. This template file will be added as the base layer, all additional objects added via ExcalidrawAutomate will appear on top of elements in the template. If `null` then no template will be used, i.e. an empty white drawing will be the base for adding objects.
`onNewPane` defines where the new drawing should be created. `false` will open the drawing on the current active leaf. `true` will open the drawing by vertically splitting the current leaf.
Example:
```javascript
create({filename:"my drawing", foldername:"myfolder/subfolder/", templatePath: "Excalidraw/template.excalidraw", onNewPane: true});
```
### createSVG()
```typescript
async createSVG(templatePath?:string)
```
Returns an HTML SVGSVGElement containing the generated drawing.
### createPNG()
```typescript
async createPNG(templatePath?:string)
```
Returns a blob containing a PNG image of the generated drawing.

View File

@@ -0,0 +1,25 @@
# [◀ Excalidraw Automate How To](../readme.md)
## Applying an Excalidraw Template to a New Drawing
This example is similar to the one in the introduction, only rotated 90°, and using a template, plus specifying a filename and folder to save the drawing, and opening the new drawing in a new pane.
*Use CTRL+Shift+V to paste code into Obsidian!*
```javascript
<%*
const ea = ExcalidrawAutomate;
ea.reset();
ea.style.angle = Math.PI/2;
ea.style.strokeWidth = 3.5;
ea.addRect(-150,-50,450,300);
ea.addText(-100,70,"Left to right");
ea.addArrow([[-100,100],[100,100]]);
ea.style.strokeColor = "red";
await ea.addText(100,-30,"top to bottom",{width:200,textAlign:"center"});
ea.addArrow([[200,0],[200,200]]);
await ea.create({
filename :"My Drawing",
foldername :"myfolder/fordemo/",
templatePath:"Excalidraw/Template2.excalidraw",
onNewPane :true});
%>
```

View File

@@ -0,0 +1,18 @@
# [◀ Excalidraw Automate How To](../readme.md)
## Connect Objects
This [Templater](https://github.com/SilentVoid13/Templater) template demonstrates how to connect two objects using ExcalidrawAutomate.
*Use CTRL+Shift+V to paste code into Obsidian!*
```javascript
<%*
const ea = ExcalidrawAutomate;
ea.reset();
ea.addText(-130,-100,"Connecting two objects");
const a = ea.addRect(-100,-100,100,100);
const b = ea.addEllipse(200,200,100,100);
ea.connectObjects(a,"bottom",b,"left",{numberOfPoints: 2}); //see how the line breaks differently when moving objects around
ea.style.strokeColor = "red";
ea.connectObjects(a,"right",b,"top",1);
await ea.create();
%>
```

View File

@@ -0,0 +1,67 @@
# [◀ Excalidraw Automate How To](../readme.md)
## Family tree from Tasklist using dataviewjs
This is similar to the mindmap script using dataviewjs, but the output is rendered vertically.
### Output
![image](https://user-images.githubusercontent.com/14358394/117549637-d3ecc280-b03b-11eb-952a-840a9a75b6ca.png)
### Input file
Task List looks like:
```markdown
- [ ] OBSIDIAN
- [ ] Silver
- [ ] PawPaw Silv
- [ ] MawMaw Silv
- [ ] Licat
- [ ] PeePaw Li
- [ ] MeeMaw Li
```
### dataviewjs script
Code to render the excalidraw looks like:
```javascript
function crawl(subtasks) {
let size = subtasks.length > 0 ? 0 : 1; //if no children then a leaf with size 1
for (let task of subtasks) {
task["size"] = crawl(task.subtasks);
size += task.size;
}
return size;
}
const tasks = dv.page("Demo.md").file.tasks[0];
tasks["size"] = crawl(tasks.subtasks);
const width = 300;
const height = 100;
const ea = ExcalidrawAutomate;
ea.reset();
function buildMindmap(subtasks, depth, offset, parentObjectID) {
if (subtasks.length == 0) return;
let task;
for (let i = 0; i < subtasks.length; i++) {
task = subtasks[i]
if (depth == 1) ea.style.strokeColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
task["objectID"] = ea.addText((task.size/2+offset)*width,depth*height,task.text,{box:true})
ea.connectObjects(parentObjectID,"top",task.objectID,"bottom",{startArrowHead: 'arrow', endArrowHead: 'dot'});
if (i >= 1) {
ea.connectObjects(subtasks[i-1]['objectID'],"right",task.objectID,"left", {endArrowHead: 'none'});
}
buildMindmap(task.subtasks, depth-1,offset,task.objectID);
offset += task.size/1.5;
}
}
tasks["objectID"] = ea.addText(width*1.5,width,tasks.text,{box:true, textAlign:"center"});
buildMindmap(tasks.subtasks, 2, 0, tasks.objectID);
(async ()=> {
const svg = await ea.createSVG();
const el=document.querySelector("div.block-language-dataviewjs");
el.appendChild(svg);
})();
```

View File

@@ -0,0 +1,60 @@
# [◀ Excalidraw Automate How To](../readme.md)
## Mindmap from Tasklist using dataviewjs
This is similar to the mindmap script using templater, but because dataview already returns tasks in a tree, it is slightly simpler
### Output
![image](https://user-images.githubusercontent.com/14358394/117548665-71dd8e80-b036-11eb-8a45-4169fdd7cc05.png)
### Input file
The input file is `Demo.md` with the following contents:
```markdown
- [ ] Root task
- [ ] task 1.1
- [ ] task 1.2
- [ ] task 1.2.1
- [ ] task 1.2.2
- [ ] task 1.3
- [ ] task 1.3.1
```
### dataviewjs script
The `dataviewjs` script looks like this:
*Use CTRL+Shift+V to paste code into Obsidian!*
```javascript
function crawl(subtasks) {
let size = subtasks.length > 0 ? 0 : 1; //if no children then a leaf with size 1
for (let task of subtasks) {
task["size"] = crawl(task.subtasks);
size += task.size;
}
return size;
}
const tasks = dv.page("Demo.md").file.tasks[0];
tasks["size"] = crawl(tasks.subtasks);
const width = 300;
const height = 100;
const ea = ExcalidrawAutomate;
ea.reset();
function buildMindmap(subtasks, depth, offset, parentObjectID) {
if (subtasks.length == 0) return;
for (let task of subtasks) {
if (depth == 1) ea.style.strokeColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
task["objectID"] = ea.addText(depth*width,(task.size/2+offset)*height,task.text,{box:true})
ea.connectObjects(parentObjectID,"right",task.objectID,"left",{startArrowHead: 'dot'});
buildMindmap(task.subtasks, depth+1,offset,task.objectID);
offset += task.size;
}
}
tasks["objectID"] = ea.addText(0,(tasks.size/2)*height,tasks.text,{box:true});
buildMindmap(tasks.subtasks, 1, 0, tasks.objectID);
(async ()=> {
const svg = await ea.createSVG();
const el=document.querySelector("div.block-language-dataviewjs");
el.appendChild(svg);
})();
```

View File

@@ -0,0 +1,23 @@
# [◀ Excalidraw Automate How To](../readme.md)
## Insert new drawing into currently edited document
This [Templater](https://github.com/SilentVoid13/Templater) template will prompt you for the title of the drawing. It will create a new drawing with the provided title, and in the folder of the document you were editing. It will then transclude the new drawing at the cursor location and open the new drawing in a new workspace leaf by splitting the current leaf.
*Use CTRL+Shift+V to paste code into Obsidian!*
```javascript
<%*
const defaultTitle = tp.date.now("HHmm")+' '+tp.file.title;
const title = await tp.system.prompt("Title of the drawing?", defaultTitle);
const folder = tp.file.folder(true);
const transcludePath = (folder== '/' ? '' : folder + '/') + title + '.excalidraw';
tR = String.fromCharCode(96,96,96)+'excalidraw\n[['+transcludePath+']]\n'+String.fromCharCode(96,96,96);
const ea = ExcalidrawAutomate;
ea.reset();
ea.setTheme(1); //set Theme to dark
await ea.create({
filename : title,
foldername : folder,
//templatePath: 'Excalidraw/Template.excalidraw', //uncomment if you want to use a template
onNewPane : true
});
%>
```

View File

@@ -0,0 +1,97 @@
# [◀ Excalidraw Automate How To](../readme.md)
## Generating a simple mindmap from a text outline
This is a slightly more elaborate example. This will generate an a mindmap from a tabulated outline.
### Output
![Drawing 2021-05-05 20 52 34](https://user-images.githubusercontent.com/14358394/117194124-00a69d00-ade4-11eb-8b75-5e18a9cbc3cd.png)
### Input file
Example input:
```
- Test 1
- Test 1.1
- Test 2
- Test 2.1
- Test 2.2
- Test 2.2.1
- Test 2.2.2
- Test 2.2.3
- Test 2.2.3.1
- Test 3
- Test 3.1
```
### Templater script
*Use CTRL+Shift+V to paste code into Obsidian!*
```javascript
<%*
const IDX = Object.freeze({"depth":0, "text":1, "parent":2, "size":3, "children": 4, "objectId":5});
//check if an editor is the active view
const editor = this.app.workspace.activeLeaf?.view?.editor;
if(!editor) return;
//initialize the tree with the title of the document as the first element
let tree = [[0,this.app.workspace.activeLeaf?.view?.getDisplayText(),-1,0,[],0]];
const linecount = editor.lineCount();
//helper function, use regex to calculate indentation depth, and to get line text
function getLineProps (i) {
props = editor.getLine(i).match(/^(\t*)-\s+(.*)/);
return [props[1].length+1, props[2]];
}
//a vector that will hold last valid parent for each depth
let parents = [0];
//load outline into tree
for(i=0;i<linecount;i++) {
[depth,text] = getLineProps(i);
if(depth>parents.length) parents.push(i+1);
else parents[depth] = i+1;
tree.push([depth,text,parents[depth-1],1,[]]);
tree[parents[depth-1]][IDX.children].push(i+1);
}
//recursive function to crawl the tree and identify height aka. size of each node
function crawlTree(i) {
if(i>linecount) return 0;
size = 0;
if((i+1<=linecount && tree[i+1][IDX.depth] <= tree[i][IDX.depth])|| i == linecount) { //I am a leaf
tree[i][IDX.size] = 1;
return 1;
}
tree[i][IDX.children].forEach((node)=>{
size += crawlTree(node);
});
tree[i][IDX.size] = size;
return size;
}
crawlTree(0);
//Build the mindmap in Excalidraw
const width = 300;
const height = 100;
const ea = ExcalidrawAutomate;
ea.reset();
//stores position offset of branch/leaf in height units
offsets = [0];
for(i=0;i<=linecount;i++) {
depth = tree[i][IDX.depth];
if (depth == 1) ea.style.strokeColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
tree[i][IDX.objectId] = ea.addText(depth*width,((tree[i][IDX.size]/2)+offsets[depth])*height,tree[i][IDX.text],{box:true});
//set child offset equal to parent offset
if((depth+1)>offsets.length) offsets.push(offsets[depth]);
else offsets[depth+1] = offsets[depth];
offsets[depth] += tree[i][IDX.size];
if(tree[i][IDX.parent]!=-1) {
ea.connectObjects(tree[tree[i][IDX.parent]][IDX.objectId],"right",tree[i][IDX.objectId],"left",{startArrowHead: 'dot'});
}
}
await ea.create({onNewPane: true});
%>
```

1
docs/_config.yml Normal file
View File

@@ -0,0 +1 @@
theme: jekyll-theme-leap-day

35
docs/readme.md Normal file
View File

@@ -0,0 +1,35 @@
# Excalidraw Automate How To
Excalidraw Automate allows you to create Excalidraw drawings using the [Templater](https://silentvoid13.github.io/Templater/docs/) plugin, and to generate embedded SVG and PNG images using [DataviewJS](https://blacksmithgu.github.io/obsidian-dataview/docs/api/intro/)
With a little work, using Excalidraw Automate you can generate simple mindmaps, build a faimly tree, fill out SVG forms, create customized charts, etc. based on documents in your vault.
![image](https://user-images.githubusercontent.com/14358394/117549619-bae41180-b03b-11eb-968d-c909e79a7524.png)
## API documenation
- [Introduction to the API](API/introduction.md)
- [Overview of Attributes and Functions](API/attributes_functions_overview.md)
- [Element Sytle](API/element_style.md)
- [Canvas Style](API/canvas_style.md)
- [Adding Objects](API/objects.md)
- [Utility Functions](API/utility.md)
## Examples
- **Templater**
- [Insert new drawing into currently edited document](Examples/insert_new_drawing.md)
- [Connect objects](Examples/connect_objects.md)
- [Apply an Excalidraw template](Examples/apply_template.md)
- [Mindmap with Templater](Examples/templater_mindmap.md)
- **Dataview**
- [Mindmap with Dataview](Examples/dataviewjs_mindmap.md)
- [Family tree with Dataview](Examples/dataviewjs_familytree.md)
## If you are enjoying the Obsidian Excalidraw Plugin...
Help spread the word by sharing about the Plugin on social media.
You can find me on Twitter [@zsviczian](https://twitter.com/zsviczian), and on my blog [zsolt.blog](https://zsolt.blog).
[<img style="float:left" src="https://user-images.githubusercontent.com/14358394/115450238-f39e8100-a21b-11eb-89d0-fa4b82cdbce8.png" width="150">](https://ko-fi.com/zsolt)

View File

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

View File

@@ -141,7 +141,7 @@ export function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
this.canvas.theme = "light";
return "light";
default:
this.canvas = "dark";
this.canvas.theme = "dark";
return "dark";
}
},
@@ -152,7 +152,8 @@ export function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
});
},
async toClipboard(templatePath?:string) {
let elements = templatePath ? (await getTemplate(templatePath)).elements : [];
const template = templatePath ? (await getTemplate(templatePath)) : null;
let elements = template ? template.elements : [];
for (let i=0;i<this.elementIds.length;i++) {
elements.push(this.elementsDict[this.elementIds[i]]);
}
@@ -163,7 +164,8 @@ export function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
}));
},
async create(params?:{filename: string, foldername:string, templatePath:string, onNewPane: boolean}) {
let elements = params?.templatePath ? (await getTemplate(params.templatePath)).elements : [];
const template = params?.templatePath ? (await getTemplate(params.templatePath)) : null;
let elements = template ? template.elements : [];
for (let i=0;i<this.elementIds.length;i++) {
elements.push(this.elementsDict[this.elementIds[i]]);
}
@@ -177,14 +179,15 @@ export function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
"source": "https://excalidraw.com",
"elements": elements,
"appState": {
"theme": this.canvas.theme,
"viewBackgroundColor": this.canvas.viewBackgroundColor
"theme": template ? template.appState.theme : this.canvas.theme,
"viewBackgroundColor": template? template.appState.viewBackgroundColor : this.canvas.viewBackgroundColor
}
})
);
},
async createSVG(templatePath?:string) {
let elements = templatePath ? (await getTemplate(templatePath)).elements : [];
const template = templatePath ? (await getTemplate(templatePath)) : null;
let elements = template ? template.elements : [];
for (let i=0;i<this.elementIds.length;i++) {
elements.push(this.elementsDict[this.elementIds[i]]);
}
@@ -195,8 +198,8 @@ export function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
"source": "https://excalidraw.com",
"elements": elements,
"appState": {
"theme": this.canvas.theme,
"viewBackgroundColor": this.canvas.viewBackgroundColor
"theme": template ? template.appState.theme : this.canvas.theme,
"viewBackgroundColor": template? template.appState.viewBackgroundColor : this.canvas.viewBackgroundColor
}
}),
{
@@ -206,7 +209,8 @@ export function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
)
},
async createPNG(templatePath?:string) {
let elements = templatePath ? (await getTemplate(templatePath)).elements : [];
const template = templatePath ? (await getTemplate(templatePath)) : null;
let elements = template ? template.elements : [];
for (let i=0;i<this.elementIds.length;i++) {
elements.push(this.elementsDict[this.elementIds[i]]);
}
@@ -217,8 +221,8 @@ export function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
"source": "https://excalidraw.com",
"elements": elements,
"appState": {
"theme": this.canvas.theme,
"viewBackgroundColor": this.canvas.viewBackgroundColor
"theme": template ? template.appState.theme : this.canvas.theme,
"viewBackgroundColor": template? template.appState.viewBackgroundColor : this.canvas.viewBackgroundColor
}
}),
{

View File

@@ -3,11 +3,11 @@ import {
WorkspaceLeaf,
normalizePath,
TFile,
Menu,
WorkspaceItem
} from "obsidian";
import * as React from "react";
import * as ReactDOM from "react-dom";
import Excalidraw, {exportToSvg} from "@excalidraw/excalidraw";
import Excalidraw, {exportToSvg, getSceneVersion} from "@excalidraw/excalidraw";
import { ExcalidrawElement } from "@excalidraw/excalidraw/types/element/types";
import {
AppState,
@@ -26,23 +26,35 @@ import {
} from './constants';
import ExcalidrawPlugin from './main';
interface WorkspaceItemExt extends WorkspaceItem {
containerEl: HTMLElement;
}
export interface ExportSettings {
withBackground: boolean,
withTheme: boolean
}
export default class ExcalidrawView extends TextFileView {
private getScene: any;
private getScene: Function;
private refresh: Function;
private excalidrawRef: React.MutableRefObject<any>;
private justLoaded: boolean;
private plugin: ExcalidrawPlugin;
private dirty: boolean;
private autosaveTimer: any;
private previousSceneVersion: number;
constructor(leaf: WorkspaceLeaf, plugin: ExcalidrawPlugin) {
super(leaf);
this.getScene = null;
this.refresh = null;
this.excalidrawRef = null;
this.plugin = plugin;
this.justLoaded = false;
this.dirty = false;
this.autosaveTimer = null;
this.previousSceneVersion = 0;
}
public async saveSVG(data?: string) {
@@ -97,20 +109,42 @@ export default class ExcalidrawView extends TextFileView {
}
else return this.data;
}
async onload() {
this.addAction(DISK_ICON_NAME,"Save drawing",async (ev)=> {
this.addAction(DISK_ICON_NAME,"Force-save now to update transclusion visible in adjacent workspace pane\n(Please note, that autosave is always on)",async (ev)=> {
await this.save();
this.plugin.triggerEmbedUpdates();
});
this.addAction(PNG_ICON_NAME,"Export as PNG",async (ev)=>this.savePNG());
this.addAction(SVG_ICON_NAME,"Export as SVG",async (ev)=>this.saveSVG());
//this is to solve sliding panes bug
if (this.app.workspace.layoutReady) {
(this.app.workspace.rootSplit as WorkspaceItem as WorkspaceItemExt).containerEl.addEventListener('scroll',(e)=>{if(this.refresh) this.refresh();});
} else {
this.registerEvent(this.app.workspace.on('layout-ready', async () => (this.app.workspace.rootSplit as WorkspaceItem as WorkspaceItemExt).containerEl.addEventListener('scroll',(e)=>{if(this.refresh) this.refresh();})));
}
this.setupAutosaveTimer();
}
private setupAutosaveTimer() {
const timer = async () => {
if(this.dirty) {
this.dirty = false;
if(this.excalidrawRef) await this.save();
this.plugin.triggerEmbedUpdates();
console.log("save");
}
}
this.autosaveTimer = setInterval(timer,30000);
}
//save current drawing when user closes workspace leaf
async onunload() {
if(this.autosaveTimer) clearInterval(this.autosaveTimer);
if(this.excalidrawRef) await this.save();
}
setViewData (data: string, clear: boolean) {
if (this.app.workspace.layoutReady) {
this.loadDrawing(data,clear);
@@ -124,6 +158,7 @@ export default class ExcalidrawView extends TextFileView {
if(this.excalidrawRef) {
this.excalidrawRef = null;
this.getScene = null;
this.refresh = null;
ReactDOM.unmountComponentAtNode(this.contentEl);
}
}
@@ -175,6 +210,8 @@ export default class ExcalidrawView extends TextFileView {
private instantiateExcalidraw(initdata: any) {
this.dirty = false;
this.previousSceneVersion = 0;
const reactElement = React.createElement(() => {
const excalidrawRef = React.useRef(null);
const excalidrawWrapperRef = React.useRef(null);
@@ -182,7 +219,7 @@ export default class ExcalidrawView extends TextFileView {
width: undefined,
height: undefined
});
this.excalidrawRef = excalidrawRef;
React.useEffect(() => {
setDimensions({
@@ -219,6 +256,11 @@ export default class ExcalidrawView extends TextFileView {
}
});
};
this.refresh = () => {
if(!excalidrawRef?.current) return;
excalidrawRef.current.refresh();
};
return React.createElement(
React.Fragment,
@@ -232,7 +274,6 @@ export default class ExcalidrawView extends TextFileView {
},
React.createElement(Excalidraw.default, {
ref: excalidrawRef,
key: "xyz",
width: dimensions.width,
height: dimensions.height,
UIOptions: {
@@ -244,11 +285,21 @@ export default class ExcalidrawView extends TextFileView {
},
},
initialData: initdata,
detectScroll: true,
onChange: (et:ExcalidrawElement[],st:AppState) => {
if(this.justLoaded) {
this.justLoaded = false;
const e = new KeyboardEvent("keydown", {bubbles : true, cancelable : true, shiftKey : true, code:"Digit1"});
this.contentEl.querySelector("canvas")?.dispatchEvent(e);
}
if (st.editingElement == null && st.resizingElement == null &&
st.draggingElement == null && st.editingGroupId == null &&
st.editingLinearElement == null ) {
const sceneVersion = Excalidraw.getSceneVersion(et);
if(sceneVersion != this.previousSceneVersion) {
this.previousSceneVersion = sceneVersion;
this.dirty=true;
}
}
},
onLibraryChange: (items:LibraryItems) => {

117
src/TransclusionIndex.ts Normal file
View File

@@ -0,0 +1,117 @@
import {Vault,TFile,TAbstractFile} from 'obsidian';
export default class TransclusionIndex {
private vault: Vault;
private doc2ex: Map<string, Set<string>>;
private ex2doc: Map<string, Set<string>>;
constructor(vault: Vault) {
this.vault = vault;
this.doc2ex = new Map<string,Set<string>>(); //markdown document includes these excalidraw drawings
this.ex2doc = new Map<string,Set<string>>(); //excalidraw drawings are referenced in these markdown documents
}
async reloadIndex() {
await this.initialize();
}
async initialize(): Promise<void> {
const doc2ex = new Map<string,Set<string>>();
const ex2doc = new Map<string,Set<string>>();
const markdownFiles = this.vault.getMarkdownFiles();
for (const file of markdownFiles) {
const drawings = await this.parseTransclusionsInFile(file);
if (drawings.size > 0) {
doc2ex.set(file.path, drawings);
drawings.forEach((drawing)=>{
if(ex2doc.has(drawing)) ex2doc.set(drawing,ex2doc.get(drawing).add(file.path));
else ex2doc.set(drawing,(new Set<string>()).add(file.path));
});
}
}
this.doc2ex = doc2ex;
this.ex2doc = ex2doc;
this.registerEventHandlers();
}
private updateMarkdownFile(file:TFile,oldExPath:string,newExPath:string) {
const fileContents = this.vault.read(file);
fileContents.then((c: string) => this.vault.modify(file, c.split("[["+oldExPath).join("[["+newExPath)));
const exlist = this.doc2ex.get(file.path);
exlist.delete(oldExPath);
exlist.add(newExPath);
this.doc2ex.set(file.path,exlist);
}
public updateTransclusion(oldExPath: string, newExPath: string): void {
if(!this.ex2doc.has(oldExPath)) return; //drawing is not transcluded in any markdown document
for(const filePath of this.ex2doc.get(oldExPath)) {
this.updateMarkdownFile(this.vault.getAbstractFileByPath(filePath) as TFile,oldExPath,newExPath);
}
this.ex2doc.set(newExPath, this.ex2doc.get(oldExPath));
this.ex2doc.delete(oldExPath);
}
private indexAbstractFile(file: TAbstractFile) {
if (!(file instanceof TFile)) return;
if (file.extension.toLowerCase() != "md") return; //not a markdown document
this.indexFile(file as TFile);
}
private indexFile(file: TFile) {
this.clearIndex(file.path);
this.parseTransclusionsInFile(file).then((drawings) => {
if(drawings.size == 0) return;
this.doc2ex.set(file.path, drawings);
drawings.forEach((drawing)=>{
if(this.ex2doc.has(drawing)) {
this.ex2doc.set(drawing,this.ex2doc.get(drawing).add(file.path));
}
else this.ex2doc.set(drawing,(new Set<string>()).add(file.path));
});
});
}
private clearIndex(path: string) {
if(!this.doc2ex.get(path)) return;
this.doc2ex.get(path).forEach((ex)=> {
const files = this.ex2doc.get(ex);
files.delete(path);
if(files.size>0) this.ex2doc.set(ex,files);
else this.ex2doc.delete(ex);
});
this.doc2ex.delete(path);
}
private async parseTransclusionsInFile(file: TFile): Promise<Set<string>> {
const fileContents = await this.vault.cachedRead(file);
const pattern = new RegExp('('+String.fromCharCode(96,96,96)+'excalidraw\\s+.*\\[{2})([^|\\]]*).*\\]{2}[\\s]+'+String.fromCharCode(96,96,96),'gm');
const transclusions = new Set<string>();
for(const transclusion of [...fileContents.matchAll(pattern)]) {
if(transclusion[2] && transclusion[2].endsWith('.excalidraw'))
transclusions.add(transclusion[2]);
}
return transclusions;
}
private registerEventHandlers() {
this.vault.on('create', (file: TAbstractFile) => {
this.indexAbstractFile(file);
});
this.vault.on('modify', (file: TAbstractFile) => {
this.indexAbstractFile(file);
});
this.vault.on('delete', (file: TAbstractFile) => {
this.clearIndex(file.path);
});
// We could simply change the references to the old path, but parsing again does the trick as well
this.vault.on('rename', (file: TAbstractFile, oldPath: string) => {
this.clearIndex(oldPath);
this.indexAbstractFile(file);
});
}
}

View File

@@ -1,5 +1,6 @@
export const VIEW_TYPE_EXCALIDRAW = "excalidraw";
export const EXCALIDRAW_FILE_EXTENSION = "excalidraw";
export const EXCALIDRAW_FILE_EXTENSION_LEN = EXCALIDRAW_FILE_EXTENSION.length;
export const ICON_NAME = "excalidraw-icon";
export const CODEBLOCK_EXCALIDRAW = "excalidraw";
export const MAX_COLORS = 5;

View File

@@ -11,6 +11,7 @@ import {
MarkdownPostProcessorContext,
Menu,
MenuItem,
TAbstractFile,
} from 'obsidian';
import {
BLANK_DRAWING,
@@ -18,6 +19,7 @@ import {
EXCALIDRAW_ICON,
ICON_NAME,
EXCALIDRAW_FILE_EXTENSION,
EXCALIDRAW_FILE_EXTENSION_LEN,
CODEBLOCK_EXCALIDRAW,
DISK_ICON,
DISK_ICON_NAME,
@@ -43,7 +45,7 @@ import {
initExcalidrawAutomate,
destroyExcalidrawAutomate
} from './ExcalidrawTemplate';
import { norm } from '@excalidraw/excalidraw/types/ga';
import TransclusionIndex from './TransclusionIndex';
export interface ExcalidrawAutomate extends Window {
ExcalidrawAutomate: {
@@ -55,10 +57,22 @@ export interface ExcalidrawAutomate extends Window {
export default class ExcalidrawPlugin extends Plugin {
public settings: ExcalidrawSettings;
private openDialog: OpenFileDialog;
private excalidrawAutomate: ExcalidrawAutomate;
private transclusionIndex: TransclusionIndex;
private activeExcalidrawView: ExcalidrawView;
public lastActiveExcalidrawFilePath: string;
/*Excalidraw Sync Begin*/
private excalidrawSync: Set<string>;
private syncModifyCreate: any;
/*Excalidraw Sync Begin*/
constructor(app: App, manifest: PluginManifest) {
super(app, manifest);
this.activeExcalidrawView = null;
this.lastActiveExcalidrawFilePath = null;
/*Excalidraw Sync Begin*/
this.excalidrawSync = new Set<string>();
this.syncModifyCreate = null;
/*Excalidraw Sync End*/
}
async onload() {
@@ -117,7 +131,7 @@ export default class ExcalidrawPlugin extends Plugin {
this.addCommand({
id: "excalidraw-insert-transclusion",
name: "Transclude (embed) an ."+EXCALIDRAW_FILE_EXTENSION+" drawing",
name: "Transclude (embed) an Excalidraw drawing",
checkCallback: (checking: boolean) => {
if (checking) {
return this.app.workspace.activeLeaf.view.getViewType() == "markdown";
@@ -128,6 +142,19 @@ export default class ExcalidrawPlugin extends Plugin {
},
});
this.addCommand({
id: "excalidraw-insert-last-active-transclusion",
name: "Transclude (embed) the most recently edited Excalidraw drawing",
checkCallback: (checking: boolean) => {
if (checking) {
return (this.app.workspace.activeLeaf.view.getViewType() == "markdown") && (this.lastActiveExcalidrawFilePath!=null);
} else {
this.insertCodeblock(this.lastActiveExcalidrawFilePath);
return true;
}
},
});
this.addCommand({
id: "excalidraw-autocreate",
name: "Create a new drawing - IN A NEW PANE",
@@ -178,6 +205,9 @@ export default class ExcalidrawPlugin extends Plugin {
},
});
this.transclusionIndex = new TransclusionIndex(this.app.vault);
this.transclusionIndex.initialize();
this.registerEvent(
this.app.workspace.on("file-menu", (menu: Menu, file: TFile) => {
if (file instanceof TFolder) {
@@ -185,51 +215,233 @@ export default class ExcalidrawPlugin extends Plugin {
item.setTitle("Create Excalidraw drawing")
.setIcon(ICON_NAME)
.onClick(evt => {
this.createDrawing(file.path+this.getNextDefaultFilename(),false,file.path);
this.createDrawing(this.getNextDefaultFilename(),false,file.path);
})
});
}
})
);
//watch filename change to rename .svg
this.app.vault.on('rename',async (file,oldPath) => {
if (!(this.settings.keepInSync && file instanceof TFile)) return;
if (file.extension != EXCALIDRAW_FILE_EXTENSION) return;
const oldSVGpath = oldPath.substring(0,oldPath.lastIndexOf('.'+EXCALIDRAW_FILE_EXTENSION)) + '.svg';
const svgFile = this.app.vault.getAbstractFileByPath(normalizePath(oldSVGpath));
if(svgFile && svgFile instanceof TFile) {
const newSVGpath = file.path.substring(0,file.path.lastIndexOf('.'+EXCALIDRAW_FILE_EXTENSION)) + '.svg';
await this.app.vault.rename(svgFile,newSVGpath);
}
});
if (this.app.workspace.layoutReady) {
this.addEventListeners(this);
} else {
this.registerEvent(this.app.workspace.on('layout-ready', async () => this.addEventListeners(this)));
}
}
/*Excalidraw Sync Begin*/
public initiateSync() {
if(!this.syncModifyCreate) return;
const files = this.app.vault.getFiles();
(files || [])
.filter((f:TFile) => (f.path.startsWith(this.settings.syncFolder) && f.extension == "md"))
.forEach((f)=>this.syncModifyCreate(f));
(files || [])
.filter((f:TFile) => (!f.path.startsWith(this.settings.syncFolder) && f.extension == EXCALIDRAW_FILE_EXTENSION))
.forEach((f)=>this.syncModifyCreate(f));
}
/*Excalidraw Sync End*/
//watch file delete and delete corresponding .svg
this.app.vault.on('delete',async (file:TFile) => {
if (!(file instanceof TFile)) return;
if (file.extension != EXCALIDRAW_FILE_EXTENSION) return;
const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW);
private async addEventListeners(plugin: ExcalidrawPlugin) {
const closeDrawing = async (filePath:string) => {
const leaves = plugin.app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW);
for (let i=0;i<leaves.length;i++) {
if((leaves[i].view as ExcalidrawView).file.path == file.path) {
//(leaves[i].view as ExcalidrawView).clear();
leaves[i].setViewState({
if((leaves[i].view as ExcalidrawView).file.path == filePath) {
await leaves[i].setViewState({
type: VIEW_TYPE_EXCALIDRAW,
state: {file: null}}
);
}
}
}
}
/*Excalidraw Sync Begin*/
const reloadDrawing = async (oldPath:string, newPath: string) => {
const file = plugin.app.vault.getAbstractFileByPath(newPath);
if(!(file && file instanceof TFile)) return;
const leaves = plugin.app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW);
for (let i=0;i<leaves.length;i++) {
if((leaves[i].view as ExcalidrawView).file.path == oldPath) {
(leaves[i].view as ExcalidrawView).setViewData(await plugin.app.vault.read(file),false);
plugin.triggerEmbedUpdates();
}
}
}
const createPathIfNotThere = async (path:string) => {
const folderArray = path.split("/");
folderArray.pop();
const folderPath = folderArray.join("/");
const folder = plugin.app.vault.getAbstractFileByPath(folderPath);
if(!folder)
await plugin.app.vault.createFolder(folderPath);
}
const getSyncFilepath = (excalidrawPath:string):string => {
return normalizePath(plugin.settings.syncFolder)+'/'+excalidrawPath.slice(0,excalidrawPath.length-EXCALIDRAW_FILE_EXTENSION_LEN)+"md";
}
const getExcalidrawFilepath = (syncFilePath:string):string => {
const syncFolder = normalizePath(plugin.settings.syncFolder)+'/';
const normalFilePath = syncFilePath.slice(syncFolder.length);
return normalFilePath.slice(0,normalFilePath.length-2)+EXCALIDRAW_FILE_EXTENSION; //2=="md".length
}
const syncCopy = async (source:TFile, targetPath: string) => {
await createPathIfNotThere(targetPath);
const target = plugin.app.vault.getAbstractFileByPath(targetPath);
plugin.excalidrawSync.add(targetPath);
if(target && target instanceof TFile) {
await plugin.app.vault.modify(target,await plugin.app.vault.read(source));
} else {
await plugin.app.vault.create(targetPath,await plugin.app.vault.read(source))
//await plugin.app.vault.copy(source,targetPath);
}
}
const syncModifyCreate = async (file:TAbstractFile) => {
if(!(file instanceof TFile)) return;
if(plugin.excalidrawSync.has(file.path)) {
plugin.excalidrawSync.delete(file.path);
return;
}
if(plugin.settings.excalidrawSync) {
switch (file.extension) {
case EXCALIDRAW_FILE_EXTENSION:
const syncFilePath = getSyncFilepath(file.path);
await syncCopy(file,syncFilePath);
break;
case 'md':
if(file.path.startsWith(normalizePath(plugin.settings.syncFolder))) {
const excalidrawNewPath = getExcalidrawFilepath(file.path);
await syncCopy(file,excalidrawNewPath);
reloadDrawing(excalidrawNewPath,excalidrawNewPath);
}
break;
}
}
};
this.syncModifyCreate = syncModifyCreate;
plugin.app.vault.on('create', syncModifyCreate);
plugin.app.vault.on('modify', syncModifyCreate);
/*Excalidraw Sync End*/
//watch filename change to rename .svg
plugin.app.vault.on('rename',async (file,oldPath) => {
plugin.transclusionIndex.updateTransclusion(oldPath,file.path);
if(!(file instanceof TFile)) return;
/*Excalidraw Sync Begin*/
if(plugin.settings.excalidrawSync) {
if(plugin.excalidrawSync.has(file.path)) {
plugin.excalidrawSync.delete(file.path);
} else {
switch (file.extension) {
case EXCALIDRAW_FILE_EXTENSION:
const syncOldPath = getSyncFilepath(oldPath);
const syncNewPath = getSyncFilepath(file.path);
const oldFile = plugin.app.vault.getAbstractFileByPath(syncOldPath);
if(oldFile && oldFile instanceof TFile) {
plugin.excalidrawSync.add(syncNewPath);
await createPathIfNotThere(syncNewPath);
await plugin.app.vault.rename(oldFile,syncNewPath);
} else {
await syncCopy(file,syncNewPath);
}
break;
case 'md':
if(file.path.startsWith(normalizePath(plugin.settings.syncFolder))) {
const excalidrawOldPath = getExcalidrawFilepath(oldPath);
const excalidrawNewPath = getExcalidrawFilepath(file.path);
const excalidrawOldFile = plugin.app.vault.getAbstractFileByPath(excalidrawOldPath);
if(excalidrawOldFile && excalidrawOldFile instanceof TFile) {
plugin.excalidrawSync.add(excalidrawNewPath);
await createPathIfNotThere(excalidrawNewPath);
await plugin.app.vault.rename(excalidrawOldFile,excalidrawNewPath);
} else {
await syncCopy(file,excalidrawNewPath);
}
reloadDrawing(excalidrawOldFile.path,excalidrawNewPath);
}
break;
}
}
}
/*Excalidraw Sync End*/
if (file.extension != EXCALIDRAW_FILE_EXTENSION) return;
if (!plugin.settings.keepInSync) return;
const oldSVGpath = oldPath.substring(0,oldPath.lastIndexOf('.'+EXCALIDRAW_FILE_EXTENSION)) + '.svg';
const svgFile = plugin.app.vault.getAbstractFileByPath(normalizePath(oldSVGpath));
if(svgFile && svgFile instanceof TFile) {
const newSVGpath = file.path.substring(0,file.path.lastIndexOf('.'+EXCALIDRAW_FILE_EXTENSION)) + '.svg';
await plugin.app.vault.rename(svgFile,newSVGpath);
}
});
//watch file delete and delete corresponding .svg
plugin.app.vault.on('delete',async (file:TFile) => {
if (!(file instanceof TFile)) return;
/*Excalidraw Sync Begin*/
if(plugin.settings.excalidrawSync) {
if(plugin.excalidrawSync.has(file.path)) {
plugin.excalidrawSync.delete(file.path);
} else {
switch (file.extension) {
case EXCALIDRAW_FILE_EXTENSION:
const syncFilePath = getSyncFilepath(file.path);
const oldFile = plugin.app.vault.getAbstractFileByPath(syncFilePath);
if(oldFile && oldFile instanceof TFile) {
plugin.excalidrawSync.add(oldFile.path);
plugin.app.vault.delete(oldFile);
}
break;
case "md":
if(file.path.startsWith(normalizePath(plugin.settings.syncFolder))) {
const excalidrawPath = getExcalidrawFilepath(file.path);
const excalidrawFile = plugin.app.vault.getAbstractFileByPath(excalidrawPath);
if(excalidrawFile && excalidrawFile instanceof TFile) {
plugin.excalidrawSync.add(excalidrawFile.path);
await closeDrawing(excalidrawFile.path);
plugin.app.vault.delete(excalidrawFile);
}
}
break;
}
}
}
/*Excalidraw Sync End*/
if (file.extension != EXCALIDRAW_FILE_EXTENSION) return;
closeDrawing(file.path);
if (this.settings.keepInSync) {
if (plugin.settings.keepInSync) {
const svgPath = file.path.substring(0,file.path.lastIndexOf('.'+EXCALIDRAW_FILE_EXTENSION)) + '.svg';
const svgFile = this.app.vault.getAbstractFileByPath(normalizePath(svgPath));
const svgFile = plugin.app.vault.getAbstractFileByPath(normalizePath(svgPath));
if(svgFile && svgFile instanceof TFile) {
await this.app.vault.delete(svgFile);
await plugin.app.vault.delete(svgFile);
}
}
});
//save open drawings when user quits the application
plugin.app.workspace.on('quit',(tasks) => {
const leaves = plugin.app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW);
for (let i=0;i<leaves.length;i++) {
(leaves[i].view as ExcalidrawView).save();
}
});
//save Excalidraw leaf and update embeds when switching to another leaf
plugin.app.workspace.on('active-leaf-change',(leaf:WorkspaceLeaf) => {
if(plugin.activeExcalidrawView) {
plugin.activeExcalidrawView.save();
plugin.triggerEmbedUpdates();
}
plugin.activeExcalidrawView = (leaf.view.getViewType() == VIEW_TYPE_EXCALIDRAW) ? leaf.view as ExcalidrawView : null;
if(plugin.activeExcalidrawView)
plugin.lastActiveExcalidrawFilePath = plugin.activeExcalidrawView.file.path;
});
}
onunload() {
destroyExcalidrawAutomate();
}
@@ -319,7 +531,7 @@ export default class ExcalidrawPlugin extends Plugin {
.forEach((el) => el.dispatchEvent(e));
}
public async openDrawing(drawingFile: TFile, onNewPane: boolean) {
public openDrawing(drawingFile: TFile, onNewPane: boolean) {
const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW);
let leaf:WorkspaceLeaf = null;
@@ -349,10 +561,11 @@ export default class ExcalidrawPlugin extends Plugin {
}
public async createDrawing(filename: string, onNewPane: boolean, foldername?: string, initData?:string) {
const fname = foldername ? normalizePath(foldername)+'/'+filename : normalizePath(this.settings.folder) + '/' + filename;
const folder = this.app.vault.getAbstractFileByPath(normalizePath(foldername ? foldername: this.settings.folder));
const folderpath = normalizePath(foldername ? foldername: this.settings.folder);
const fname = folderpath +'/'+ filename;
const folder = this.app.vault.getAbstractFileByPath(folderpath);
if (!(folder && folder instanceof TFolder)) {
await this.app.vault.createFolder(this.settings.folder);
await this.app.vault.createFolder(folderpath);
}
if(initData) {

View File

@@ -16,6 +16,10 @@ export interface ExcalidrawSettings {
autoexportPNG: boolean,
keepInSync: boolean,
library: string,
/*Excalidraw Sync Begin*/
syncFolder: string,
excalidrawSync: boolean,
/*Excalidraw Sync End*/
}
export const DEFAULT_SETTINGS: ExcalidrawSettings = {
@@ -28,6 +32,10 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
autoexportPNG: false,
keepInSync: false,
library: `{"type":"excalidrawlib","version":1,"library":[]}`,
/*Excalidraw Sync Begin*/
syncFolder: 'excalidraw_sync',
excalidrawSync: false,
/*Excalidraw Sync End*/
}
export class ExcalidrawSettingTab extends PluginSettingTab {
@@ -140,5 +148,43 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
await this.plugin.saveSettings();
}));
/*Excalidraw Sync Begin*/
this.containerEl.createEl('h1', {text: 'Excalidraw sync'});
this.containerEl.createEl('h3', {text: 'This is a hack and a temporary workaround. Turn it on only if you are comfortable with hacky solutions...'});
this.containerEl.createEl('p', {text: 'By enabling this feature Excalidraw will sync drawings to a sync folder where drawings are stored in an ".md" file. ' +
'This will allow Obsidian sync to synchronize Excalidraw drawings as well... ' +
'Whenever your drawing changes, the corresponding file in the sync folder will also get updated. Similarly, whenever a file is synchronized to the sync folder ' +
'by Obsidian sync, Excalidraw will sync it with the .excalidraw file in your vault.'});
this.containerEl.createEl('p', {text: 'Because this is a temporary workaround until Obsidian sync is ready, I didn\'t implement extensive application logic to manage sync. ' +
'Sync might get confused requiring some manual intervention.'});
new Setting(containerEl)
.setName('Excalidraw sync folder')
.setDesc('Configure the folder first, before activating the feature! ' +
'This is the root folder for your mirrored excalidraw drawings. ' +
'Don\'t save other files here, as my algorithm is not prepared to handle those... and I can\'t predict the outcome. ')
.addText(text => text
.setPlaceholder('.excalidraw_sync')
.setValue(this.plugin.settings.syncFolder)
.onChange(async (value) => {
this.plugin.settings.syncFolder = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Excalidraw sync')
.setDesc('Enable Excalidraw Sync')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.excalidrawSync)
.onChange(async (value) => {
this.plugin.settings.excalidrawSync = value;
await this.plugin.saveSettings();
this.plugin.initiateSync();
}));
/*Excalidraw Sync End*/
}
}

View File

@@ -37,4 +37,8 @@ div.excalidraw-svg-right {
div.excalidraw-svg-left {
text-align: left;
}
button.ToolIcon_type_button[title="Export"] {
display:none;
}

View File

@@ -13,7 +13,7 @@
"dom",
"es5",
"scripthost",
"es2015",
"es2020",
"DOM.Iterable"
],
"jsx": "react",

View File

@@ -1,5 +1,3 @@
{
"1.0.7": "0.11.13",
"1.0.6": "0.11.13",
"1.0.5": "0.11.13"
"1.0.10": "0.11.13"
}