mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2025-08-06 05:46:28 +00:00
Compare commits
66 Commits
1.2.7
...
ImageEleme
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78fb37b173 | ||
|
|
a17638717f | ||
|
|
70de8ba2f8 | ||
|
|
e8a29a2715 | ||
|
|
7b1f13391c | ||
|
|
33081b1a84 | ||
|
|
aafd9f17f8 | ||
|
|
a27da5f5f5 | ||
|
|
472b58a417 | ||
|
|
1bba254eaf | ||
|
|
a0e47c390c | ||
|
|
caa1281d23 | ||
|
|
3fb2cbba14 | ||
|
|
8f1ec2acbc | ||
|
|
3e2d85dd09 | ||
|
|
ec3e9fd5b7 | ||
|
|
784a7cb6bf | ||
|
|
e8666797d7 | ||
|
|
5c2c1ebf5e | ||
|
|
ecd19dd072 | ||
|
|
377927c891 | ||
|
|
9f28c974f7 | ||
|
|
1b9fa6a790 | ||
|
|
4dd8271223 | ||
|
|
3e62cd33a2 | ||
|
|
c670ecb09c | ||
|
|
f5307db33e | ||
|
|
7e216306c0 | ||
|
|
e3daf5d22e | ||
|
|
a85a46cbae | ||
|
|
ac16f5427b | ||
|
|
edc92472df | ||
|
|
e66b7aef7f | ||
|
|
7e9d5e8867 | ||
|
|
167918f718 | ||
|
|
65af29c2ef | ||
|
|
b19e1b6dcb | ||
|
|
f7263543fa | ||
|
|
c6339b28ac | ||
|
|
f24e4fce9c | ||
|
|
5eff9b2e54 | ||
|
|
d89c019612 | ||
|
|
01d3c13cce | ||
|
|
de68ebbe7d | ||
|
|
caee4f7500 | ||
|
|
6d28546677 | ||
|
|
ec5a13f9e4 | ||
|
|
b788118880 | ||
|
|
6e22e0a428 | ||
|
|
8b8b469569 | ||
|
|
789851c0c4 | ||
|
|
816de255ee | ||
|
|
54d4eb7ab4 | ||
|
|
e3242ebfb7 | ||
|
|
2e36d83abc | ||
|
|
6552e6bd7b | ||
|
|
21ff1833a8 | ||
|
|
1b931abd38 | ||
|
|
fe28098776 | ||
|
|
72c158e08b | ||
|
|
5133ab028b | ||
|
|
5fc0f70ded | ||
|
|
08f489f1c5 | ||
|
|
dd476b564a | ||
|
|
b7a7c9473e | ||
|
|
cc7dc16810 |
10
README.md
10
README.md
@@ -41,8 +41,12 @@ To convert files you have the following options:
|
||||
- Supports hyperlinks e.g. `https://zsolt.blog`, `[Obsidian](https://obsidian.md)`, and internal links e.g. `[[My file in vault|Alias]]` in drawing text.
|
||||
- Links will update when files are moved or renamed, if you have the Obsidian setting Files & Links/Automatically Update Internal Links enalbled.
|
||||
- Links in drawings will show up in backlinks of documents
|
||||
- Transclusions are supported i.e. `![[myfile#^blockref]]` will convert in the drawing into the transcluded text
|
||||
- Transclusions are supported
|
||||
- `![[myfile#^blockref]]` will convert in the drawing into the transcluded text of the block
|
||||
- `![[myfile#section]]` also works, this will transclude the section
|
||||
- you can also specify word wrapping for transcluded text by adding the max character count in curly brackets right after the transclusion e.g. `![[myfile#^blockref]]{40}` will wrap text at 40 characters.
|
||||
- For convenience you can also use the command palette to insert links into drawings
|
||||
- CTRL/META + hover to bring up the Obsidian quick preview for the link. (On Mac it is CTRL+CMD+hover).
|
||||
- CTRL/META + CLICK a text element to open it as a link.
|
||||
- CTRL/META + ALT + CLICK to create the file (if it does not yet exist) and open it
|
||||
- CTRL/META + SHIFT + CLICK to open the file in a new pane
|
||||
@@ -54,6 +58,10 @@ To convert files you have the following options:
|
||||
- You can add metadata to the YAML front matter of drawings
|
||||
- Anything you add between the frontmatter and the `# Text Elements` heading will be ignored by Excalidraw, i.e. you can add whatever you like here, it will be preserved as part of the document.
|
||||
- Excalidraw documents now show in graph view.
|
||||
- The following front matter keys will customize how the drawing is displayed - overriding general settings:
|
||||
- `excalidraw-link-prefix: "📍"` preview prefix for internal links
|
||||
- `excalidraw-url-prefix: "🌐"` preview prefix for external links
|
||||
- `excalidraw-link-brackets: true|false` whether or not to display brackets around links in preview
|
||||
- Includes full [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/)
|
||||
- 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.
|
||||
|
||||
@@ -2,44 +2,137 @@
|
||||
## Attributes and functions overview
|
||||
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;
|
||||
};
|
||||
```
|
||||
```typescript
|
||||
export interface ExcalidrawAutomate extends Window {
|
||||
ExcalidrawAutomate: {
|
||||
plugin: ExcalidrawPlugin;
|
||||
elementsDict: {};
|
||||
style: {
|
||||
strokeColor: string;
|
||||
backgroundColor: string;
|
||||
angle: number;
|
||||
fillStyle: FillStyle;
|
||||
strokeWidth: number;
|
||||
storkeStyle: StrokeStyle;
|
||||
roughness: number;
|
||||
opacity: number;
|
||||
strokeSharpness: StrokeSharpness;
|
||||
fontFamily: number;
|
||||
fontSize: number;
|
||||
textAlign: string;
|
||||
verticalAlign: string;
|
||||
startArrowHead: string;
|
||||
endArrowHead: string;
|
||||
}
|
||||
canvas: {
|
||||
theme: string,
|
||||
viewBackgroundColor: string,
|
||||
gridSize: number
|
||||
};
|
||||
setFillStyle (val:number): void;
|
||||
setStrokeStyle (val:number): void;
|
||||
setStrokeSharpness (val:number): void;
|
||||
setFontFamily (val:number): void;
|
||||
setTheme (val:number): void;
|
||||
addToGroup (objectIds:[]):string;
|
||||
toClipboard (templatePath?:string): void;
|
||||
getElements ():ExcalidrawElement[];
|
||||
getElement (id:string):ExcalidrawElement;
|
||||
create (
|
||||
params?: {
|
||||
filename?: string,
|
||||
foldername?:string,
|
||||
templatePath?:string,
|
||||
onNewPane?: boolean,
|
||||
frontmatterKeys?:{
|
||||
"excalidraw-plugin"?: "raw"|"parsed",
|
||||
"excalidraw-link-prefix"?: string,
|
||||
"excalidraw-link-brackets"?: boolean,
|
||||
"excalidraw-url-prefix"?: string
|
||||
}
|
||||
}
|
||||
):Promise<string>;
|
||||
createSVG (templatePath?:string):Promise<SVGSVGElement>;
|
||||
createPNG (templatePath?:string):Promise<any>;
|
||||
wrapText (text:string, lineLen:number):string;
|
||||
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;
|
||||
addBlob (topX:number, topY:number, width:number, height:number):string;
|
||||
addText (
|
||||
topX:number,
|
||||
topY:number,
|
||||
text:string,
|
||||
formatting?: {
|
||||
wrapAt?:number,
|
||||
width?:number,
|
||||
height?:number,
|
||||
textAlign?: string,
|
||||
box?: "box"|"blob"|"ellipse"|"diamond",
|
||||
boxPadding?: number
|
||||
},
|
||||
id?:string
|
||||
):string;
|
||||
addLine(points: [[x:number,y:number]]):string;
|
||||
addArrow (
|
||||
points: [[x:number,y:number]],
|
||||
formatting?: {
|
||||
startArrowHead?:string,
|
||||
endArrowHead?:string,
|
||||
startObjectId?:string,
|
||||
endObjectId?:string
|
||||
}
|
||||
):string ;
|
||||
connectObjects (
|
||||
objectA: string,
|
||||
connectionA: ConnectionPoint,
|
||||
objectB: string,
|
||||
connectionB: ConnectionPoint,
|
||||
formatting?: {
|
||||
numberOfPoints?: number,
|
||||
startArrowHead?:string,
|
||||
endArrowHead?:string,
|
||||
padding?: number
|
||||
}
|
||||
):void;
|
||||
clear (): void;
|
||||
reset (): void;
|
||||
isExcalidrawFile (f:TFile): boolean;
|
||||
//view manipulation
|
||||
targetView: ExcalidrawView;
|
||||
setView (view:ExcalidrawView|"first"|"active"):ExcalidrawView;
|
||||
getExcalidrawAPI ():any;
|
||||
getViewElements ():ExcalidrawElement[];
|
||||
deleteViewElements (el: ExcalidrawElement[]):boolean;
|
||||
getViewSelectedElement( ):ExcalidrawElement;
|
||||
getViewSelectedElements ():ExcalidrawElement[];
|
||||
viewToggleFullScreen (forceViewMode?:boolean):void;
|
||||
connectObjectWithViewSelectedElement (
|
||||
objectA:string,
|
||||
connectionA: ConnectionPoint,
|
||||
connectionB: ConnectionPoint,
|
||||
formatting?: {
|
||||
numberOfPoints?: number,
|
||||
startArrowHead?:string,
|
||||
endArrowHead?:string,
|
||||
padding?: number
|
||||
}
|
||||
):boolean;
|
||||
addElementsToView (repositionToCursor:boolean, save:boolean):Promise<boolean>;
|
||||
onDropHook (data: {
|
||||
ea: ExcalidrawAutomate,
|
||||
event: React.DragEvent<HTMLDivElement>,
|
||||
draggable: any, //Obsidian draggable object
|
||||
type: "file"|"text"|"unknown",
|
||||
payload: {
|
||||
files: TFile[], //TFile[] array of dropped files
|
||||
text: string, //string
|
||||
},
|
||||
excalidrawFile: TFile, //the file receiving the drop event
|
||||
view: ExcalidrawView, //the excalidraw view receiving the drop
|
||||
pointerPosition: {x:number, y:number} //the pointer position on canvas at the time of drop
|
||||
}):boolean;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -12,4 +12,7 @@ String. Valid values are "light" and "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`.
|
||||
Allowed values are [HTML color names](https://www.w3schools.com/colors/colors_names.asp), hexadecimal RGB strings e.g. `#FF0000` for red, or `transparent`.
|
||||
|
||||
### gridSize
|
||||
Number. The size of the grid. If set to zero, no grid is displayed.
|
||||
@@ -1,6 +1,6 @@
|
||||
# [◀ Excalidraw Automate How To](../readme.md)
|
||||
## Introduction to the API
|
||||
You can access Excalidraw Automate via the ExcalidrawAutomate object. I recommend starting your Automate scripts with the following code.
|
||||
You can access Excalidraw Automate via the ExcalidrawAutomate object. I recommend starting your Automate scripts with the following code:
|
||||
|
||||
*Use CTRL+Shift+V to paste code into Obsidian!*
|
||||
```javascript
|
||||
@@ -15,11 +15,11 @@ The second line resets ExcalidrawAutomate to defaults. This is important as you
|
||||
### 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
|
||||
3. Call `await ea.create();` to instantiate the drawing, or use `ea.setView();` followed by `ea.addElementsToView();` to add your elements to an existing view, or create a PNG or SVG image out of your elements using `await ea.createSVG();` or `await ea.createPNG();`;
|
||||
|
||||
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.
|
||||
You can change the 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 that. 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
|
||||
### Before we dive deeper, here are three a simple example Templater 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.
|
||||
|
||||
@@ -55,4 +55,46 @@ This simple script gives you significant additional flexibility over Excalidraw
|
||||
```
|
||||
The script will generate the following drawing:
|
||||
|
||||

|
||||

|
||||
|
||||
#### Add a TextElement in a box to an open Excalidraw View.
|
||||
Position the new element under the currently selected element, with an arrow from the selected element to the added text.
|
||||
|
||||
*Use CTRL+Shift+V to paste code into Obsidian!*
|
||||
```javascript
|
||||
<%*
|
||||
const ea = ExcalidrawAutomate;
|
||||
ea.reset();
|
||||
ea.setView("first");
|
||||
selectedElement = ea.getViewSelectedElement();
|
||||
ea.setStrokeSharpness(0);
|
||||
const boxPadding = 5;
|
||||
id = ea.addText(
|
||||
selectedElement.x + boxPadding,
|
||||
selectedElement.y+selectedElement.height+100,
|
||||
"[[Next process step]]",
|
||||
{
|
||||
textAlign:"center",
|
||||
box:true,
|
||||
boxPadding:boxPadding,
|
||||
width:selectedElement.width-boxPadding*2,
|
||||
}
|
||||
);
|
||||
ea.setStrokeSharpness(1);
|
||||
ea.style.roughness= 0;
|
||||
ea.connectObjectWithViewSelectedElement(
|
||||
id,
|
||||
"top",
|
||||
"bottom",
|
||||
{
|
||||
numberOfPoints:2,
|
||||
startArrowHead:"arrow",
|
||||
endArrowHead:"dot",
|
||||
padding:5
|
||||
});
|
||||
ea.addElementsToView();
|
||||
%>
|
||||
```
|
||||
[Click here to view animation](https://user-images.githubusercontent.com/14358394/131967188-2a488e38-f742-49d9-ae98-33238a8d4712.mp4)
|
||||
|
||||
|
||||
|
||||
@@ -14,7 +14,20 @@ Returns the `id` of the object. The `id` is required when connecting objects wit
|
||||
|
||||
### addText()
|
||||
```typescript
|
||||
addText(topX:number, topY:number, text:string, formatting?:{width:number, height:number,textAlign: string, verticalAlign:string, box: boolean, boxPadding: number}):string
|
||||
addText(
|
||||
topX:number,
|
||||
topY:number,
|
||||
text:string,
|
||||
formatting?:{
|
||||
wrapAt?:number,
|
||||
width?:number,
|
||||
height?:number,
|
||||
textAlign?:string,
|
||||
box?: "box"|"blob"|"ellipse"|"diamond",
|
||||
boxPadding?:number
|
||||
},
|
||||
id?:string
|
||||
):string
|
||||
```
|
||||
|
||||
Adds text to the drawing.
|
||||
@@ -22,19 +35,21 @@ 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}`
|
||||
- If you want to add a box around the text, set `{box:"box"|"blob"|"ellipse"|"diamond"}`
|
||||
|
||||
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.
|
||||
Returns the `id` of the object. The `id` is required when connecting objects with lines. See later. If `{box:}` then returns the id of the enclosing box object.
|
||||
|
||||
### addLine()
|
||||
```typescript
|
||||
addLine(points: [[x:number,y:number]]):void
|
||||
addLine(points: [[x:number,y:number]]):string
|
||||
```
|
||||
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".
|
||||
|
||||
Returns the `id` of the object.
|
||||
|
||||
### addArrow()
|
||||
```typescript
|
||||
addArrow(points: [[x:number,y:number]],formatting?:{startArrowHead:string,endArrowHead:string,startObjectId:string,endObjectId:string}):void
|
||||
addArrow(points: [[x:number,y:number]],formatting?:{startArrowHead?:string,endArrowHead?:string,startObjectId?:string,endObjectId?:string}):string ;
|
||||
```
|
||||
|
||||
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".
|
||||
@@ -43,12 +58,14 @@ Adds an arrow following the points provided. Must include at least two points `p
|
||||
|
||||
`startObjectId` and `endObjectId` are the object id's of connected objects. I recommend using `connectObjects` instead calling addArrow() for the purpose of connecting objects.
|
||||
|
||||
Returns the `id` of the object.
|
||||
|
||||
### 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.
|
||||
Connects two objects with an arrow. Will do nothing if either of the two elements is of type `line`, `arrow`, or `freedraw`.
|
||||
|
||||
`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.
|
||||
|
||||
@@ -60,6 +77,6 @@ Connects two objects with an arrow.
|
||||
|
||||
### addToGroup()
|
||||
```typescript
|
||||
addToGroup(objectIds:[]):void
|
||||
addToGroup(objectIds:[]):string
|
||||
```
|
||||
Groups objects listed in `objectIds`.
|
||||
Groups objects listed in `objectIds`. Returns the `id` of the group.
|
||||
@@ -1,5 +1,11 @@
|
||||
# [◀ Excalidraw Automate How To](../readme.md)
|
||||
## Utility functions
|
||||
### isExcalidrawFile()
|
||||
```typescript
|
||||
isExcalidrawFile(f:TFile): boolean
|
||||
```
|
||||
Returns true if the file provided is a valid Excalidraw file (either a legacy `*.excalidraw` file or a markdown file with the excalidraw key in the front-matter).
|
||||
|
||||
### clear()
|
||||
`clear()` will clear objects from cache, but will retain element style settings.
|
||||
|
||||
@@ -12,11 +18,24 @@ 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 existing drawing.
|
||||
|
||||
### getElements()
|
||||
```typescript
|
||||
getElements():ExcalidrawElement[];
|
||||
```
|
||||
Returns the elements in ExcalidrawAutomate as an array of ExcalidrawElements. This format is usefull when working with ExcalidrawRef.
|
||||
|
||||
### getElement()
|
||||
```typescript
|
||||
getElement(id:string):ExcalidrawElement;
|
||||
```
|
||||
|
||||
Returns the element object matching the id. If the element does not exist, returns null.
|
||||
|
||||
### create()
|
||||
```typescript
|
||||
async create(params?:{filename: string, foldername:string, templatePath:string, onNewPane: boolean})
|
||||
```
|
||||
Creates the drawing and opens it.
|
||||
Creates the drawing and opens it. Returns the full filepath of the created file.
|
||||
|
||||
`filename` is the filename without extension of the drawing to be created. If `null`, then Excalidraw will generate a filename.
|
||||
|
||||
@@ -26,9 +45,30 @@ Creates the drawing and opens it.
|
||||
|
||||
`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.
|
||||
|
||||
`frontmatterKeys` are the set of frontmatter keys to apply to the document
|
||||
{
|
||||
excalidraw-plugin?: "raw"|"parsed",
|
||||
excalidraw-link-prefix?: string,
|
||||
excalidraw-link-brackets?: boolean,
|
||||
excalidraw-url-prefix?: string
|
||||
}
|
||||
|
||||
Example:
|
||||
```javascript
|
||||
create({filename:"my drawing", foldername:"myfolder/subfolder/", templatePath: "Excalidraw/template.excalidraw", onNewPane: true});
|
||||
create (
|
||||
{
|
||||
filename:"my drawing",
|
||||
foldername:"myfolder/subfolder/",
|
||||
templatePath: "Excalidraw/template.excalidraw",
|
||||
onNewPane: true,
|
||||
frontmatterKeys: {
|
||||
"excalidraw-plugin": "parsed",
|
||||
"excalidraw-link-prefix": "",
|
||||
"excalidraw-link-brackets": true,
|
||||
"excalidraw-url-prefix": "🌐",
|
||||
}
|
||||
}
|
||||
);
|
||||
```
|
||||
### createSVG()
|
||||
```typescript
|
||||
@@ -38,6 +78,144 @@ Returns an HTML SVGSVGElement containing the generated drawing.
|
||||
|
||||
### createPNG()
|
||||
```typescript
|
||||
async createPNG(templatePath?:string)
|
||||
async createPNG(templatePath?:string, scale:number=1)
|
||||
```
|
||||
Returns a blob containing a PNG image of the generated drawing.
|
||||
Returns a blob containing a PNG image of the generated drawing.
|
||||
|
||||
### wrapText()
|
||||
```typescript
|
||||
wrapText(text:string, lineLen:number):string
|
||||
```
|
||||
Returns a string wrapped to the provided max lineLen.
|
||||
|
||||
|
||||
### Accessing the open Excalidraw view
|
||||
You first need to initialize targetView, before using any of the view manipulation functions.
|
||||
|
||||
#### targetView
|
||||
```typescript
|
||||
targetView: ExcalidrawView
|
||||
```
|
||||
The open Excalidraw View configured as the target of the view operations. User `setView` to initialize.
|
||||
|
||||
#### setView()
|
||||
```typescript
|
||||
setView(view:ExcalidrawView|"first"|"active"):ExcalidrawView
|
||||
```
|
||||
Setting the ExcalidrawView that will be the target of the View operations. Valid `view` input values are:
|
||||
- an object instance of ExcalidrawView
|
||||
- "first": meaning if there are multiple Excalidraw Views open, pick the first that is returned by `app.workspace.getLeavesOfType("Excalidraw")`
|
||||
- "active": meaning the currently active view
|
||||
|
||||
#### getExcalidrawAPI()
|
||||
```typescript
|
||||
getExcalidrawAPI():any
|
||||
```
|
||||
Returns the native Excalidraw API (ref.current) for the active drawing specified in `targetView`.
|
||||
See Excalidraw documentation here: https://www.npmjs.com/package/@excalidraw/excalidraw#ref
|
||||
|
||||
#### getViewElements()
|
||||
```typescript
|
||||
getViewElements():ExcalidrawElement[]
|
||||
```
|
||||
|
||||
Returns all the elements from the view.
|
||||
|
||||
#### deleteViewElements()
|
||||
```typescript
|
||||
deleteViewElements(elToDelete: ExcalidrawElement[]):boolean
|
||||
```
|
||||
|
||||
Deletes those elements from the view that match the elements provided as the input parameter.
|
||||
|
||||
Example to delete the selected elements from the view:
|
||||
```typescript
|
||||
ea = ExcalidrawAutomate;
|
||||
ea.setView("active");
|
||||
el = ea.getViewSelectedElements();
|
||||
ea.deleteViewElements();
|
||||
```
|
||||
|
||||
#### getViewSelectedElement()
|
||||
```typescript
|
||||
getViewSelectedElement():ExcalidrawElement
|
||||
```
|
||||
|
||||
You first need to set the view calling `setView()`.
|
||||
|
||||
If an element is selected in the targetView the function returns the selected element. If multiple elements are selected, either by SHIFT+Clicking to select multiple elements, or by selecting a group, the first of the elements will be selected. If you want to specify which element to select from a group, double click the desired element in the group.
|
||||
|
||||
This function is helpful if you want to add a new element in relation to an existing element in your drawing.
|
||||
|
||||
#### getViewSelectedElements()
|
||||
```typescript
|
||||
getViewSelectedElements():ExcalidrawElement[]
|
||||
```
|
||||
|
||||
You first need to set the view calling `setView()`.
|
||||
|
||||
Gets the array of selected elements in the scene. Returns [] if no elements are selected.
|
||||
|
||||
Note: you can call `getExcalidrawAPI().getSceneElements()` to retreive all the elements in the scene.
|
||||
|
||||
#### viewToggleFullScreen()
|
||||
```typescript
|
||||
viewToggleFullScreen(forceViewMode?:boolean):void;
|
||||
```
|
||||
|
||||
Toggles targetView between fullscreen mode and normal mode. By setting forceViewMode to `true` will change Excalidraw mode to View mode. Default is `false`.
|
||||
|
||||
The function will do nothing on Obsidian Mobile.
|
||||
|
||||
#### connectObjectWithViewSelectedElement()
|
||||
```typescript
|
||||
connectObjectWithViewSelectedElement(objectA:string,connectionA: ConnectionPoint, connectionB: ConnectionPoint, formatting?:{numberOfPoints?: number,startArrowHead?:string,endArrowHead?:string, padding?: number}):boolean
|
||||
```
|
||||
Same as `connectObjects()`, but ObjectB is the currently selected element in the target ExcalidrawView. The function helps with placing an arrow between a newly created object and the selected element in the target ExcalidrawView.
|
||||
|
||||
#### addElementsToView()
|
||||
```typescript
|
||||
async addElementsToView(repositionToCursor:boolean=false, save:boolean=false):Promise<boolean>
|
||||
```
|
||||
Adds elements created with ExcalidrawAutomate to the target ExcalidrawView.
|
||||
`repositionToCursor` dafault is false
|
||||
- true: the elements will be moved such that the center point of the elements will be aligned with the current position of the pointer on ExcalidrawView. You can point and place elements to a desired location in your drawing using this switch.
|
||||
- false: elements will be positioned as defined by the x&y coordinates of each element.
|
||||
|
||||
`save` default is false
|
||||
- true: the drawing will be saved after the elements were added.
|
||||
- false: the drawing will be saved at the next autosave cycle. Use false when adding multiple elements one after the other. Else, best to use true, to minimize risk of data loss.
|
||||
|
||||
### onDropHook
|
||||
```typescript
|
||||
onDropHook (data: {
|
||||
ea: ExcalidrawAutomate,
|
||||
event: React.DragEvent<HTMLDivElement>,
|
||||
draggable: any, //Obsidian draggable object
|
||||
type: "file"|"text"|"unknown",
|
||||
payload: {
|
||||
files: TFile[], //TFile[] array of dropped files
|
||||
text: string, //string
|
||||
},
|
||||
excalidrawFile: TFile, //the file receiving the drop event
|
||||
view: ExcalidrawView, //the excalidraw view receiving the drop
|
||||
pointerPosition: {x:number, y:number} //the pointer position on canvas at the time of drop
|
||||
}):boolean;
|
||||
```
|
||||
|
||||
Callback function triggered when an draggable item is dropped on Excalidraw.
|
||||
The function should return a boolean value. True if the drop was handled by the hook and futher native processing should be stopped, and false if Excalidraw should continue with the processing of the drop.
|
||||
type of drop can be one of:
|
||||
- "file" if a file from Obsidian file explorer is dropped onto Excalidraw. In this case payload.files will contain the list of files dropped.
|
||||
- "text" if a link (e.g. url, or wiki link) or other text is dropped. In this case payload.text will contain the received string
|
||||
- "unknown" if Excalidraw plugin does not recognize the type of dropped object. In this case you can use React.DragEvent to analysed the dropped object.
|
||||
|
||||
Use Templater startup templates or similar to set the Hook function.
|
||||
|
||||
```typescript
|
||||
ea = ExcalidrawAutomate;
|
||||
ea.onDropHook = (data) => {
|
||||
console.log(data);
|
||||
return false;
|
||||
}
|
||||
```
|
||||
@@ -59,9 +59,5 @@ function buildMindmap(subtasks, depth, offset, parentObjectID) {
|
||||
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);
|
||||
})();
|
||||
ea.createSVG().then((svg)=>dv.span(svg.outerHTML));
|
||||
```
|
||||
@@ -52,9 +52,5 @@ function buildMindmap(subtasks, depth, offset, parentObjectID) {
|
||||
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);
|
||||
})();
|
||||
ea.createSVG().then((svg)=>dv.span(svg.outerHTML));
|
||||
```
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "1.2.6",
|
||||
"minAppVersion": "0.11.13",
|
||||
"version": "1.3.16",
|
||||
"minAppVersion": "0.12.0",
|
||||
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
|
||||
"author": "Zsolt Viczian",
|
||||
"authorUrl": "https://zsolt.blog",
|
||||
|
||||
@@ -11,11 +11,12 @@
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@excalidraw/excalidraw": "^0.9.0",
|
||||
"@zsviczian/excalidraw": "0.9.0-obsidian-image-support-3",
|
||||
"monkey-around": "^2.2.0",
|
||||
"react": "^17.0.2",
|
||||
"react-dom": "^17.0.2",
|
||||
"react-scripts": "^1.1.5"
|
||||
"react-scripts": "^1.1.5",
|
||||
"roughjs": "4.4.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.14.6",
|
||||
@@ -30,7 +31,7 @@
|
||||
"@types/react-dom": "^17.0.8",
|
||||
"cross-env": "^7.0.3",
|
||||
"nanoid": "^3.1.23",
|
||||
"obsidian": "https://github.com/obsidianmd/obsidian-api/tarball/master",
|
||||
"obsidian": "^0.12.16",
|
||||
"rollup": "^2.52.3",
|
||||
"rollup-plugin-visualizer": "^5.5.0",
|
||||
"tslib": "^2.3.0",
|
||||
|
||||
@@ -3,7 +3,8 @@ import {
|
||||
FillStyle,
|
||||
StrokeStyle,
|
||||
StrokeSharpness,
|
||||
} from "@excalidraw/excalidraw/types/element/types";
|
||||
ExcalidrawElement,
|
||||
} from "@zsviczian/excalidraw/types/element/types";
|
||||
import {
|
||||
normalizePath,
|
||||
TFile
|
||||
@@ -13,16 +14,20 @@ import { getJSON } from "./ExcalidrawData";
|
||||
import {
|
||||
FRONTMATTER,
|
||||
nanoid,
|
||||
JSON_parse
|
||||
JSON_parse,
|
||||
VIEW_TYPE_EXCALIDRAW,
|
||||
MAX_IMAGE_SIZE
|
||||
} from "./constants";
|
||||
import { getObsidianImage, wrapText } from "./Utils";
|
||||
import { AppState } from "@zsviczian/excalidraw/types/types";
|
||||
|
||||
declare type ConnectionPoint = "top"|"bottom"|"left"|"right";
|
||||
|
||||
export interface ExcalidrawAutomate extends Window {
|
||||
ExcalidrawAutomate: {
|
||||
plugin: ExcalidrawPlugin;
|
||||
elementIds: [];
|
||||
elementsDict: {},
|
||||
elementsDict: {};
|
||||
imagesDict: {};
|
||||
style: {
|
||||
strokeColor: string;
|
||||
backgroundColor: string;
|
||||
@@ -40,27 +45,115 @@ export interface ExcalidrawAutomate extends Window {
|
||||
startArrowHead: string;
|
||||
endArrowHead: string;
|
||||
}
|
||||
canvas: {theme: string, viewBackgroundColor: string};
|
||||
setFillStyle(val:number): void;
|
||||
setStrokeStyle(val:number): void;
|
||||
setStrokeSharpness(val:number): void;
|
||||
setFontFamily(val:number): void;
|
||||
setTheme(val:number): void;
|
||||
addToGroup(objectIds:[]):void;
|
||||
toClipboard(templatePath?:string): void;
|
||||
create(params?:{filename: string, foldername:string, templatePath:string, onNewPane: boolean}):Promise<void>;
|
||||
createSVG(templatePath?:string):Promise<SVGSVGElement>;
|
||||
createPNG(templatePath?:string):Promise<any>;
|
||||
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;
|
||||
addText(topX:number, topY:number, text:string, formatting?:{width:number, height:number,textAlign: string, verticalAlign:string, box: boolean, boxPadding: number}):string;
|
||||
addLine(points: [[x:number,y:number]]):void;
|
||||
addArrow(points: [[x:number,y:number]],formatting?:{startArrowHead:string,endArrowHead:string,startObjectId:string,endObjectId:string}):void ;
|
||||
connectObjects(objectA: string, connectionA: ConnectionPoint, objectB: string, connectionB: ConnectionPoint, formatting?:{numberOfPoints: number,startArrowHead:string,endArrowHead:string, padding: number}):void;
|
||||
clear(): void;
|
||||
reset(): void;
|
||||
isExcalidrawFile(f:TFile): boolean;
|
||||
canvas: {
|
||||
theme: string,
|
||||
viewBackgroundColor: string,
|
||||
gridSize: number
|
||||
};
|
||||
setFillStyle (val:number): void;
|
||||
setStrokeStyle (val:number): void;
|
||||
setStrokeSharpness (val:number): void;
|
||||
setFontFamily (val:number): void;
|
||||
setTheme (val:number): void;
|
||||
addToGroup (objectIds:[]):string;
|
||||
toClipboard (templatePath?:string): void;
|
||||
getElements ():ExcalidrawElement[];
|
||||
getElement (id:string):ExcalidrawElement;
|
||||
create (
|
||||
params?: {
|
||||
filename?: string,
|
||||
foldername?:string,
|
||||
templatePath?:string,
|
||||
onNewPane?: boolean,
|
||||
frontmatterKeys?:{
|
||||
"excalidraw-plugin"?: "raw"|"parsed",
|
||||
"excalidraw-link-prefix"?: string,
|
||||
"excalidraw-link-brackets"?: boolean,
|
||||
"excalidraw-url-prefix"?: string
|
||||
}
|
||||
}
|
||||
):Promise<string>;
|
||||
createSVG (templatePath?:string):Promise<SVGSVGElement>;
|
||||
createPNG (templatePath?:string):Promise<any>;
|
||||
wrapText (text:string, lineLen:number):string;
|
||||
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;
|
||||
addBlob (topX:number, topY:number, width:number, height:number):string;
|
||||
addText (
|
||||
topX:number,
|
||||
topY:number,
|
||||
text:string,
|
||||
formatting?: {
|
||||
wrapAt?:number,
|
||||
width?:number,
|
||||
height?:number,
|
||||
textAlign?: string,
|
||||
box?: boolean|"box"|"blob"|"ellipse"|"diamond",
|
||||
boxPadding?: number
|
||||
},
|
||||
id?:string
|
||||
):string;
|
||||
addLine(points: [[x:number,y:number]]):string;
|
||||
addArrow (
|
||||
points: [[x:number,y:number]],
|
||||
formatting?: {
|
||||
startArrowHead?:string,
|
||||
endArrowHead?:string,
|
||||
startObjectId?:string,
|
||||
endObjectId?:string
|
||||
}
|
||||
):string ;
|
||||
addImage(topX:number, topY:number, imageFile: TFile):Promise<string>;
|
||||
connectObjects (
|
||||
objectA: string,
|
||||
connectionA: ConnectionPoint,
|
||||
objectB: string,
|
||||
connectionB: ConnectionPoint,
|
||||
formatting?: {
|
||||
numberOfPoints?: number,
|
||||
startArrowHead?:string,
|
||||
endArrowHead?:string,
|
||||
padding?: number
|
||||
}
|
||||
):void;
|
||||
clear (): void;
|
||||
reset (): void;
|
||||
isExcalidrawFile (f:TFile): boolean;
|
||||
//view manipulation
|
||||
targetView: ExcalidrawView;
|
||||
setView (view:ExcalidrawView|"first"|"active"):ExcalidrawView;
|
||||
getExcalidrawAPI ():any;
|
||||
getViewElements ():ExcalidrawElement[];
|
||||
deleteViewElements (el: ExcalidrawElement[]):boolean;
|
||||
getViewSelectedElement ():ExcalidrawElement;
|
||||
getViewSelectedElements ():ExcalidrawElement[];
|
||||
viewToggleFullScreen (forceViewMode?:boolean):void;
|
||||
connectObjectWithViewSelectedElement (
|
||||
objectA:string,
|
||||
connectionA: ConnectionPoint,
|
||||
connectionB: ConnectionPoint,
|
||||
formatting?: {
|
||||
numberOfPoints?: number,
|
||||
startArrowHead?:string,
|
||||
endArrowHead?:string,
|
||||
padding?: number
|
||||
}
|
||||
):boolean;
|
||||
addElementsToView (repositionToCursor:boolean, save:boolean):Promise<boolean>;
|
||||
onDropHook (data: {
|
||||
ea: ExcalidrawAutomate,
|
||||
event: React.DragEvent<HTMLDivElement>,
|
||||
draggable: any, //Obsidian draggable object
|
||||
type: "file"|"text"|"unknown",
|
||||
payload: {
|
||||
files: TFile[], //TFile[] array of dropped files
|
||||
text: string, //string
|
||||
},
|
||||
excalidrawFile: TFile, //the file receiving the drop event
|
||||
view: ExcalidrawView, //the excalidraw view receiving the drop
|
||||
pointerPosition: {x:number, y:number} //the pointer position on canvas at the time of drop
|
||||
}):boolean;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -69,8 +162,8 @@ declare let window: ExcalidrawAutomate;
|
||||
export async function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
|
||||
window.ExcalidrawAutomate = {
|
||||
plugin: plugin,
|
||||
elementIds: [],
|
||||
elementsDict: {},
|
||||
imagesDict: {},
|
||||
style: {
|
||||
strokeColor: "#000000",
|
||||
backgroundColor: "transparent",
|
||||
@@ -86,9 +179,9 @@ export async function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
|
||||
textAlign: "left",
|
||||
verticalAlign: "top",
|
||||
startArrowHead: null,
|
||||
endArrowHead: "arrow"
|
||||
endArrowHead: "arrow",
|
||||
},
|
||||
canvas: {theme: "light", viewBackgroundColor: "#FFFFFF"},
|
||||
canvas: {theme: "light", viewBackgroundColor: "#FFFFFF", gridSize: 0},
|
||||
setFillStyle (val:number) {
|
||||
switch(val) {
|
||||
case 0:
|
||||
@@ -148,35 +241,71 @@ export async function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
|
||||
return "dark";
|
||||
}
|
||||
},
|
||||
addToGroup(objectIds:[]):void {
|
||||
addToGroup(objectIds:[]):string {
|
||||
const id = nanoid();
|
||||
objectIds.forEach((objectId)=>{
|
||||
this.elementsDict[objectId]?.groupIds?.push(id);
|
||||
});
|
||||
return id;
|
||||
},
|
||||
async toClipboard(templatePath?:string) {
|
||||
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]]);
|
||||
}
|
||||
elements = elements.concat(this.getElements());
|
||||
navigator.clipboard.writeText(
|
||||
JSON.stringify({
|
||||
"type":"excalidraw/clipboard",
|
||||
"elements": elements,
|
||||
}));
|
||||
},
|
||||
async create(params?:{filename: string, foldername:string, templatePath:string, onNewPane: boolean}) {
|
||||
getElements():ExcalidrawElement[] {
|
||||
let elements=[];
|
||||
const elementIds = Object.keys(this.elementsDict);
|
||||
for (let i=0;i<elementIds.length;i++) {
|
||||
elements.push(this.elementsDict[elementIds[i]]);
|
||||
}
|
||||
return elements;
|
||||
},
|
||||
getElement(id:string):ExcalidrawElement {
|
||||
return this.elementsDict[id];
|
||||
},
|
||||
async create (
|
||||
params?:{
|
||||
filename?: string,
|
||||
foldername?:string,
|
||||
templatePath?:string,
|
||||
onNewPane?: boolean,
|
||||
frontmatterKeys?:{
|
||||
"excalidraw-plugin"?: "raw"|"parsed",
|
||||
"excalidraw-link-prefix"?: string,
|
||||
"excalidraw-link-brackets"?: boolean,
|
||||
"excalidraw-url-prefix"?: string
|
||||
}
|
||||
}
|
||||
):Promise<string> {
|
||||
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]]);
|
||||
elements = elements.concat(this.getElements());
|
||||
let frontmatter:string;
|
||||
if(params?.frontmatterKeys) {
|
||||
const keys = Object.keys(params.frontmatterKeys);
|
||||
if(!keys.includes("excalidraw-plugin")) {
|
||||
params.frontmatterKeys["excalidraw-plugin"] = "parsed";
|
||||
}
|
||||
frontmatter = "---\n\n";
|
||||
for(const key of Object.keys(params.frontmatterKeys)) {
|
||||
//@ts-ignore
|
||||
frontmatter += key + ": " + (params.frontmatterKeys[key]==="" ? '""' : params.frontmatterKeys[key]) +"\n";
|
||||
}
|
||||
frontmatter += "\n---\n";
|
||||
} else {
|
||||
frontmatter = template?.frontmatter ? template.frontmatter : FRONTMATTER;
|
||||
}
|
||||
plugin.createDrawing(
|
||||
return plugin.createDrawing(
|
||||
params?.filename ? params.filename + '.excalidraw.md' : this.plugin.getNextDefaultFilename(),
|
||||
params?.onNewPane ? params.onNewPane : false,
|
||||
params?.foldername ? params.foldername : this.plugin.settings.folder,
|
||||
FRONTMATTER + exportSceneToMD(
|
||||
frontmatter + plugin.exportSceneToMD(
|
||||
JSON.stringify({
|
||||
type: "excalidraw",
|
||||
version: 2,
|
||||
@@ -199,6 +328,7 @@ export async function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
|
||||
currentItemStartArrowhead: template? template.appState.currentItemStartArrowhead: this.style.startArrowHead,
|
||||
currentItemEndArrowhead: template? template.appState.currentItemEndArrowhead : this.style.endArrowHead,
|
||||
currentItemLinearStrokeSharpness: template? template.appState.currentItemLinearStrokeSharpness : this.style.strokeSharpness,
|
||||
gridSize: template ? template.appState.gridSize : this.canvas.gridSize
|
||||
}
|
||||
}))
|
||||
);
|
||||
@@ -206,9 +336,7 @@ export async function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
|
||||
async createSVG(templatePath?:string):Promise<SVGSVGElement> {
|
||||
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]]);
|
||||
}
|
||||
elements = elements.concat(this.getElements());
|
||||
return await ExcalidrawView.getSVG(
|
||||
{//createDrawing
|
||||
"type": "excalidraw",
|
||||
@@ -226,12 +354,10 @@ export async function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
|
||||
}
|
||||
)
|
||||
},
|
||||
async createPNG(templatePath?:string) {
|
||||
async createPNG(templatePath?:string, scale:number=1) {
|
||||
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]]);
|
||||
}
|
||||
elements = elements.concat(this.getElements());
|
||||
return ExcalidrawView.getPNG(
|
||||
{
|
||||
"type": "excalidraw",
|
||||
@@ -246,56 +372,119 @@ export async function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
|
||||
{
|
||||
withBackground: plugin.settings.exportWithBackground,
|
||||
withTheme: plugin.settings.exportWithTheme
|
||||
}
|
||||
},
|
||||
scale
|
||||
)
|
||||
},
|
||||
wrapText(text:string, lineLen:number):string {
|
||||
return wrapText(text,lineLen,this.plugin.settings.forceWrap);
|
||||
},
|
||||
addRect(topX:number, topY:number, width:number, height:number):string {
|
||||
const id = nanoid();
|
||||
this.elementIds.push(id);
|
||||
this.elementsDict[id] = boxedElement(id,"rectangle",topX,topY,width,height);
|
||||
return id;
|
||||
},
|
||||
addDiamond(topX:number, topY:number, width:number, height:number):string {
|
||||
const id = nanoid();
|
||||
this.elementIds.push(id);
|
||||
this.elementsDict[id] = boxedElement(id,"diamond",topX,topY,width,height);
|
||||
return id;
|
||||
},
|
||||
addEllipse(topX:number, topY:number, width:number, height:number):string {
|
||||
const id = nanoid();
|
||||
this.elementIds.push(id);
|
||||
this.elementsDict[id] = boxedElement(id,"ellipse",topX,topY,width,height);
|
||||
return id;
|
||||
},
|
||||
addText(topX:number, topY:number, text:string, formatting?:{width:number, height:number,textAlign: string, verticalAlign:string, box: boolean, boxPadding: number}):string {
|
||||
const id = nanoid();
|
||||
},
|
||||
addBlob(topX:number, topY:number, width:number, height:number):string {
|
||||
const b = height*0.5; //minor axis of the ellipsis
|
||||
const a = width*0.5; //major axis of the ellipsis
|
||||
const sx = a/9;
|
||||
const sy = b*0.8;
|
||||
const step = 6;
|
||||
let p:any = [];
|
||||
const pushPoint = (i:number,dir:number) => {
|
||||
const x = i + Math.random()*sx-sx/2;
|
||||
p.push([x+Math.random()*sx-sx/2+(i%2)*sx/6+topX,dir*Math.sqrt(b*b*(1-(x*x)/(a*a)))+Math.random()*sy-sy/2+(i%2)*sy/6+topY]);
|
||||
}
|
||||
let i:number;
|
||||
for (i=-a+sx/2;i<=a-sx/2;i+=a/step) {
|
||||
pushPoint(i,1);
|
||||
}
|
||||
for(i=a-sx/2;i>=-a+sx/2;i-=a/step) {
|
||||
pushPoint(i,-1);
|
||||
}
|
||||
p.push(p[0]);
|
||||
const scale = (p:[[x:number,y:number]]):[[x:number,y:number]] => {
|
||||
const box = getLineBox(p);
|
||||
const scaleX = width/box.w;
|
||||
const scaleY = height/box.h;
|
||||
let i;
|
||||
for(i=0;i<p.length;i++) {
|
||||
let [x,y] = p[i];
|
||||
x = (x-box.x)*scaleX+box.x;
|
||||
y = (y-box.y)*scaleY+box.y;
|
||||
p[i]=[x,y]
|
||||
}
|
||||
return p;
|
||||
}
|
||||
const id=this.addLine(scale(p));
|
||||
this.elementsDict[id]=repositionElementsToCursor([this.getElement(id)],{x:topX,y:topY},false)[0];
|
||||
return id;
|
||||
},
|
||||
addText(
|
||||
topX:number,
|
||||
topY:number,
|
||||
text:string,
|
||||
formatting?:{
|
||||
wrapAt?:number,
|
||||
width?:number,
|
||||
height?:number,
|
||||
textAlign?:string,
|
||||
box?: boolean|"box"|"blob"|"ellipse"|"diamond",
|
||||
boxPadding?:number
|
||||
},
|
||||
id?:string
|
||||
):string {
|
||||
id = id ?? nanoid();
|
||||
text = (formatting?.wrapAt) ? this.wrapText(text,formatting.wrapAt):text;
|
||||
const {w, h, baseline} = measureText(text, this.style.fontSize,this.style.fontFamily);
|
||||
const width = formatting?.width ? formatting.width : w;
|
||||
const height = formatting?.height ? formatting.height : h;
|
||||
this.elementIds.push(id);
|
||||
|
||||
let boxId:string = null;
|
||||
const boxPadding = formatting?.boxPadding ?? 10;
|
||||
if(formatting?.box) {
|
||||
switch(formatting?.box) {
|
||||
case "ellipse":
|
||||
boxId = this.addEllipse(topX-boxPadding,topY-boxPadding,width+2*boxPadding,height+2*boxPadding);
|
||||
break;
|
||||
case "diamond":
|
||||
boxId = this.addDiamond(topX-boxPadding,topY-boxPadding,width+2*boxPadding,height+2*boxPadding);
|
||||
break;
|
||||
case "blob":
|
||||
boxId = this.addBlob(topX-boxPadding,topY-boxPadding,width+2*boxPadding,height+2*boxPadding);
|
||||
break;
|
||||
default:
|
||||
boxId = this.addRect(topX-boxPadding,topY-boxPadding,width+2*boxPadding,height+2*boxPadding);
|
||||
}
|
||||
}
|
||||
this.elementsDict[id] = {
|
||||
text: text,
|
||||
fontSize: window.ExcalidrawAutomate.style.fontSize,
|
||||
fontFamily: window.ExcalidrawAutomate.style.fontFamily,
|
||||
textAlign: formatting?.textAlign ? formatting.textAlign : window.ExcalidrawAutomate.style.textAlign,
|
||||
verticalAlign: formatting?.verticalAlign ? formatting.verticalAlign : window.ExcalidrawAutomate.style.verticalAlign,
|
||||
verticalAlign: window.ExcalidrawAutomate.style.verticalAlign,
|
||||
baseline: baseline,
|
||||
... boxedElement(id,"text",topX,topY,width,height)
|
||||
};
|
||||
if(formatting?.box) {
|
||||
const boxPadding = formatting?.boxPadding ? formatting.boxPadding : 10;
|
||||
const boxId = this.addRect(topX-boxPadding,topY-boxPadding,width+2*boxPadding,height+2*boxPadding);
|
||||
this.addToGroup([id,boxId])
|
||||
return boxId;
|
||||
}
|
||||
return id;
|
||||
if (boxId) this.addToGroup([id,boxId])
|
||||
return boxId ?? id;
|
||||
},
|
||||
addLine(points: [[x:number,y:number]]):void {
|
||||
addLine(points: [[x:number,y:number]]):string {
|
||||
const box = getLineBox(points);
|
||||
const id = nanoid();
|
||||
this.elementIds.push(id);
|
||||
//this.elementIds.push(id);
|
||||
this.elementsDict[id] = {
|
||||
points: normalizeLinePoints(points),
|
||||
points: normalizeLinePoints(points,box),
|
||||
lastCommittedPoint: null,
|
||||
startBinding: null,
|
||||
endBinding: null,
|
||||
@@ -303,13 +492,14 @@ export async function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
|
||||
endArrowhead: null,
|
||||
... boxedElement(id,"line",box.x,box.y,box.w,box.h)
|
||||
};
|
||||
return id;
|
||||
},
|
||||
addArrow(points: [[x:number,y:number]],formatting?:{startArrowHead:string,endArrowHead:string,startObjectId:string,endObjectId:string}):void {
|
||||
addArrow(points: [[x:number,y:number]],formatting?:{startArrowHead?:string,endArrowHead?:string,startObjectId?:string,endObjectId?:string}):string {
|
||||
const box = getLineBox(points);
|
||||
const id = nanoid();
|
||||
this.elementIds.push(id);
|
||||
//this.elementIds.push(id);
|
||||
this.elementsDict[id] = {
|
||||
points: normalizeLinePoints(points),
|
||||
points: normalizeLinePoints(points,box),
|
||||
lastCommittedPoint: null,
|
||||
startBinding: {elementId:formatting?.startObjectId,focus:0.1,gap:4},
|
||||
endBinding: {elementId:formatting?.endObjectId,focus:0.1,gap:4},
|
||||
@@ -317,13 +507,45 @@ export async function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
|
||||
endArrowhead: formatting?.endArrowHead ? formatting.endArrowHead : this.style.endArrowHead,
|
||||
... boxedElement(id,"arrow",box.x,box.y,box.w,box.h)
|
||||
};
|
||||
if(formatting?.startObjectId) this.elementsDict[formatting.startObjectId].boundElementIds.push(id);
|
||||
if(formatting?.endObjectId) this.elementsDict[formatting.endObjectId].boundElementIds.push(id);
|
||||
if(formatting?.startObjectId) {
|
||||
if(!this.elementsDict[formatting.startObjectId].boundElementIds) this.elementsDict[formatting.startObjectId].boundElementIds = [];
|
||||
this.elementsDict[formatting.startObjectId].boundElementIds.push(id);
|
||||
}
|
||||
if(formatting?.endObjectId) {
|
||||
if(!this.elementsDict[formatting.endObjectId].boundElementIds) this.elementsDict[formatting.endObjectId].boundElementIds = [];
|
||||
this.elementsDict[formatting.endObjectId].boundElementIds.push(id);
|
||||
}
|
||||
return id;
|
||||
},
|
||||
connectObjects(objectA: string, connectionA: ConnectionPoint, objectB: string, connectionB: ConnectionPoint, formatting?:{numberOfPoints: number,startArrowHead:string,endArrowHead:string, padding: number}):void {
|
||||
async addImage(topX:number, topY:number, imageFile: TFile):Promise<string> {
|
||||
const id = nanoid();
|
||||
const image = await getObsidianImage(this.plugin.app,imageFile);
|
||||
if(!image) return null;
|
||||
this.imagesDict[image.imageId] = {
|
||||
type:"image",
|
||||
id: image.imageId,
|
||||
dataURL: image.dataURL
|
||||
}
|
||||
if (Math.max(image.size.width,image.size.height) > MAX_IMAGE_SIZE) {
|
||||
const scale = MAX_IMAGE_SIZE/Math.max(image.size.width,image.size.height);
|
||||
image.size.width = scale*image.size.width;
|
||||
image.size.height = scale*image.size.height;
|
||||
}
|
||||
this.elementsDict[id] = boxedElement(id,"image",topX,topY,image.size.width,image.size.height);
|
||||
this.elementsDict[id].imageId = image.imageId;
|
||||
this.elementsDict[id].scale = [1,1];
|
||||
return id;
|
||||
},
|
||||
connectObjects(objectA: string, connectionA: ConnectionPoint, objectB: string, connectionB: ConnectionPoint, formatting?:{numberOfPoints?: number,startArrowHead?:string,endArrowHead?:string, padding?: number}):void {
|
||||
if(!(this.elementsDict[objectA] && this.elementsDict[objectB])) {
|
||||
return;
|
||||
}
|
||||
|
||||
if(["line","arrow","freedraw"].includes(this.elementsDict[objectA].type) ||
|
||||
["line","arrow","freedraw"].includes(this.elementsDict[objectB].type)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const padding = formatting?.padding ? formatting.padding : 10;
|
||||
const numberOfPoints = formatting?.numberOfPoints ? formatting.numberOfPoints : 0;
|
||||
const getSidePoints = (side:string, el:any) => {
|
||||
@@ -352,8 +574,8 @@ export async function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
|
||||
});
|
||||
},
|
||||
clear() {
|
||||
this.elementIds = [];
|
||||
this.elementsDict = {};
|
||||
this.imagesDict = {};
|
||||
},
|
||||
reset() {
|
||||
this.clear();
|
||||
@@ -374,11 +596,119 @@ export async function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
|
||||
this.style.endArrowHead= "arrow";
|
||||
this.canvas.theme = "light";
|
||||
this.canvas.viewBackgroundColor="#FFFFFF";
|
||||
this.canvas.gridSize = 0;
|
||||
},
|
||||
isExcalidrawFile(f:TFile) {
|
||||
isExcalidrawFile(f:TFile):boolean {
|
||||
return this.plugin.isExcalidrawFile(f);
|
||||
}
|
||||
|
||||
},
|
||||
targetView: null,
|
||||
setView(view:ExcalidrawView|"first"|"active"):ExcalidrawView {
|
||||
if(view == "active") {
|
||||
const v = this.plugin.app.workspace.activeLeaf.view;
|
||||
if(!(v instanceof ExcalidrawView)) return;
|
||||
this.targetView = v;
|
||||
}
|
||||
if(view == "first") {
|
||||
const leaves = this.plugin.app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW);
|
||||
if(!leaves || leaves.length == 0) return;
|
||||
this.targetView = (leaves[0].view as ExcalidrawView);
|
||||
}
|
||||
if(view instanceof ExcalidrawView) this.targetView = view;
|
||||
return this.targetView;
|
||||
},
|
||||
getExcalidrawAPI():any {
|
||||
if (!this.targetView || !this.targetView?._loaded) {
|
||||
errorMessage("targetView not set", "getExcalidrawAPI()");
|
||||
return null;
|
||||
}
|
||||
return (this.targetView as ExcalidrawView).excalidrawRef.current;
|
||||
},
|
||||
getViewElements ():ExcalidrawElement[] {
|
||||
if (!this.targetView || !this.targetView?._loaded) {
|
||||
errorMessage("targetView not set", "getViewSelectedElements()");
|
||||
return [];
|
||||
}
|
||||
const current = this.targetView?.excalidrawRef?.current;
|
||||
if(!current) return [];
|
||||
return current?.getSceneElements();
|
||||
},
|
||||
deleteViewElements (elToDelete: ExcalidrawElement[]):boolean {
|
||||
if (!this.targetView || !this.targetView?._loaded) {
|
||||
errorMessage("targetView not set", "getViewSelectedElements()");
|
||||
return false;
|
||||
}
|
||||
const current = this.targetView?.excalidrawRef?.current;
|
||||
if(!current) return false;
|
||||
const el: ExcalidrawElement[] = current.getSceneElements();
|
||||
const st: AppState = current.getAppState();
|
||||
current.updateScene({
|
||||
elements: el.filter((e:ExcalidrawElement)=>!elToDelete.includes(e)),
|
||||
appState: st,
|
||||
commitToHistory: true,
|
||||
});
|
||||
this.targetView.save();
|
||||
return true;
|
||||
},
|
||||
getViewSelectedElement():any {
|
||||
const elements = this.getViewSelectedElements();
|
||||
return elements ? elements[0] : null;
|
||||
},
|
||||
getViewSelectedElements():any[] {
|
||||
if (!this.targetView || !this.targetView?._loaded) {
|
||||
errorMessage("targetView not set", "getViewSelectedElements()");
|
||||
return [];
|
||||
}
|
||||
const current = this.targetView?.excalidrawRef?.current;
|
||||
const selectedElements = current?.getAppState()?.selectedElementIds;
|
||||
if(!selectedElements) return [];
|
||||
const selectedElementsKeys = Object.keys(selectedElements);
|
||||
if(!selectedElementsKeys) return [];
|
||||
return current.getSceneElements().filter((e:any)=>selectedElementsKeys.includes(e.id));
|
||||
},
|
||||
viewToggleFullScreen(forceViewMode:boolean = false):void {
|
||||
if (this.plugin.app.isMobile) {
|
||||
errorMessage("mobile not supported", "viewToggleFullScreen()");
|
||||
return;
|
||||
}
|
||||
if (!this.targetView || !this.targetView?._loaded) {
|
||||
errorMessage("targetView not set", "viewToggleFullScreen()");
|
||||
return;
|
||||
}
|
||||
if(forceViewMode){
|
||||
const ref = this.getExcalidrawAPI();
|
||||
ref.updateScene({
|
||||
elements: ref.getSceneElements(),
|
||||
appState: {
|
||||
viewModeEnabled: true,
|
||||
... ref.appState,
|
||||
},
|
||||
commitToHistory: false,
|
||||
});
|
||||
}
|
||||
if(document.fullscreenElement === (this.targetView as ExcalidrawView).contentEl) {
|
||||
document.exitFullscreen();
|
||||
} else {
|
||||
(this.targetView as ExcalidrawView).contentEl.requestFullscreen();
|
||||
}
|
||||
},
|
||||
connectObjectWithViewSelectedElement(objectA:string,connectionA: ConnectionPoint, connectionB: ConnectionPoint, formatting?:{numberOfPoints?: number,startArrowHead?:string,endArrowHead?:string, padding?: number}):boolean {
|
||||
const el = this.getViewSelectedElement();
|
||||
if(!el) return false;
|
||||
const id = el.id;
|
||||
this.elementsDict[id] = el;
|
||||
this.connectObjects(objectA,connectionA,id,connectionB,formatting);
|
||||
delete this.elementsDict[id];
|
||||
return true;
|
||||
},
|
||||
async addElementsToView(repositionToCursor:boolean = false, save:boolean=false):Promise<boolean> {
|
||||
if (!this.targetView || !this.targetView?._loaded) {
|
||||
errorMessage("targetView not set", "addElementsToView()");
|
||||
return false;
|
||||
}
|
||||
const elements = this.getElements();
|
||||
return await this.targetView.addElements(elements,repositionToCursor,save,this.imagesDict);
|
||||
},
|
||||
onDropHook:null,
|
||||
};
|
||||
await initFonts();
|
||||
}
|
||||
@@ -387,10 +717,10 @@ export function destroyExcalidrawAutomate() {
|
||||
delete window.ExcalidrawAutomate;
|
||||
}
|
||||
|
||||
function normalizeLinePoints(points:[[x:number,y:number]]) {
|
||||
function normalizeLinePoints(points:[[x:number,y:number]],box:{x:number,y:number,w:number,h:number}) {
|
||||
let p = [];
|
||||
for(let i=0;i<points.length;i++) {
|
||||
p.push([points[i][0]-points[0][0], points[i][1]-points[0][1]]);
|
||||
p.push([points[i][0]-box.x, points[i][1]-box.y]);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
@@ -422,11 +752,12 @@ function boxedElement(id:string,eltype:any,x:number,y:number,w:number,h:number)
|
||||
}
|
||||
|
||||
function getLineBox(points: [[x:number,y:number]]) {
|
||||
const [x1,y1,x2,y2] = estimateLineBound(points);
|
||||
return {
|
||||
x: points[0][0],
|
||||
y: points[0][1],
|
||||
w: Math.abs(points[points.length-1][0]-points[0][0]),
|
||||
h: Math.abs(points[points.length-1][1]-points[0][1])
|
||||
x: x1,
|
||||
y: y1,
|
||||
w: x2-x1, //Math.abs(points[points.length-1][0]-points[0][0]),
|
||||
h: y2-y1 //Math.abs(points[points.length-1][1]-points[0][1])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -473,47 +804,95 @@ export function measureText (newText:string, fontSize:number, fontFamily:number)
|
||||
return {w: width, h: height, baseline: baseline };
|
||||
};
|
||||
|
||||
async function getTemplate(fileWithPath: string):Promise<{elements: any,appState: any}> {
|
||||
const vault = window.ExcalidrawAutomate.plugin.app.vault;
|
||||
const file = vault.getAbstractFileByPath(normalizePath(fileWithPath));
|
||||
async function getTemplate(fileWithPath: string):Promise<{elements: any,appState: any, frontmatter: string}> {
|
||||
const app = window.ExcalidrawAutomate.plugin.app;
|
||||
const vault = app.vault;
|
||||
const file = app.metadataCache.getFirstLinkpathDest(normalizePath(fileWithPath),'');
|
||||
if(file && file instanceof TFile) {
|
||||
const data = await vault.read(file);
|
||||
const excalidrawData = JSON_parse(getJSON(data));
|
||||
|
||||
let trimLocation = data.search("# Text Elements\n");
|
||||
if(trimLocation == -1) trimLocation = data.search("# Drawing\n");
|
||||
|
||||
const excalidrawData = JSON_parse(getJSON(data)[0]);
|
||||
return {
|
||||
elements: excalidrawData.elements,
|
||||
appState: excalidrawData.appState,
|
||||
frontmatter: data.substring(0,trimLocation)
|
||||
};
|
||||
};
|
||||
return {
|
||||
elements: [],
|
||||
appState: {},
|
||||
frontmatter: null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the text elements from an Excalidraw scene into a string of ids as headers followed by the text contents
|
||||
* @param {string} data - Excalidraw scene JSON string
|
||||
* @returns {string} - Text starting with the "# Text Elements" header and followed by each "## id-value" and text
|
||||
*/
|
||||
export function exportSceneToMD(data:string): string {
|
||||
if(!data) return "";
|
||||
const excalidrawData = JSON_parse(data);
|
||||
const textElements = excalidrawData.elements?.filter((el:any)=> el.type=="text")
|
||||
let outString = '# Text Elements\n';
|
||||
let id:string;
|
||||
for (const te of textElements) {
|
||||
id = te.id;
|
||||
//replacing Excalidraw text IDs with my own, because default IDs may contain
|
||||
//characters not recognized by Obsidian block references
|
||||
//also Excalidraw IDs are inconveniently long
|
||||
if(te.id.length>8) {
|
||||
id=nanoid();
|
||||
data = data.replaceAll(te.id,id); //brute force approach to replace all occurances.
|
||||
}
|
||||
outString += te.text+' ^'+id+'\n\n';
|
||||
function estimateLineBound(points:any):[number,number,number,number] {
|
||||
let minX = Infinity;
|
||||
let maxX = -Infinity;
|
||||
let minY = Infinity;
|
||||
let maxY = -Infinity;
|
||||
points.forEach((p:any) => {
|
||||
const [x,y] = p;
|
||||
minX = Math.min(minX, x);
|
||||
minY = Math.min(minY, y);
|
||||
maxX = Math.max(maxX, x);
|
||||
maxY = Math.max(maxY, y);
|
||||
});
|
||||
return[minX,minY,maxX,maxY];
|
||||
}
|
||||
|
||||
export function estimateElementBounds (element:ExcalidrawElement):[number,number,number,number] {
|
||||
if(element.type=="line" || element.type=="arrow") {
|
||||
const [minX,minY,maxX,maxY] = estimateLineBound(element.points);
|
||||
return [minX+element.x,minY+element.y,maxX+element.x,maxY+element.y];
|
||||
}
|
||||
return outString + '# Drawing\n'
|
||||
+ String.fromCharCode(96)+String.fromCharCode(96)+String.fromCharCode(96)+'json\n'
|
||||
+ data + '\n'
|
||||
+ String.fromCharCode(96)+String.fromCharCode(96)+String.fromCharCode(96);
|
||||
}
|
||||
return[element.x,element.y,element.x+element.width,element.y+element.height];
|
||||
}
|
||||
|
||||
export function estimateBounds (elements:ExcalidrawElement[]):[number,number,number,number] {
|
||||
if(!elements.length) return [0,0,0,0];
|
||||
let minX = Infinity;
|
||||
let maxX = -Infinity;
|
||||
let minY = Infinity;
|
||||
let maxY = -Infinity;
|
||||
|
||||
elements.forEach((element)=>{
|
||||
const [x1,y1,x2,y2] = estimateElementBounds(element);
|
||||
minX = Math.min(minX, x1);
|
||||
minY = Math.min(minY, y1);
|
||||
maxX = Math.max(maxX, x2);
|
||||
maxY = Math.max(maxY, y2);
|
||||
});
|
||||
return [minX,minY,maxX,maxY];
|
||||
}
|
||||
|
||||
export function repositionElementsToCursor (elements:ExcalidrawElement[],newPosition:{x:number, y:number},center:boolean=false):ExcalidrawElement[] {
|
||||
const [x1,y1,x2,y2] = estimateBounds(elements);
|
||||
let [offsetX,offsetY] = [0,0];
|
||||
if (center) {
|
||||
[offsetX,offsetY] = [newPosition.x-(x1+x2)/2,newPosition.y-(y1+y2)/2];
|
||||
} else {
|
||||
[offsetX,offsetY] = [newPosition.x-x1,newPosition.y-y1];
|
||||
}
|
||||
|
||||
elements.forEach((element:any)=>{ //using any so I can write read-only propery x & y
|
||||
element.x=element.x+offsetX;
|
||||
element.y=element.y+offsetY;
|
||||
});
|
||||
return elements;
|
||||
}
|
||||
|
||||
function errorMessage(message: string, source: string) {
|
||||
switch(message) {
|
||||
case "targetView not set":
|
||||
console.log(source, "ExcalidrawAutomate: targetView not set, or no longer active. Use setView before calling this function");
|
||||
break;
|
||||
case "mobile not supported":
|
||||
console.log(source, "ExcalidrawAutomate: this function is not avalable on Obsidian Mobile");
|
||||
break;
|
||||
default:
|
||||
console.log(source, "ExcalidrawAutomate: unknown error");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,42 +3,84 @@ import {
|
||||
nanoid,
|
||||
FRONTMATTER_KEY_CUSTOM_PREFIX,
|
||||
FRONTMATTER_KEY_CUSTOM_LINK_BRACKETS,
|
||||
FRONTMATTER_KEY_CUSTOM_URL_PREFIX,
|
||||
} from "./constants";
|
||||
import { measureText } from "./ExcalidrawAutomate";
|
||||
import ExcalidrawPlugin from "./main";
|
||||
import { ExcalidrawSettings } from "./settings";
|
||||
import {
|
||||
JSON_parse
|
||||
} from "./constants";
|
||||
import { TextMode } from "./ExcalidrawView";
|
||||
import { wrapText } from "./Utils";
|
||||
|
||||
const DRAWING_REG = /\n# Drawing\n(```json\n)?(.*)(```)?/gm;
|
||||
|
||||
//![[link|alias]]
|
||||
//1 2 3 4 5 6
|
||||
export const REG_LINK_BACKETS = /(!)?\[\[([^|\]]+)\|?(.+)?]]|(!)?\[(.*)\]\((.*)\)/g;
|
||||
|
||||
export function getJSON(data:string):string {
|
||||
const findJSON = DRAWING_REG;
|
||||
const res = data.matchAll(findJSON);
|
||||
const parts = res.next();
|
||||
if(parts.value && parts.value.length>1) {
|
||||
return parts.value[2];
|
||||
declare module "obsidian" {
|
||||
interface MetadataCache {
|
||||
blockCache: {
|
||||
getForFile(x:any,f:TAbstractFile):any;
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
export const REGEX_LINK = {
|
||||
//![[link|alias]] [alias](link){num}
|
||||
// 1 2 3 4 5 6 7 8 9
|
||||
EXPR: /(!)?(\[\[([^|\]]+)\|?(.+)?]]|\[(.*)\]\((.*)\))(\{(\d+)\})?/g,
|
||||
isTransclusion: (parts: IteratorResult<RegExpMatchArray, any>):boolean => {
|
||||
return parts.value[1] ? true:false;
|
||||
},
|
||||
getLink: (parts: IteratorResult<RegExpMatchArray, any>):string => {
|
||||
return parts.value[3] ? parts.value[3] : parts.value[6];
|
||||
},
|
||||
isWikiLink: (parts: IteratorResult<RegExpMatchArray, any>):boolean => {
|
||||
return parts.value[3] ? true:false;
|
||||
},
|
||||
getAliasOrLink: (parts: IteratorResult<RegExpMatchArray, any>):string => {
|
||||
return REGEX_LINK.isWikiLink(parts)
|
||||
? (parts.value[4] ? parts.value[4] : parts.value[3])
|
||||
: (parts.value[5] ? parts.value[5] : parts.value[6]);
|
||||
},
|
||||
getWrapLength: (parts: IteratorResult<RegExpMatchArray, any>):number => {
|
||||
return parts.value[8];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export const REG_LINKINDEX_HYPERLINK = /^\w+:\/\//;
|
||||
|
||||
const DRAWING_REG = /\n%%\n# Drawing\n(```json\n)(.*)\n```%%/gm;
|
||||
const DRAWING_REG_FALLBACK = /\n# Drawing\n(```json\n)?(.*)(```)?(%%)?/gm;
|
||||
export function getJSON(data:string):[string,number] {
|
||||
let res = data.matchAll(DRAWING_REG);
|
||||
|
||||
//In case the user adds a text element with the contents "# Drawing\n"
|
||||
let parts;
|
||||
parts = res.next();
|
||||
if(parts.done) { //did not find a match
|
||||
res = data.matchAll(DRAWING_REG_FALLBACK);
|
||||
parts = res.next();
|
||||
}
|
||||
if(parts.value && parts.value.length>1) {
|
||||
const result = parts.value[2];
|
||||
return [result.substr(0,result.lastIndexOf("}")+1),parts.value.index]; //this is a workaround in case sync merges two files together and one version is still an old version without the ```codeblock
|
||||
}
|
||||
return [data,parts.value.index];
|
||||
}
|
||||
|
||||
export class ExcalidrawData {
|
||||
private textElements:Map<string,{raw:string, parsed:string}> = null;
|
||||
public scene:any = null;
|
||||
private file:TFile = null;
|
||||
private settings:ExcalidrawSettings;
|
||||
private app:App;
|
||||
private showLinkBrackets: boolean;
|
||||
private linkPrefix: string;
|
||||
private allowParse: boolean = false;
|
||||
private urlPrefix: string;
|
||||
private textMode: TextMode = TextMode.raw;
|
||||
private plugin: ExcalidrawPlugin;
|
||||
public loaded: boolean = false;
|
||||
|
||||
constructor(plugin: ExcalidrawPlugin) {
|
||||
this.settings = plugin.settings;
|
||||
this.plugin = plugin;
|
||||
this.app = plugin.app;
|
||||
}
|
||||
|
||||
@@ -47,9 +89,8 @@ export class ExcalidrawData {
|
||||
* @param {TFile} file - the MD file containing the Excalidraw drawing
|
||||
* @returns {boolean} - true if file was loaded, false if there was an error
|
||||
*/
|
||||
public async loadData(data: string,file: TFile, allowParse:boolean):Promise<boolean> {
|
||||
//console.log("Excalidraw.Data.loadData()",{data:data,allowParse:allowParse,file:file});
|
||||
|
||||
public async loadData(data: string,file: TFile, textMode:TextMode):Promise<boolean> {
|
||||
this.loaded = false;
|
||||
this.file = file;
|
||||
this.textElements = new Map<string,{raw:string, parsed:string}>();
|
||||
|
||||
@@ -57,9 +98,15 @@ export class ExcalidrawData {
|
||||
//The drawing will use these values until next drawing is loaded or this drawing is re-loaded
|
||||
this.setShowLinkBrackets();
|
||||
this.setLinkPrefix();
|
||||
this.setUrlPrefix();
|
||||
|
||||
this.scene = null;
|
||||
if (this.settings.syncExcalidraw) {
|
||||
|
||||
//In compatibility mode if the .excalidraw file was more recently updated than the .md file, then the .excalidraw file
|
||||
//should be loaded as the scene.
|
||||
//This feature is mostly likely only relevant to people who use Obsidian and Logseq on the same vault and edit .excalidraw
|
||||
//drawings in Logseq.
|
||||
if (this.plugin.settings.syncExcalidraw) {
|
||||
const excalfile = file.path.substring(0,file.path.lastIndexOf('.md')) + '.excalidraw';
|
||||
const f = this.app.vault.getAbstractFileByPath(excalfile);
|
||||
if(f && f instanceof TFile && f.stat.mtime>file.stat.mtime) { //the .excalidraw file is newer then the .md file
|
||||
@@ -69,33 +116,47 @@ export class ExcalidrawData {
|
||||
}
|
||||
|
||||
//Load scene: Read the JSON string after "# Drawing"
|
||||
let parts = data.matchAll(DRAWING_REG).next();
|
||||
if(!(parts.value && parts.value.length>1)) return false; //JSON not found or invalid
|
||||
if(!this.scene) { //scene was not loaded from .excalidraw
|
||||
this.scene = JSON_parse(parts.value[2]);
|
||||
const [scene,pos] = getJSON(data);
|
||||
if (pos === -1) {
|
||||
return false; //JSON not found
|
||||
}
|
||||
//Trim data to remove the JSON string
|
||||
data = data.substring(0,parts.value.index);
|
||||
if (!this.scene) {
|
||||
this.scene = JSON_parse(scene); //this is a workaround to address when files are mereged by sync and one version is still an old markdown without the codeblock ```
|
||||
}
|
||||
data = data.substring(0,pos);
|
||||
|
||||
//The Markdown # Text Elements take priority over the JSON text elements.
|
||||
//i.e. if the JSON is modified to reflect the MD in case of difference
|
||||
//The Markdown # Text Elements take priority over the JSON text elements. Assuming the scenario in which the link was updated due to filename changes
|
||||
//The .excalidraw JSON is modified to reflect the MD in case of difference
|
||||
//Read the text elements into the textElements Map
|
||||
let position = data.search("# Text Elements");
|
||||
if(position==-1) return true; //Text Elements header does not exist
|
||||
position += "# Text Elements\n".length;
|
||||
let position = data.search(/(^%%\n)?# Text Elements\n/m);
|
||||
if(position==-1) {
|
||||
await this.setTextMode(textMode,false);
|
||||
this.loaded = true;
|
||||
return true; //Text Elements header does not exist
|
||||
}
|
||||
position += data.match(/((^%%\n)?# Text Elements\n)/m)[0].length
|
||||
|
||||
//iterating through all the text elements in .md
|
||||
//Text elements always contain the raw value
|
||||
const BLOCKREF_LEN:number = " ^12345678\n\n".length;
|
||||
const res = data.matchAll(/\s\^(.{8})\n/g);
|
||||
const res = data.matchAll(/\s\^(.{8})[\n]+/g);
|
||||
let parts;
|
||||
while(!(parts = res.next()).done) {
|
||||
const text = data.substring(position,parts.value.index);
|
||||
this.textElements.set(parts.value[1],{raw: text, parsed: await this.parse(text)});
|
||||
const id:string = parts.value[1];
|
||||
this.textElements.set(id,{raw: text, parsed: await this.parse(text)});
|
||||
//this will set the rawText field of text elements imported from files before 1.3.14, and from other instances of Excalidraw
|
||||
const textEl = this.scene.elements.filter((el:any)=>el.id===id)[0];
|
||||
if(textEl && (!textEl.rawText || textEl.rawText === "")) textEl.rawText = text;
|
||||
|
||||
position = parts.value.index + BLOCKREF_LEN;
|
||||
}
|
||||
|
||||
//Check to see if there are text elements in the JSON that were missed from the # Text Elements section
|
||||
//e.g. if the entire text elements section was deleted.
|
||||
this.findNewTextElementsInScene();
|
||||
await this.setAllowParse(allowParse,true);
|
||||
await this.setTextMode(textMode,true);
|
||||
this.loaded = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -104,41 +165,47 @@ export class ExcalidrawData {
|
||||
this.textElements = new Map<string,{raw:string, parsed:string}>();
|
||||
this.setShowLinkBrackets();
|
||||
this.setLinkPrefix();
|
||||
this.setUrlPrefix();
|
||||
this.scene = JSON.parse(data);
|
||||
this.findNewTextElementsInScene();
|
||||
await this.setAllowParse(false,true);
|
||||
await this.setTextMode(TextMode.raw,true); //legacy files are always displayed in raw mode.
|
||||
return true;
|
||||
}
|
||||
|
||||
public async setAllowParse(allowParse:boolean,forceupdate:boolean=false) {
|
||||
this.allowParse = allowParse;
|
||||
public async setTextMode(textMode:TextMode,forceupdate:boolean=false) {
|
||||
this.textMode = textMode;
|
||||
await this.updateSceneTextElements(forceupdate);
|
||||
}
|
||||
|
||||
private async updateSceneTextElements(forceupdate:boolean=false) {
|
||||
//console.log("Excalidraw.Data.updateSceneTextElements(), forceupdate",forceupdate);
|
||||
//update a single text element in the scene if the newText is different
|
||||
const update = (sceneTextElement:any, newText:string) => {
|
||||
if(forceupdate || newText!=sceneTextElement.text) {
|
||||
const measure = measureText(newText,sceneTextElement.fontSize,sceneTextElement.fontFamily);
|
||||
sceneTextElement.text = newText;
|
||||
sceneTextElement.width = measure.w;
|
||||
sceneTextElement.height = measure.h;
|
||||
sceneTextElement.baseline = measure.baseline;
|
||||
}
|
||||
//update a single text element in the scene if the newText is different
|
||||
public updateTextElement(sceneTextElement:any, newText:string, forceUpdate:boolean = false) {
|
||||
if(forceUpdate || newText!=sceneTextElement.text) {
|
||||
const measure = measureText(newText,sceneTextElement.fontSize,sceneTextElement.fontFamily);
|
||||
sceneTextElement.text = newText;
|
||||
sceneTextElement.width = measure.w;
|
||||
sceneTextElement.height = measure.h;
|
||||
sceneTextElement.baseline = measure.baseline;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the TextElements in the Excalidraw scene based on textElements MAP in ExcalidrawData
|
||||
* Depending on textMode, TextElements will receive their raw or parsed values
|
||||
* @param forceupdate : will update text elements even if text contents has not changed, this will
|
||||
* correct sizing issues
|
||||
*/
|
||||
private async updateSceneTextElements(forceupdate:boolean=false) {
|
||||
//update text in scene based on textElements Map
|
||||
//first get scene text elements
|
||||
const texts = this.scene.elements?.filter((el:any)=> el.type=="text")
|
||||
for (const te of texts) {
|
||||
update(te,await this.getText(te.id));
|
||||
this.updateTextElement(te,await this.getText(te.id),forceupdate);
|
||||
}
|
||||
}
|
||||
|
||||
private async getText(id:string):Promise<string> {
|
||||
if (this.allowParse) {
|
||||
if(!this.textElements.get(id)?.parsed) {
|
||||
if (this.textMode == TextMode.parsed) {
|
||||
if(!this.textElements.get(id).parsed) {
|
||||
const raw = this.textElements.get(id).raw;
|
||||
this.textElements.set(id,{raw:raw, parsed: await this.parse(raw)})
|
||||
}
|
||||
@@ -172,14 +239,20 @@ export class ExcalidrawData {
|
||||
id=nanoid();
|
||||
jsonString = jsonString.replaceAll(te.id,id); //brute force approach to replace all occurances (e.g. links, groups,etc.)
|
||||
}
|
||||
if(!this.textElements.has(id)) {
|
||||
if(te.id.length > 8 && this.textElements.has(te.id)) { //element was created with onBeforeTextSubmit
|
||||
const element = this.textElements.get(te.id);
|
||||
this.textElements.set(id,{raw: element.raw, parsed: element.parsed})
|
||||
this.textElements.delete(te.id); //delete the old ID from the Map
|
||||
dirty = true;
|
||||
this.textElements.set(id,{raw: te.text, parsed: null});
|
||||
this.parseasync(id,te.text);
|
||||
} else if(!this.textElements.has(id)) {
|
||||
dirty = true;
|
||||
const raw = (te.rawText && te.rawText!==""?te.rawText:te.text); //this is for compatibility with drawings created before the rawText change on ExcalidrawTextElement
|
||||
this.textElements.set(id,{raw: raw, parsed: null});
|
||||
this.parseasync(id,raw);
|
||||
}
|
||||
}
|
||||
if(dirty) { //reload scene json in case it has changed
|
||||
this.scene = JSON_parse(jsonString);
|
||||
this.scene = JSON.parse(jsonString);
|
||||
}
|
||||
|
||||
return dirty;
|
||||
@@ -190,46 +263,15 @@ export class ExcalidrawData {
|
||||
* and updating the textElement map based on the text updated in the scene
|
||||
*/
|
||||
private async updateTextElementsFromScene() {
|
||||
//console.log("Excalidraw.Data.updateTextElementesFromScene()");
|
||||
for(const key of this.textElements.keys()){
|
||||
//find text element in the scene
|
||||
const el = this.scene.elements?.filter((el:any)=> el.type=="text" && el.id==key);
|
||||
if(el.length==0) {
|
||||
this.textElements.delete(key); //if no longer in the scene, delete the text element
|
||||
} else {
|
||||
if(!this.textElements.has(key)) {
|
||||
const text = await this.getText(key);
|
||||
if(text != el[0].text) {
|
||||
this.textElements.set(key,{raw: el[0].text,parsed: await this.parse(el[0].text)});
|
||||
} else {
|
||||
const text = await this.getText(key);
|
||||
if(text != el[0].text) {
|
||||
this.textElements.set(key,{raw: el[0].text,parsed: await this.parse(el[0].text)});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* update text element map by deleting entries that are no long in the scene
|
||||
* and updating the textElement map based on the text updated in the scene
|
||||
*/
|
||||
private updateTextElementsFromSceneRawOnly() {
|
||||
//console.log("Excalidraw.Data.updateTextElementsFromSceneRawOnly()");
|
||||
for(const key of this.textElements.keys()){
|
||||
//find text element in the scene
|
||||
const el = this.scene.elements?.filter((el:any)=> el.type=="text" && el.id==key);
|
||||
if(el.length==0) {
|
||||
this.textElements.delete(key); //if no longer in the scene, delete the text element
|
||||
} else {
|
||||
if(!this.textElements.has(key)) {
|
||||
this.textElements.set(key,{raw: el[0].text,parsed: null});
|
||||
this.parseasync(key,el[0].text);
|
||||
} else {
|
||||
const text = this.allowParse ? this.textElements.get(key).parsed : this.textElements.get(key).raw;
|
||||
if(text != el[0].text) {
|
||||
this.textElements.set(key,{raw: el[0].text,parsed: null});
|
||||
this.parseasync(key,el[0].text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -239,48 +281,134 @@ export class ExcalidrawData {
|
||||
this.textElements.set(key,{raw:raw,parsed: await this.parse(raw)});
|
||||
}
|
||||
|
||||
private parseLinks(text:string, position:number, parts:any):string {
|
||||
return text.substring(position,parts.value.index) +
|
||||
(this.showLinkBrackets ? "[[" : "") +
|
||||
REGEX_LINK.getAliasOrLink(parts) +
|
||||
(this.showLinkBrackets ? "]]" : "");
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param text
|
||||
* @returns [string,number] - the transcluded text, and the line number for the location of the text
|
||||
*/
|
||||
public async getTransclusion (text:string):Promise<[string,number]> {
|
||||
//file-name#^blockref
|
||||
//1 2 3
|
||||
const REG_FILE_BLOCKREF = /(.*)#(\^)?(.*)/g;
|
||||
const parts=text.matchAll(REG_FILE_BLOCKREF).next();
|
||||
if(!parts.done && !parts.value[1]) return [text,0]; //filename not found
|
||||
const filename = parts.done ? text : parts.value[1];
|
||||
const file = this.app.metadataCache.getFirstLinkpathDest(filename,this.file.path);
|
||||
if(!file || !(file instanceof TFile)) return [text,0];
|
||||
const contents = await this.app.vault.cachedRead(file);
|
||||
if(parts.done) { //no blockreference
|
||||
return([contents.substr(0,this.plugin.settings.pageTransclusionCharLimit),0]);
|
||||
}
|
||||
const isParagraphRef = parts.value[2] ? true : false; //does the reference contain a ^ character?
|
||||
const id = parts.value[3]; //the block ID or heading text
|
||||
const blocks = (await this.app.metadataCache.blockCache.getForFile({isCancelled: ()=>false},file)).blocks.filter((block:any)=>block.node.type!="comment");
|
||||
if(!blocks) return [text,0];
|
||||
if(isParagraphRef) {
|
||||
let para = blocks.filter((block:any)=>block.node.id == id)[0]?.node;
|
||||
if(!para) return [text,0];
|
||||
if(["blockquote","listItem"].includes(para.type)) para = para.children[0]; //blockquotes are special, they have one child, which has the paragraph
|
||||
const startPos = para.position.start.offset;
|
||||
const lineNum = para.position.start.line;
|
||||
const endPos = para.children[para.children.length-1]?.position.start.offset-1; //alternative: filter((c:any)=>c.type=="blockid")[0]
|
||||
return [contents.substr(startPos,endPos-startPos),lineNum]
|
||||
|
||||
} else {
|
||||
const headings = blocks.filter((block:any)=>block.display.startsWith("#"));
|
||||
let startPos:number = null;
|
||||
let lineNum:number = 0;
|
||||
let endPos:number = null;
|
||||
for(let i=0;i<headings.length;i++) {
|
||||
if(startPos && !endPos) {
|
||||
endPos = headings[i].node.position.start.offset-1;
|
||||
return [contents.substr(startPos,endPos-startPos),lineNum];
|
||||
}
|
||||
if(!startPos && headings[i].node.children[0]?.value == id) {
|
||||
startPos = headings[i].node.children[0]?.position.start.offset; //
|
||||
lineNum = headings[i].node.children[0]?.position.start.line; //
|
||||
}
|
||||
}
|
||||
if(startPos) return [contents.substr(startPos),lineNum];
|
||||
return [text,0];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process aliases and block embeds
|
||||
* @param text
|
||||
* @returns
|
||||
*/
|
||||
private async parse(text:string):Promise<string>{
|
||||
const getTransclusion = async (text:string) => {
|
||||
//file-name#^blockref
|
||||
//1 2
|
||||
const REG_FILE_BLOCKREF = /(.*)#\^(.*)/g;
|
||||
const parts=text.matchAll(REG_FILE_BLOCKREF).next();
|
||||
if(parts.done || !parts.value[1] || !parts.value[2]) return text; //filename and/or blockref not found
|
||||
const file = this.app.metadataCache.getFirstLinkpathDest(parts.value[1],this.file.path);
|
||||
const contents = await this.app.vault.cachedRead(file);
|
||||
//get transcluded line and take the part before ^blockref
|
||||
const REG_TRANSCLUDE = new RegExp("(.*)\\s\\^" + parts.value[2]);
|
||||
const res = contents.match(REG_TRANSCLUDE);
|
||||
if(res) return res[1];
|
||||
return text;//if blockref not found in file, return the input string
|
||||
let outString = "";
|
||||
let position = 0;
|
||||
const res = text.matchAll(REGEX_LINK.EXPR);
|
||||
let linkIcon = false;
|
||||
let urlIcon = false;
|
||||
let parts;
|
||||
while(!(parts=res.next()).done) {
|
||||
if (REGEX_LINK.isTransclusion(parts)) { //transclusion //parts.value[1] || parts.value[4]
|
||||
const [contents,lineNum] = await this.getTransclusion(REGEX_LINK.getLink(parts));
|
||||
outString += text.substring(position,parts.value.index) +
|
||||
wrapText(contents,REGEX_LINK.getWrapLength(parts),this.plugin.settings.forceWrap);
|
||||
} else {
|
||||
const parsedLink = this.parseLinks(text,position,parts);
|
||||
if(parsedLink) {
|
||||
outString += parsedLink;
|
||||
if(!(urlIcon || linkIcon))
|
||||
if(REGEX_LINK.getLink(parts).match(REG_LINKINDEX_HYPERLINK)) urlIcon = true;
|
||||
else linkIcon = true;
|
||||
}
|
||||
}
|
||||
position = parts.value.index + parts.value[0].length;
|
||||
}
|
||||
outString += text.substring(position,text.length);
|
||||
if (linkIcon) {
|
||||
outString = this.linkPrefix + outString;
|
||||
}
|
||||
if (urlIcon) {
|
||||
outString = this.urlPrefix + outString;
|
||||
}
|
||||
|
||||
return outString;
|
||||
}
|
||||
|
||||
/**
|
||||
* Does a quick parse of the raw text. Returns the parsed string if raw text does not include a transclusion.
|
||||
* Return null if raw text includes a transclusion.
|
||||
* This is implemented in a separate function, because by nature resolving a transclusion is an asynchronious
|
||||
* activity. Quick parse gets the job done synchronously if possible.
|
||||
* @param text
|
||||
*/
|
||||
private quickParse(text:string):string {
|
||||
const hasTransclusion = (text:string):boolean => {
|
||||
const res = text.matchAll(REGEX_LINK.EXPR);
|
||||
let parts;
|
||||
while(!(parts=res.next()).done) {
|
||||
if (REGEX_LINK.isTransclusion(parts)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (hasTransclusion(text)) return null;
|
||||
|
||||
let outString = "";
|
||||
let position = 0;
|
||||
const res = text.matchAll(REG_LINK_BACKETS);
|
||||
const res = text.matchAll(REGEX_LINK.EXPR);
|
||||
let linkIcon = false;
|
||||
let urlIcon = false;
|
||||
let parts;
|
||||
while(!(parts=res.next()).done) {
|
||||
if (parts.value[1] || parts.value[4]) { //transclusion
|
||||
outString += text.substring(position,parts.value.index) +
|
||||
await getTransclusion(parts.value[1] ? parts.value[2] : parts.value[6]);
|
||||
} else if (parts.value[2]) {
|
||||
linkIcon = true;
|
||||
outString += text.substring(position,parts.value.index) +
|
||||
(this.showLinkBrackets ? "[[" : "") +
|
||||
(parts.value[3] ? parts.value[3]:parts.value[2]) + //insert alias or link text
|
||||
(this.showLinkBrackets ? "]]" : "");
|
||||
} else {
|
||||
linkIcon = true;
|
||||
outString += text.substring(position,parts.value.index) +
|
||||
(this.showLinkBrackets ? "[[" : "") +
|
||||
(parts.value[5] ? parts.value[5]:parts.value[6]) + //insert alias or link text
|
||||
(this.showLinkBrackets ? "]]" : "");
|
||||
const parsedLink = this.parseLinks(text,position,parts);
|
||||
if(parsedLink) {
|
||||
outString += parsedLink;
|
||||
if(!(urlIcon || linkIcon))
|
||||
if(REGEX_LINK.getLink(parts).match(REG_LINKINDEX_HYPERLINK)) urlIcon = true;
|
||||
else linkIcon = true;
|
||||
}
|
||||
position = parts.value.index + parts.value[0].length;
|
||||
}
|
||||
@@ -288,40 +416,39 @@ export class ExcalidrawData {
|
||||
if (linkIcon) {
|
||||
outString = this.linkPrefix + outString;
|
||||
}
|
||||
|
||||
if (urlIcon) {
|
||||
outString = this.urlPrefix + outString;
|
||||
}
|
||||
return outString;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Generate markdown file representation of excalidraw drawing
|
||||
* @returns markdown string
|
||||
*/
|
||||
generateMD():string {
|
||||
//console.log("Excalidraw.Data.generateMD()");
|
||||
let outString = '# Text Elements\n';
|
||||
for(const key of this.textElements.keys()){
|
||||
outString += this.textElements.get(key).raw+' ^'+key+'\n\n';
|
||||
}
|
||||
return outString + '# Drawing\n'
|
||||
+ String.fromCharCode(96)+String.fromCharCode(96)+String.fromCharCode(96)+'json\n'
|
||||
+ JSON.stringify(this.scene) + '\n'
|
||||
+ String.fromCharCode(96)+String.fromCharCode(96)+String.fromCharCode(96);
|
||||
return outString + this.plugin.getMarkdownDrawingSection(JSON.stringify(this.scene));
|
||||
}
|
||||
|
||||
public syncElements(newScene:any):boolean {
|
||||
public async syncElements(newScene:any):Promise<boolean> {
|
||||
//console.log("Excalidraw.Data.syncElements()");
|
||||
this.scene = newScene;//JSON_parse(newScene);
|
||||
const result = this.setLinkPrefix() || this.setShowLinkBrackets() || this.findNewTextElementsInScene();
|
||||
this.updateTextElementsFromSceneRawOnly();
|
||||
return result;
|
||||
const result = this.setLinkPrefix() || this.setUrlPrefix() || this.setShowLinkBrackets();
|
||||
await this.updateTextElementsFromScene();
|
||||
return result || this.findNewTextElementsInScene();
|
||||
}
|
||||
|
||||
public async updateScene(newScene:any){
|
||||
//console.log("Excalidraw.Data.updateScene()");
|
||||
this.scene = JSON_parse(newScene);
|
||||
const result = this.setLinkPrefix() || this.setShowLinkBrackets() || this.findNewTextElementsInScene();
|
||||
const result = this.setLinkPrefix() || this.setUrlPrefix() || this.setShowLinkBrackets();
|
||||
await this.updateTextElementsFromScene();
|
||||
if(result) {
|
||||
if(result || this.findNewTextElementsInScene()) {
|
||||
await this.updateSceneTextElements();
|
||||
return true;
|
||||
};
|
||||
@@ -331,6 +458,34 @@ export class ExcalidrawData {
|
||||
public getRawText(id:string) {
|
||||
return this.textElements.get(id)?.raw;
|
||||
}
|
||||
|
||||
public getParsedText(id:string):string {
|
||||
return this.textElements.get(id)?.parsed;
|
||||
}
|
||||
|
||||
public setTextElement(elementID:string, rawText:string, updateScene:Function):string {
|
||||
const parseResult = this.quickParse(rawText); //will return the parsed result if raw text does not include transclusion
|
||||
if(parseResult) { //No transclusion
|
||||
this.textElements.set(elementID,{raw: rawText,parsed: parseResult});
|
||||
return parseResult;
|
||||
}
|
||||
//transclusion needs to be resolved asynchornously
|
||||
this.parse(rawText).then((parsedText:string)=> {
|
||||
this.textElements.set(elementID,{raw: rawText,parsed: parsedText});
|
||||
if(parsedText) updateScene(parsedText);
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
public async addTextElement(elementID:string, rawText:string):Promise<string> {
|
||||
const parseResult = await this.parse(rawText);
|
||||
this.textElements.set(elementID,{raw: rawText,parsed: parseResult});
|
||||
return parseResult;
|
||||
}
|
||||
|
||||
public deleteTextElement(id:string) {
|
||||
this.textElements.delete(id);
|
||||
}
|
||||
|
||||
private setLinkPrefix():boolean {
|
||||
const linkPrefix = this.linkPrefix;
|
||||
@@ -338,20 +493,33 @@ export class ExcalidrawData {
|
||||
if (fileCache?.frontmatter && fileCache.frontmatter[FRONTMATTER_KEY_CUSTOM_PREFIX]!=null) {
|
||||
this.linkPrefix=fileCache.frontmatter[FRONTMATTER_KEY_CUSTOM_PREFIX];
|
||||
} else {
|
||||
this.linkPrefix = this.settings.linkPrefix;
|
||||
this.linkPrefix = this.plugin.settings.linkPrefix;
|
||||
}
|
||||
return linkPrefix != this.linkPrefix;
|
||||
}
|
||||
|
||||
private setUrlPrefix():boolean {
|
||||
const urlPrefix = this.urlPrefix;
|
||||
const fileCache = this.app.metadataCache.getFileCache(this.file);
|
||||
if (fileCache?.frontmatter && fileCache.frontmatter[FRONTMATTER_KEY_CUSTOM_URL_PREFIX]!=null) {
|
||||
this.urlPrefix=fileCache.frontmatter[FRONTMATTER_KEY_CUSTOM_URL_PREFIX];
|
||||
} else {
|
||||
this.urlPrefix = this.plugin.settings.urlPrefix;
|
||||
}
|
||||
return urlPrefix != this.urlPrefix;
|
||||
}
|
||||
|
||||
private setShowLinkBrackets():boolean {
|
||||
const showLinkBrackets = this.showLinkBrackets;
|
||||
const fileCache = this.app.metadataCache.getFileCache(this.file);
|
||||
if (fileCache?.frontmatter && fileCache.frontmatter[FRONTMATTER_KEY_CUSTOM_LINK_BRACKETS]!=null) {
|
||||
this.showLinkBrackets=fileCache.frontmatter[FRONTMATTER_KEY_CUSTOM_LINK_BRACKETS]!=false;
|
||||
} else {
|
||||
this.showLinkBrackets = this.settings.showLinkBrackets;
|
||||
this.showLinkBrackets = this.plugin.settings.showLinkBrackets;
|
||||
}
|
||||
return showLinkBrackets != this.showLinkBrackets;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
43
src/InsertLinkDialog.ts
Normal file
43
src/InsertLinkDialog.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import {
|
||||
App,
|
||||
FuzzySuggestModal,
|
||||
TFile
|
||||
} from "obsidian";
|
||||
import {t} from './lang/helpers'
|
||||
|
||||
export class InsertLinkDialog extends FuzzySuggestModal<TFile> {
|
||||
public app: App;
|
||||
private addText: Function;
|
||||
private drawingPath: string;
|
||||
|
||||
constructor(app: App) {
|
||||
super(app);
|
||||
this.app = app;
|
||||
this.limit = 20;
|
||||
this.setInstructions([{
|
||||
command: t("SELECT_FILE"),
|
||||
purpose: "",
|
||||
}]);
|
||||
this.setPlaceholder(t("SELECT_FILE_TO_LINK"));
|
||||
this.emptyStateText = t("NO_MATCH");
|
||||
}
|
||||
|
||||
getItems(): TFile[] {
|
||||
return this.app.vault.getFiles();
|
||||
}
|
||||
|
||||
getItemText(item: TFile): string {
|
||||
return item.path;
|
||||
}
|
||||
|
||||
onChooseItem(item: TFile, _evt: MouseEvent | KeyboardEvent): void {
|
||||
const filepath = this.app.metadataCache.fileToLinktext(item,this.drawingPath,true);
|
||||
this.addText("[["+filepath+"]]");
|
||||
}
|
||||
|
||||
public start(drawingPath:string, addText: Function) {
|
||||
this.addText = addText;
|
||||
this.drawingPath = drawingPath;
|
||||
this.open();
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ export class Prompt extends Modal {
|
||||
private promptEl: HTMLInputElement;
|
||||
private resolve: (value: string) => void;
|
||||
|
||||
constructor(app: App, private prompt_text: string, private default_value: string) {
|
||||
constructor(app: App, private prompt_text: string, private default_value: string, private placeholder:string) {
|
||||
super(app);
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ export class Prompt extends Modal {
|
||||
|
||||
this.promptEl = form.createEl("input");
|
||||
this.promptEl.type = "text";
|
||||
this.promptEl.placeholder = "$\\theta$";
|
||||
this.promptEl.placeholder = this.placeholder;
|
||||
this.promptEl.value = this.default_value ?? "";
|
||||
this.promptEl.addClass("excalidraw-prompt-input")
|
||||
this.promptEl.select();
|
||||
|
||||
152
src/Utils.ts
152
src/Utils.ts
@@ -1,4 +1,9 @@
|
||||
import { normalizePath, TFolder } from "obsidian";
|
||||
import { App, normalizePath, TAbstractFile, TFile, TFolder, Vault } from "obsidian";
|
||||
import { Random } from "roughjs/bin/math";
|
||||
import { Zoom } from "@zsviczian/excalidraw/types/types";
|
||||
import { nanoid } from "nanoid";
|
||||
import { IMAGE_TYPES } from "./constants";
|
||||
|
||||
|
||||
/**
|
||||
* Splits a full path including a folderpath and a filename into separate folderpath and filename components
|
||||
@@ -39,4 +44,147 @@ export function getIMGPathFromExcalidrawFile (excalidrawPath:string,newExtension
|
||||
const isLegacyFile:boolean = excalidrawPath.endsWith(".excalidraw");
|
||||
const replaceExtension:string = isLegacyFile ? ".excalidraw" : ".md";
|
||||
return excalidrawPath.substring(0,excalidrawPath.lastIndexOf(replaceExtension)) + newExtension;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new file, if file already exists find first unique filename by adding a number to the end of the filename
|
||||
* @param filename
|
||||
* @param folderpath
|
||||
* @returns
|
||||
*/
|
||||
export function getNewUniqueFilepath(vault:Vault, filename:string, folderpath:string):string {
|
||||
let fname = normalizePath(folderpath +'/'+ filename);
|
||||
let file:TAbstractFile = vault.getAbstractFileByPath(fname);
|
||||
let i = 0;
|
||||
while(file) {
|
||||
fname = normalizePath(folderpath + '/' + filename.slice(0,filename.lastIndexOf("."))+"_"+i+filename.slice(filename.lastIndexOf(".")));
|
||||
i++;
|
||||
file = vault.getAbstractFileByPath(fname);
|
||||
}
|
||||
return fname;
|
||||
}
|
||||
|
||||
/**
|
||||
* Open or create a folderpath if it does not exist
|
||||
* @param folderpath
|
||||
*/
|
||||
export async function checkAndCreateFolder(vault:Vault,folderpath:string) {
|
||||
folderpath = normalizePath(folderpath);
|
||||
let folder = vault.getAbstractFileByPath(folderpath);
|
||||
if(folder && folder instanceof TFolder) return;
|
||||
await vault.createFolder(folderpath);
|
||||
}
|
||||
|
||||
let random = new Random(Date.now());
|
||||
export const randomInteger = () => Math.floor(random.next() * 2 ** 31);
|
||||
|
||||
//https://macromates.com/blog/2006/wrapping-text-with-regular-expressions/
|
||||
export function wrapText(text:string, lineLen:number, forceWrap:boolean=false):string {
|
||||
if(!lineLen) return text;
|
||||
let outstring = "";
|
||||
if(forceWrap) {
|
||||
for(const t of text.split("\n")) {
|
||||
const v = t.match(new RegExp('(.){1,'+lineLen+'}','g'));
|
||||
outstring += v ? v.join("\n")+"\n" : "\n";
|
||||
}
|
||||
return outstring.replace(/\n$/, '');
|
||||
}
|
||||
|
||||
// 1 2 3 4
|
||||
const reg = new RegExp(`(.{1,${lineLen}})(\\s+|$\\n?)|([^\\s]+)(\\s+|$\\n?)`,'gm');
|
||||
const res = text.matchAll(reg);
|
||||
let parts;
|
||||
while(!(parts = res.next()).done) {
|
||||
outstring += parts.value[1] ? parts.value[1].trimEnd() : parts.value[3].trimEnd();
|
||||
const newLine1 = parts.value[2]?.includes("\n");
|
||||
const newLine2 = parts.value[4]?.includes("\n");
|
||||
if(newLine1) outstring += parts.value[2];
|
||||
if(newLine2) outstring += parts.value[4];
|
||||
if(!(newLine1 || newLine2)) outstring += "\n";
|
||||
}
|
||||
return outstring.replace(/\n$/, '');
|
||||
}
|
||||
|
||||
export const viewportCoordsToSceneCoords = (
|
||||
{ clientX, clientY }: { clientX: number; clientY: number },
|
||||
{
|
||||
zoom,
|
||||
offsetLeft,
|
||||
offsetTop,
|
||||
scrollX,
|
||||
scrollY,
|
||||
}: {
|
||||
zoom: Zoom;
|
||||
offsetLeft: number;
|
||||
offsetTop: number;
|
||||
scrollX: number;
|
||||
scrollY: number;
|
||||
},
|
||||
) => {
|
||||
const invScale = 1 / zoom.value;
|
||||
const x = (clientX - zoom.translation.x - offsetLeft) * invScale - scrollX;
|
||||
const y = (clientY - zoom.translation.y - offsetTop) * invScale - scrollY;
|
||||
return { x, y };
|
||||
};
|
||||
|
||||
export const getObsidianImage = async (app: App, file: TFile)
|
||||
:Promise<{
|
||||
imageId: string,
|
||||
dataURL: string,
|
||||
size: {height: number, width: number},
|
||||
}> => {
|
||||
if(!app || !file) return null;
|
||||
if (!IMAGE_TYPES.contains(file.extension)) return null;
|
||||
const ab = await app.vault.readBinary(file);
|
||||
return {
|
||||
imageId: await generateIdFromFile(ab),
|
||||
dataURL: file.extension==="svg" ? await getSVGData(app,file) : await getDataURL(ab),
|
||||
size: await getImageSize(app,file)
|
||||
}
|
||||
}
|
||||
|
||||
const getSVGData = async (app: App, file: TFile): Promise<string> => {
|
||||
const svg = await app.vault.read(file);
|
||||
return "data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(svg.replaceAll(" "," "))))
|
||||
}
|
||||
|
||||
const getDataURL = async (file: ArrayBuffer): Promise<string> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const dataURL = reader.result as string;
|
||||
resolve(dataURL);
|
||||
};
|
||||
reader.onerror = (error) => reject(error);
|
||||
reader.readAsDataURL(new Blob([new Uint8Array(file)]));
|
||||
});
|
||||
};
|
||||
|
||||
const generateIdFromFile = async (file: ArrayBuffer):Promise<string> => {
|
||||
let id: string;
|
||||
try {
|
||||
const hashBuffer = await window.crypto.subtle.digest(
|
||||
"SHA-1",
|
||||
file,
|
||||
);
|
||||
id =
|
||||
// convert buffer to byte array
|
||||
Array.from(new Uint8Array(hashBuffer))
|
||||
// convert to hex string
|
||||
.map((byte) => byte.toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
id = nanoid(40);
|
||||
}
|
||||
return id;
|
||||
};
|
||||
|
||||
const getImageSize = async (app: App, file:TFile):Promise<{height:number, width:number}> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
let img = new Image()
|
||||
img.onload = () => resolve({height: img.height, width:img.width});
|
||||
img.onerror = reject;
|
||||
img.src = app.vault.getResourcePath(file);
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
//This is to avoid brackets littering graph view with links
|
||||
//export function JSON_stringify(x:any):string {return JSON.stringify(x).replaceAll("[","[");}
|
||||
//This is only for backward compatibility because an early version of obsidian included an encoding to avoid fantom links from littering Obsidian graph view
|
||||
export function JSON_parse(x:string):any {return JSON.parse(x.replaceAll("[","["));}
|
||||
|
||||
import {customAlphabet} from "nanoid";
|
||||
export const nanoid = customAlphabet('1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',8);
|
||||
export const IMAGE_TYPES = ['jpeg', 'jpg', 'png', 'gif', 'svg', 'bmp'];
|
||||
export const MAX_IMAGE_SIZE = 600;
|
||||
export const FRONTMATTER_KEY = "excalidraw-plugin";
|
||||
export const FRONTMATTER_KEY_CUSTOM_PREFIX = "excalidraw-link-prefix";
|
||||
export const FRONTMATTER_KEY_CUSTOM_URL_PREFIX = "excalidraw-url-prefix";
|
||||
export const FRONTMATTER_KEY_CUSTOM_LINK_BRACKETS = "excalidraw-link-brackets";
|
||||
export const VIEW_TYPE_EXCALIDRAW = "excalidraw";
|
||||
export const ICON_NAME = "excalidraw-icon";
|
||||
@@ -13,12 +15,12 @@ export const MAX_COLORS = 5;
|
||||
export const COLOR_FREQ = 6;
|
||||
export const RERENDER_EVENT = "excalidraw-embed-rerender";
|
||||
export const BLANK_DRAWING = '{"type":"excalidraw","version":2,"source":"https://excalidraw.com","elements":[],"appState":{"gridSize":null,"viewBackgroundColor":"#ffffff"}}';
|
||||
export const FRONTMATTER = ["---","",`${FRONTMATTER_KEY}: unlocked`,"","---", "", ""].join("\n");
|
||||
export const FRONTMATTER = ["---","",`${FRONTMATTER_KEY}: parsed`,"","---", "==⚠ Switch to EXCALIDRAW VIEW in the MORE OPTIONS menu of this document. ⚠==", "",""].join("\n");
|
||||
export const EMPTY_MESSAGE = "Hit enter to create a new drawing";
|
||||
export const LOCK_ICON_NAME = "lock";
|
||||
export const LOCK_ICON = `<path fill="currentColor" stroke="currentColor" d="M35.715 42.855h28.57v-10.71c0-3.946-1.394-7.313-4.183-10.102-2.793-2.79-6.157-4.188-10.102-4.188-3.945 0-7.309 1.399-10.102 4.188-2.789 2.789-4.183 6.156-4.183 10.102zm46.43 5.36v32.14c0 1.489-.524 2.754-1.563 3.797-1.043 1.043-2.309 1.563-3.797 1.563h-53.57c-1.488 0-2.754-.52-3.797-1.563-1.04-1.043-1.563-2.308-1.563-3.797v-32.14c0-1.488.524-2.754 1.563-3.797 1.043-1.04 2.309-1.563 3.797-1.563H25v-10.71c0-6.848 2.457-12.727 7.367-17.637S43.157 7.145 50 7.145c6.844 0 12.723 2.453 17.633 7.363C72.543 19.418 75 25.297 75 32.145v10.71h1.785c1.488 0 2.754.524 3.797 1.563 1.04 1.043 1.563 2.309 1.563 3.797zm0 0"/>`
|
||||
export const UNLOCK_ICON_NAME = "unlock";
|
||||
export const UNLOCK_ICON = `<path fill="currentColor" stroke="currentColor" d="M96.43 32.145V46.43c0 .965-.356 1.804-1.063 2.511-.707.707-1.543 1.059-2.512 1.059h-3.57c-.965 0-1.805-.352-2.512-1.059-.707-.707-1.058-1.546-1.058-2.511V32.145c0-3.946-1.395-7.313-4.188-10.102-2.789-2.79-6.156-4.188-10.097-4.188-3.946 0-7.313 1.399-10.102 4.188-2.789 2.789-4.183 6.156-4.183 10.102v10.71H62.5c1.488 0 2.754.524 3.793 1.563 1.043 1.043 1.562 2.309 1.562 3.797v32.14c0 1.489-.52 2.754-1.562 3.797-1.04 1.043-2.305 1.563-3.793 1.563H8.93c-1.489 0-2.754-.52-3.797-1.563-1.04-1.043-1.563-2.308-1.563-3.797v-32.14c0-1.488.524-2.754 1.563-3.797 1.043-1.04 2.308-1.563 3.797-1.563h37.5v-10.71c0-6.883 2.445-12.77 7.336-17.665 4.894-4.89 10.78-7.335 17.664-7.335 6.882 0 12.77 2.445 17.66 7.335 4.894 4.895 7.34 10.782 7.34 17.665zm0 0"/>`;
|
||||
export const TEXT_DISPLAY_PARSED_ICON_NAME = "quote-glyph";
|
||||
export const TEXT_DISPLAY_RAW_ICON_NAME = "presentation";
|
||||
export const FULLSCREEN_ICON_NAME="fullscreen";
|
||||
export const EXIT_FULLSCREEN_ICON_NAME = "exit-fullscreen";
|
||||
export const DISK_ICON_NAME = "disk";
|
||||
export const DISK_ICON = `<path fill="none" stroke="currentColor" fill="#fff" d="M0 0h100v100H0z"/><path fill="none" stroke="currentColor" d="M20.832 4.168c21.824.145 43.645.289 74.68.5m-74.68-.5c17.09.113 34.176.227 74.68.5m0 0c.094 27.3.191 54.602.32 91.164m-.32-91.164c.113 32.633.23 65.27.32 91.164m0 0H4.168m91.664 0H4.168m0 0v-75m0 75v-75m0 0L20.832 4.168M4.168 20.832L20.832 4.168M20.832 4.168h58.336m-58.336 0h58.336m0 0v25m0-25v25m0 0H20.832m58.336 0H20.832m0 0v-25m0 25v-25" stroke-width="1.66668" /><path fill="none" stroke="currentColor" d="M29.168 4.168h16.664v16.664H29.168"/><path fill="none" stroke="currentColor" d="M29.168 4.168h16.664m-16.664 0h16.664m0 0v16.664m0-16.664v16.664m0 0H29.168m16.664 0H29.168m0 0V4.168m0 16.664V4.168M12.5 54.168h75m-75 0h75m0 0v41.664m0-41.664v41.664m0 0h-75m75 0h-75m0 0V54.168m0 41.664V54.168M20.832 62.5c20.11-.18 40.219-.36 55.68-.5m-55.68.5c14.656-.133 29.313-.262 55.68-.5M20.832 71.332c13.098-.117 26.2-.234 55.68-.5m-55.68.5l55.68-.5M21.117 79.582c20.645-.184 41.285-.371 55.68-.5m-55.68.5c18.153-.16 36.301-.324 55.68-.5" stroke-width="1.66668"/>`;
|
||||
export const PNG_ICON_NAME = "save-png";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FRONTMATTER_KEY_CUSTOM_LINK_BRACKETS, FRONTMATTER_KEY_CUSTOM_PREFIX } from "src/constants";
|
||||
import { FRONTMATTER_KEY_CUSTOM_LINK_BRACKETS, FRONTMATTER_KEY_CUSTOM_PREFIX, FRONTMATTER_KEY_CUSTOM_URL_PREFIX } from "src/constants";
|
||||
|
||||
// English
|
||||
export default {
|
||||
@@ -21,7 +21,7 @@ export default {
|
||||
NEW_IN_ACTIVE_PANE_EMBED: "Create a new drawing - IN THE CURRENT ACTIVE PANE - 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 LOCK/UNLOCK",
|
||||
TOGGLE_LOCK: "Toggle Text Element edit RAW/PREVIEW",
|
||||
INSERT_LINK: "Insert link to file",
|
||||
INSERT_LATEX: "Insert LaTeX-symbol (e.g. $\\theta$)",
|
||||
ENTER_LATEX: "Enter a valid LaTeX expression",
|
||||
@@ -32,7 +32,6 @@ export default {
|
||||
SAVE_AS_SVG: "Save as SVG into Vault (CTRL/META+CLICK to export)",
|
||||
OPEN_LINK: "Open selected text as link\n(SHIFT+CLICK to open in a new pane)",
|
||||
EXPORT_EXCALIDRAW: "Export to an .Excalidraw file",
|
||||
UNLOCK_TO_EDIT: "UNLOCKED Text Elements automatically to allow edit",
|
||||
LINK_BUTTON_CLICK_NO_TEXT: 'Select a Text Element containing an internal or external link.\n'+
|
||||
'SHIFT CLICK this button to open the link in a new pane.\n'+
|
||||
'CTRL/META CLICK the Text Element on the canvas has the same effect!',
|
||||
@@ -40,11 +39,13 @@ export default {
|
||||
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: "Force-save to update transclusions in adjacent panes.\n(Please note, that autosave is always on)",
|
||||
LOCK: "Text Elements are unlocked. Click to LOCK.",
|
||||
UNLOCK: "Text Elements are locked. Click to UNLOCK.",
|
||||
RAW: "Change to PREVIEW mode (only effects text-elements with links or transclusions)",
|
||||
PARSED: "Change to RAW mode (only effects text-elements with links or transclusions)",
|
||||
NOFILE: "Excalidraw (no file)",
|
||||
COMPATIBILITY_MODE: "*.excalidraw file opened in compatibility mode. Convert to new format for full plugin functionality.",
|
||||
CONVERT_FILE: "Convert to new format",
|
||||
DRAWING_CONTAINS_IMAGE: "Warning! The drawing contains image elements. Depending on the number and size of the images, " +
|
||||
"loading Markdown View may take a while. Please be patient. ",
|
||||
|
||||
//settings.ts
|
||||
FOLDER_NAME: "Excalidraw folder",
|
||||
@@ -52,7 +53,7 @@ export default {
|
||||
TEMPLATE_NAME: "Excalidraw template file",
|
||||
TEMPLATE_DESC: "Full filepath to the Excalidraw template. " +
|
||||
"E.g.: If your template is in the default Excalidraw folder and it's name is " +
|
||||
"Template.md, the setting would be: Excalidraw/Template.md " +
|
||||
"Template.md, the setting would be: Excalidraw/Template.md (or just Excalidraw/Template - you may ommit the .md file extension" +
|
||||
"If you are using Excalidraw in compatibility mode, then your template must be a legacy excalidraw file as well " +
|
||||
"such as Excalidraw/Template.excalidraw.",
|
||||
AUTOSAVE_NAME: "Autosave",
|
||||
@@ -70,7 +71,10 @@ export default {
|
||||
FILENAME_PREFIX_DESC: "The first part of the filename",
|
||||
FILENAME_DATE_NAME: "Filename date",
|
||||
FILENAME_DATE_DESC: "The second part of the filename",
|
||||
LINKS_HEAD: "Links",
|
||||
DISPLAY_HEAD: "Display",
|
||||
ZOOM_TO_FIT_NAME: "Zoom to fit on view resize",
|
||||
ZOOM_TO_FIT_DESC: "Zoom to fit drawing when the pane is resized",
|
||||
LINKS_HEAD: "Links and transclusion",
|
||||
LINKS_DESC: "CTRL/META + CLICK on Text Elements to open them as links. " +
|
||||
"If the selected text has more than one [[valid Obsidian links]], only the first will be opened. " +
|
||||
"If the text starts as a valid web link (i.e. https:// or http://), then " +
|
||||
@@ -78,21 +82,41 @@ export default {
|
||||
"When Obsidian files change, the matching [[link]] in your drawings will also change. " +
|
||||
"If you don't want text accidentally changing in your drawings use [[links|with aliases]].",
|
||||
LINK_BRACKETS_NAME: "Show [[brackets]] around links",
|
||||
LINK_BRACKETS_DESC: "In preview (locked) mode, when parsing Text Elements, place brackets around links. " +
|
||||
LINK_BRACKETS_DESC: "In PREVIEW mode, when parsing Text Elements, place brackets around links. " +
|
||||
"You can override this setting for a specific drawing by adding '" + FRONTMATTER_KEY_CUSTOM_LINK_BRACKETS +
|
||||
": true/false' to the file\'s frontmatter.",
|
||||
LINK_PREFIX_NAME:"Link prefix",
|
||||
LINK_PREFIX_DESC:"In preview (locked) mode, if the Text Element contains a link, precede the text with these characters. " +
|
||||
LINK_PREFIX_DESC:"In PREVIEW mode, if the Text Element contains a link, precede the text with these characters. " +
|
||||
"You can override this setting for a specific drawing by adding \'" + FRONTMATTER_KEY_CUSTOM_PREFIX +
|
||||
': "👉 "\' to the file\'s frontmatter.',
|
||||
': "📍 "\' to the file\'s frontmatter.',
|
||||
URL_PREFIX_NAME:"URL prefix",
|
||||
URL_PREFIX_DESC:"In PREVIEW mode, if the Text Element contains a URL link, precede the text with these characters. " +
|
||||
"You can override this setting for a specific drawing by adding \'" + FRONTMATTER_KEY_CUSTOM_URL_PREFIX +
|
||||
': "🌐 "\' to the file\'s frontmatter.',
|
||||
LINK_CTRL_CLICK_NAME: "CTRL + CLICK on text to open them as links",
|
||||
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.",
|
||||
TRANSCLUSION_WRAP_NAME: "Overflow wrap behavior of transcluded text",
|
||||
TRANSCLUSION_WRAP_DESC: "Number specifies the character count where the text should be wrapped. " +
|
||||
"Set the text wrapping behavior of transcluded text. Turn this ON to force-wrap " +
|
||||
"text (i.e. no overflow), or OFF to soft-warp text (at the nearest whitespace).",
|
||||
PAGE_TRANSCLUSION_CHARCOUNT_NAME: "Page transclusion max char count",
|
||||
PAGE_TRANSCLUSION_CHARCOUNT_DESC: "The maximum number of characters to display from the page when transcluding an entire page with the "+
|
||||
"![[markdown page]] format.",
|
||||
EMBED_HEAD: "Embed & Export",
|
||||
EMBED_PREVIEW_SVG_NAME: "Display SVG in markdown preview",
|
||||
EMBED_PREVIEW_SVG_DESC: "The default is to display drawings as SVG images in the markdown preview. Turning this feature off, the markdown preview will display the drawing as an embedded PNG image.",
|
||||
EMBED_WIDTH_NAME: "Default width of embedded (transcluded) image",
|
||||
EMBED_WIDTH_DESC: "The default width of an embedded drawing. You can specify a custom " +
|
||||
EMBED_WIDTH_DESC: "Only relevant if embed type is excalidraw. Has no effect on PNG and SVG embeds. The default width of an embedded drawing. You can specify a custom " +
|
||||
"width when embedding an image using the ![[drawing.excalidraw|100]] or " +
|
||||
"[[drawing.excalidraw|100x100]] format.",
|
||||
EMBED_TYPE_NAME: "Type of file to insert into the document",
|
||||
EMBED_TYPE_DESC: "When you embed an image into a document using the command palette this setting will specify if Excalidraw should embed the original excalidraw file "+
|
||||
"or a PNG or an SVG copy. You need to enable auto-export PNG / SVG (see below under Export Settings) for those image types to be available in the dropdown. For drawings that do not have a " +
|
||||
"a correspondign PNG or SVG readily available the command palette action will insert a broken link. You need to open the original drawing and initiate export manually. " +
|
||||
"This option will not autogenerate PNG/SVG files, but will simply reference the already existing files.",
|
||||
EXPORT_PNG_SCALE_NAME: "PNG export image scale",
|
||||
EXPORT_PNG_SCALE_DESC: "The size-scale of the exported PNG image",
|
||||
EXPORT_BACKGROUND_NAME: "Export image with background",
|
||||
EXPORT_BACKGROUND_DESC: "If turned off, the exported image will be transparent.",
|
||||
EXPORT_THEME_NAME: "Export image with theme",
|
||||
@@ -125,7 +149,7 @@ export default {
|
||||
FILETYPE_DESC: "Excalidraw files will receive an indicator using the emojii or text defined in the next setting.",
|
||||
FILETAG_NAME: "Set the type indicator for excalidraw.md files",
|
||||
FILETAG_DESC: "The text or emojii to display as type indicator.",
|
||||
|
||||
INSERT_EMOJI: "Insert an emoji",
|
||||
|
||||
|
||||
//openDrawings.ts
|
||||
|
||||
@@ -1,3 +1,140 @@
|
||||
// 简体中文
|
||||
|
||||
export default {};
|
||||
// 简体中文
|
||||
|
||||
import { FRONTMATTER_KEY_CUSTOM_LINK_BRACKETS, FRONTMATTER_KEY_CUSTOM_PREFIX } from "src/constants";
|
||||
|
||||
export default {
|
||||
// main.ts
|
||||
OPEN_AS_EXCALIDRAW: "打开为 Excalidraw 绘图",
|
||||
TOGGLE_MODE: "在 Excalidraw 和 Markdown 模式之间切换",
|
||||
CONVERT_NOTE_TO_EXCALIDRAW: "转换空白笔记为 Excalidraw 绘图",
|
||||
CONVERT_EXCALIDRAW: "转换 *.excalidraw 为 *.md 文件",
|
||||
CREATE_NEW : "新建 Excalidraw 绘图",
|
||||
CONVERT_FILE_KEEP_EXT: "*.excalidraw 格式 => *.excalidraw.md 格式",
|
||||
CONVERT_FILE_REPLACE_EXT: "*.excalidraw 格式 => *.md (Logseq compatibility) 格式",
|
||||
DOWNLOAD_LIBRARY: "导出 stencil 库为 *.excalidrawlib 文件",
|
||||
OPEN_EXISTING_NEW_PANE: "在新面板中打开已存在的绘图",
|
||||
OPEN_EXISTING_ACTIVE_PANE: "在当前面板中打开已存在的绘图",
|
||||
TRANSCLUDE: "嵌入绘图",
|
||||
TRANSCLUDE_MOST_RECENT: "嵌入最近编辑的绘图",
|
||||
NEW_IN_NEW_PANE: "在新面板中创建已存在的绘图",
|
||||
NEW_IN_ACTIVE_PANE: "在当前面板中创建已存在的绘图",
|
||||
NEW_IN_NEW_PANE_EMBED: "在新面板中创建已存在的绘图且嵌入到当前笔记中",
|
||||
NEW_IN_ACTIVE_PANE_EMBED: "在当前面板中创建已存在的绘图且嵌入到当前笔记中",
|
||||
EXPORT_SVG: "导出 SVG 文件到当前文件的目录中",
|
||||
EXPORT_PNG: "导出 PNG 文件到当前文件的目录中",
|
||||
TOGGLE_LOCK: "切换文本元素锁定模式",
|
||||
INSERT_LINK: "在文件中插入链接",
|
||||
INSERT_LATEX: "在文件中插入 LaTeX 符号 (e.g. $\\theta$)",
|
||||
ENTER_LATEX: "输入一个 LaTeX 表达式",
|
||||
|
||||
//ExcalidrawView.ts
|
||||
OPEN_AS_MD: "打开为 Markdown 文件",
|
||||
SAVE_AS_PNG: "保存成 PNG 文件到库里(CTRL/META 加左键点击来指定导出位置)",
|
||||
SAVE_AS_SVG: "保存成 SVG 文件到库里(CTRL/META 加左键点击来指定导出位置)",
|
||||
OPEN_LINK: "以链接的方式打开文本 \n(按住 SHIFT 来在新面板中打开)",
|
||||
EXPORT_EXCALIDRAW: "导出为 .Excalidraw 文件",
|
||||
LINK_BUTTON_CLICK_NO_TEXT: '选择带有外部链接或内部链接的文本。\n'+
|
||||
'SHIFT 加左键点击按钮来在新面板中打开链接。\n'+
|
||||
'CTRL/META 加左键在画布中点击文本元素也可以打开对应的链接。',
|
||||
TEXT_ELEMENT_EMPTY: "文本元素没有链接任何东西.",
|
||||
FILENAME_INVALID_CHARS: '文件名不能包含以下符号: * " \\ < > : | ?',
|
||||
FILE_DOES_NOT_EXIST: "文件不存在。按住 ALT(或者 ALT + SHIFT)加左键点击来创建新文件。",
|
||||
FORCE_SAVE: "强制保存以更新相邻面板中的嵌入。\n(请注意,自动保存始终处于开启状态)",
|
||||
RAW: "文本元素正以原文模式显示。 单击按钮更改为预览模式。",
|
||||
PARSED: "文本元素正以预览模式显示。 单击按钮更改为原文模式。",
|
||||
NOFILE: "Excalidraw (没有文件)",
|
||||
COMPATIBILITY_MODE: "*.excalidraw 文件以兼容模式打开。转换为新格式以获得完整的插件功能。",
|
||||
CONVERT_FILE: "转换为新格式",
|
||||
|
||||
//settings.ts
|
||||
FOLDER_NAME: "Excalidraw 文件夹",
|
||||
FOLDER_DESC: "新绘图的默认位置。如果此处为空,将在 Vault 根目录中创建绘图。",
|
||||
TEMPLATE_NAME: "Excalidraw 模板文件",
|
||||
TEMPLATE_DESC: "Excalidraw 模板的完整文件路径。" +
|
||||
"例如:如果您的模板在默认的 Excalidraw 文件夹中且它的名称是" +
|
||||
"Template.md,你应当设置为:Excalidraw/Template.md。" +
|
||||
"如果您在兼容模式下使用 Excalidraw,那么您的模板也必须是旧的 excalidraw 文件," +
|
||||
"例如 Excalidraw/Template.excalidraw。",
|
||||
AUTOSAVE_NAME: "自动保存",
|
||||
AUTOSAVE_DESC: "每 30 秒自动保存编辑中的绘图。当您关闭 Excalidraw 或 Obsidian 或焦点移动到另一个面板时,通常会引发保存"+
|
||||
"在极少数情况下自动保存可能会稍微扰乱绘图流程。我在创建此功能时考虑到了手机端(安卓)," +
|
||||
"其中“滑到另一个应用程序”会导致一些数据丢失,并且因为我无法在手机上的应用程序" +
|
||||
" 终止时强制保存。如果您在桌面上使用 Excalidraw,这你可以关掉它。",
|
||||
FILENAME_HEAD: "文件名",
|
||||
FILENAME_DESC: "<p>自动生成的文件名包括一个前缀和一个日期。" +
|
||||
"例如 'Drawing 2021-05-24 12.58.07'。</p>"+
|
||||
"<p>点击<a href='https://momentjs.com/docs/#/displaying/format/'>"+
|
||||
"日期和时间格式参考</a>来查看如何修改。</p>",
|
||||
FILENAME_SAMPLE: "当前文件名的格式为:<b>",
|
||||
FILENAME_PREFIX_NAME: "文件名前缀",
|
||||
FILENAME_PREFIX_DESC: "文件名的第一部分",
|
||||
FILENAME_DATE_NAME: "文件名日期",
|
||||
FILENAME_DATE_DESC: "文件名的第二部分",
|
||||
LINKS_HEAD: "链接",
|
||||
LINKS_DESC: "CTRL/META 加左键点击文本元素来打开链接。" +
|
||||
"如果选中的文本指向多个双链,只会打开其中第一个。" +
|
||||
"如果选中的文本为超链接 (i.e. https:// or http://),然后" +
|
||||
"插件会在浏览器中打开超链接。" +
|
||||
"当对应的文件名修改时,匹配的链接也会修改。" +
|
||||
"如果你不希望你自己的链接文本突然修改,用别名来替代",
|
||||
LINK_BRACKETS_NAME: "在链接上显示双链符号[[",
|
||||
LINK_BRACKETS_DESC: "在预览(锁定)模式,当解析文本元素,在链接左右展示中括号。" +
|
||||
"你可以在文件的 Frontmatter 中加入'" + FRONTMATTER_KEY_CUSTOM_LINK_BRACKETS +
|
||||
": true/false' 来单独控制某个文件。",
|
||||
LINK_PREFIX_NAME:"链接前缀",
|
||||
LINK_PREFIX_DESC:"在预览(锁定)模式,如果文本元素包含链接,在文本之前加上这些字符。" +
|
||||
"你可以在文件的 Frontmatter 中加入 \'" + FRONTMATTER_KEY_CUSTOM_PREFIX +
|
||||
': "👉 "\' 单独更改',
|
||||
LINK_CTRL_CLICK_NAME: "CTRL 加左键点击文本来打开链接",
|
||||
LINK_CTRL_CLICK_DESC: "如果此功能干扰了您要使用的 Excalidraw 功能,您可以将其关闭。 如果" +
|
||||
"关闭此选项,则只有绘图标题栏中的链接按钮可以让你打开链接。",
|
||||
EMBED_HEAD: "嵌入 & 导出",
|
||||
EMBED_WIDTH_NAME: "嵌入图像的默认宽度",
|
||||
EMBED_WIDTH_DESC: "嵌入图形的默认宽度。您可以在使用" +
|
||||
"![[drawing.excalidraw|100]] 或 [[drawing.excalidraw|100x100]]" +
|
||||
"格式指定嵌入图像时的宽度。",
|
||||
EXPORT_PNG_SCALE_NAME: "PNG 导出图像比例",
|
||||
EXPORT_PNG_SCALE_DESC: "导出的 PNG 图像的大小比例",
|
||||
EXPORT_BACKGROUND_NAME: "导出带有背景的图像",
|
||||
EXPORT_BACKGROUND_DESC: "如果关闭,导出的图像的背景将是透明的。",
|
||||
EXPORT_THEME_NAME: "导出带有主题的图像",
|
||||
EXPORT_THEME_DESC: "导出与绘图的暗/亮主题匹配的图像。" +
|
||||
"如果关闭,在深色模式下导出的绘图将和浅色模式下导出的图像一样",
|
||||
EXPORT_HEAD: "导出设置",
|
||||
EXPORT_SYNC_NAME:"保持 .SVG 和/或 .PNG 文件名与绘图文件同步",
|
||||
EXPORT_SYNC_DESC:"打开后,当同一文件夹且同名的绘图被重命名时,插件将自动更新对应的 .SVG 和/或 .PNG 文件的文件名。" +
|
||||
"当同一文件夹的同一名称的绘图被删除时,该插件还将自动删除对应的 .SVG 和/或 .PNG 文件。",
|
||||
EXPORT_SVG_NAME: "自动导出 SVG",
|
||||
EXPORT_SVG_DESC: "自动导出和你文件同名的 SVG 文件" +
|
||||
"插件会将 SVG 文件保存到对应的 Excalidraw 所在的文件夹中"+
|
||||
"将 .svg 文件嵌入到文档中,而不是 excalidraw,使您嵌入的页面独立开来" +
|
||||
"当自动导出开关打开时,每次您编辑对应的 excalidraw 绘图时,此文件都会更新。",
|
||||
EXPORT_PNG_NAME: "自动导出 PNG",
|
||||
EXPORT_PNG_DESC: "和自动导出 SVG 一样,但面向 *.PNG",
|
||||
COMPATIBILITY_HEAD: "兼容特性",
|
||||
EXPORT_EXCALIDRAW_NAME: "自动导出 Excalidraw 文件",
|
||||
EXPORT_EXCALIDRAW_DESC: "和自动导出 SVG 一样,但面向 *.Excalidraw",
|
||||
SYNC_EXCALIDRAW_NAME: "同步 .md 格式以及 .excalidraw 格式",
|
||||
SYNC_EXCALIDRAW_DESC: "如果 *.excalidraw 文件的修改比 *.md 文件的修改更新" +
|
||||
",会根据 .excalidraw 文件更新 .md 文件中的绘图",
|
||||
COMPATIBILITY_MODE_NAME: "以旧格式创建新绘图",
|
||||
COMPATIBILITY_MODE_DESC: "通过启用此功能图形,您可以使用功能区图标、命令面板操作、 "+
|
||||
"并且文件浏览器将仍旧保留 *.excalidraw 文件。 此设置还将" +
|
||||
"关闭你打开旧格式绘图时的提醒消息",
|
||||
EXPERIMENTAL_HEAD: "实验性特性",
|
||||
EXPERIMENTAL_DESC: "这些设置不会立即生效,只有在刷新文件资源管理器或重新启动 Obsidian 时才会生效。",
|
||||
FILETYPE_NAME: "在文件浏览器中给所有的 Excalidraw 文件加上 ✏️ 标识符",
|
||||
FILETYPE_DESC: "Excalidraw 文件将使用下一个设置中定义的表情符号或文本来做标识。",
|
||||
FILETAG_NAME: "给 Excalidraw 文件设置标识符",
|
||||
FILETAG_DESC: "要显示为标识符的文本或表情符号。",
|
||||
|
||||
|
||||
|
||||
//openDrawings.ts
|
||||
SELECT_FILE: "选择一个文件后按回车。",
|
||||
NO_MATCH: "没有文件匹配你的索引。",
|
||||
SELECT_FILE_TO_LINK: "选择要为其插入链接的文件。",
|
||||
TYPE_FILENAME: "键入要选择的绘图名称。",
|
||||
SELECT_FILE_OR_TYPE_NEW: "选择现有绘图或新绘图的类型名称,然后按回车。",
|
||||
SELECT_TO_EMBED: "选择要插入到当前文档中的绘图。",
|
||||
};
|
||||
|
||||
367
src/main.ts
367
src/main.ts
@@ -15,9 +15,7 @@ import {
|
||||
MarkdownRenderer,
|
||||
ViewState,
|
||||
Notice,
|
||||
TFolder,
|
||||
} from "obsidian";
|
||||
|
||||
import {
|
||||
BLANK_DRAWING,
|
||||
VIEW_TYPE_EXCALIDRAW,
|
||||
@@ -32,13 +30,10 @@ import {
|
||||
RERENDER_EVENT,
|
||||
FRONTMATTER_KEY,
|
||||
FRONTMATTER,
|
||||
LOCK_ICON,
|
||||
LOCK_ICON_NAME,
|
||||
UNLOCK_ICON_NAME,
|
||||
UNLOCK_ICON,
|
||||
JSON_parse
|
||||
JSON_parse,
|
||||
nanoid
|
||||
} from "./constants";
|
||||
import ExcalidrawView, {ExportSettings} from "./ExcalidrawView";
|
||||
import ExcalidrawView, {ExportSettings, TextMode} from "./ExcalidrawView";
|
||||
import {getJSON} from "./ExcalidrawData";
|
||||
import {
|
||||
ExcalidrawSettings,
|
||||
@@ -49,26 +44,40 @@ import {
|
||||
openDialogAction,
|
||||
OpenFileDialog
|
||||
} from "./openDrawing";
|
||||
import {
|
||||
InsertLinkDialog
|
||||
} from "./InsertLinkDialog";
|
||||
import {
|
||||
initExcalidrawAutomate,
|
||||
destroyExcalidrawAutomate,
|
||||
exportSceneToMD,
|
||||
destroyExcalidrawAutomate
|
||||
} from "./ExcalidrawAutomate";
|
||||
import { Prompt } from "./Prompt";
|
||||
import { around } from "monkey-around";
|
||||
import { t } from "./lang/helpers";
|
||||
import { MigrationPrompt } from "./MigrationPrompt";
|
||||
import { download, getIMGPathFromExcalidrawFile, splitFolderAndFilename } from "./Utils";
|
||||
import { checkAndCreateFolder, download, getIMGPathFromExcalidrawFile, getNewUniqueFilepath, splitFolderAndFilename } from "./Utils";
|
||||
|
||||
declare module "obsidian" {
|
||||
interface App {
|
||||
isMobile():boolean;
|
||||
}
|
||||
interface Vault {
|
||||
getConfig(option:"attachmentFolderPath"): string;
|
||||
}
|
||||
interface Workspace {
|
||||
on(name: 'hover-link', callback: (e:MouseEvent) => any, ctx?: any): EventRef;
|
||||
}
|
||||
}
|
||||
|
||||
export default class ExcalidrawPlugin extends Plugin {
|
||||
public excalidrawFileModes: { [file: string]: string } = {};
|
||||
private _loaded: boolean = false;
|
||||
public settings: ExcalidrawSettings;
|
||||
//public stencilLibrary: any = null;
|
||||
private openDialog: OpenFileDialog;
|
||||
private insertLinkDialog: InsertLinkDialog;
|
||||
private activeExcalidrawView: ExcalidrawView = null;
|
||||
public lastActiveExcalidrawFilePath: string = null;
|
||||
private hover: {linkText: string, sourcePath: string} = {linkText: null, sourcePath: null};
|
||||
public hover: {linkText: string, sourcePath: string} = {linkText: null, sourcePath: null};
|
||||
private observer: MutationObserver;
|
||||
private fileExplorerObserver: MutationObserver;
|
||||
public opencount:number = 0;
|
||||
@@ -82,8 +91,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
addIcon(DISK_ICON_NAME,DISK_ICON);
|
||||
addIcon(PNG_ICON_NAME,PNG_ICON);
|
||||
addIcon(SVG_ICON_NAME,SVG_ICON);
|
||||
addIcon(LOCK_ICON_NAME,LOCK_ICON);
|
||||
addIcon(UNLOCK_ICON_NAME,UNLOCK_ICON);
|
||||
|
||||
await this.loadSettings();
|
||||
this.addSettingTab(new ExcalidrawSettingTab(this.app, this));
|
||||
@@ -106,14 +113,69 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
//https://github.com/mgmeyers/obsidian-kanban/blob/44118e25661bff9ebfe54f71ae33805dc88ffa53/src/main.ts#L267
|
||||
this.registerMonkeyPatches();
|
||||
if(this.settings.loadCount<1) this.migrationNotice();
|
||||
|
||||
const electron:string = process.versions.electron;
|
||||
if(electron.startsWith("8.")) {
|
||||
new Notice(`You are running an older version of the electron Browser (${electron}). If Excalidraw does not start up, please reinstall Obsidian with the latest installer and try again.`,10000);
|
||||
}
|
||||
this.switchToExcalidarwAfterLoad()
|
||||
|
||||
//This is a once off cleanup process to remediate incorrectly placed comment %% before # Text Elements
|
||||
if(this.settings.patchCommentBlock) {
|
||||
const self = this;
|
||||
console.log(window.moment().format("HH:mm:ss") + ": Excalidraw will patch drawings in 5 minutes");
|
||||
setTimeout(async ()=>{
|
||||
await self.loadSettings();
|
||||
if (!self.settings.patchCommentBlock) {
|
||||
console.log(window.moment().format("HH:mm:ss") + ": Excalidraw patching aborted because synched data.json is already patched");
|
||||
return;
|
||||
}
|
||||
console.log(window.moment().format("HH:mm:ss") + ": Excalidraw is starting the patching process");
|
||||
let i = 0;
|
||||
const excalidrawFiles = this.app.vault.getFiles();
|
||||
for (const f of (excalidrawFiles || []).filter((f:TFile) => self.isExcalidrawFile(f))) {
|
||||
if ( (f.extension !== "excalidraw") //legacy files do not need to be touched
|
||||
&& (self.app.workspace.getActiveFile() !== f)) { //file is currently being edited
|
||||
let drawing = await self.app.vault.read(f);
|
||||
const orig_drawing = drawing;
|
||||
drawing = drawing.replaceAll("\r\n","\n").replaceAll("\r","\n"); //Win, Mac, Linux compatibility
|
||||
drawing = drawing.replace("\n%%\n# Text Elements\n","\n# Text Elements\n");
|
||||
if (drawing.search("\n%%\n# Drawing\n") === -1) {
|
||||
const [json,pos] = getJSON(drawing);
|
||||
drawing = drawing.substr(0,pos)+"\n%%\n# Drawing\n```json\n"+json+"\n```%%";
|
||||
};
|
||||
if (drawing !== orig_drawing) {
|
||||
i++;
|
||||
console.log("Excalidraw patched: " + f.path);
|
||||
await self.app.vault.modify(f,drawing);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.settings.patchCommentBlock = false;
|
||||
self.saveSettings();
|
||||
console.log(window.moment().format("HH:mm:ss") + ": Excalidraw patched in total " + i + " files");
|
||||
},300000) //5 minutes
|
||||
}
|
||||
}
|
||||
|
||||
private switchToExcalidarwAfterLoad() {
|
||||
const self = this;
|
||||
this.app.workspace.onLayoutReady(() => {
|
||||
let leaf: WorkspaceLeaf;
|
||||
for (leaf of self.app.workspace.getLeavesOfType("markdown")) {
|
||||
if ((leaf.view instanceof MarkdownView) && self.isExcalidrawFile(leaf.view.file)) {
|
||||
self.excalidrawFileModes[(leaf as any).id || leaf.view.file.path] =
|
||||
VIEW_TYPE_EXCALIDRAW;
|
||||
self.setExcalidrawView(leaf);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private migrationNotice(){
|
||||
const self = this;
|
||||
this.app.workspace.onLayoutReady(async () => {
|
||||
self.settings.loadCount++;
|
||||
//self.saveSettings();
|
||||
self.saveSettings();
|
||||
const files = this.app.vault.getFiles().filter((f)=>f.extension=="excalidraw");
|
||||
if(files.length>0) {
|
||||
const prompt = new MigrationPrompt(self.app, self);
|
||||
@@ -121,12 +183,14 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a transcluded .excalidraw image in markdown preview mode
|
||||
*/
|
||||
private addMarkdownPostProcessor() {
|
||||
|
||||
interface imgElementAttributes {
|
||||
file?: TFile,
|
||||
fname: string, //Excalidraw filename
|
||||
fwidth: string, //Display width of image
|
||||
fheight: string, //Display height of image
|
||||
@@ -134,14 +198,18 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates an img element with the .excalidraw drawing encoded as a base64 svg
|
||||
* 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 encoded SVG image
|
||||
* @returns {Promise<HTMLElement>} - the IMG HTML element containing the image
|
||||
*/
|
||||
const getIMG = async (parts:imgElementAttributes):Promise<HTMLElement> => {
|
||||
const file = this.app.vault.getAbstractFileByPath(parts.fname);
|
||||
if(!(file && file instanceof TFile)) {
|
||||
return null;
|
||||
const getIMG = async (imgAttributes:imgElementAttributes):Promise<HTMLElement> => {
|
||||
let file = imgAttributes.file;
|
||||
if(!imgAttributes.file) {
|
||||
const f = this.app.vault.getAbstractFileByPath(imgAttributes.fname);
|
||||
if(!(f && f instanceof TFile)) {
|
||||
return null;
|
||||
}
|
||||
file = f;
|
||||
}
|
||||
|
||||
const content = await this.app.vault.read(file);
|
||||
@@ -149,16 +217,28 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
withBackground: this.settings.exportWithBackground,
|
||||
withTheme: this.settings.exportWithTheme
|
||||
}
|
||||
let svg = await ExcalidrawView.getSVG(JSON_parse(getJSON(content)),exportSettings);
|
||||
const img = createEl("img");
|
||||
img.setAttribute("width",imgAttributes.fwidth);
|
||||
if(imgAttributes.fheight) img.setAttribute("height",imgAttributes.fheight);
|
||||
img.addClass(imgAttributes.style);
|
||||
|
||||
|
||||
if(!this.settings.displaySVGInPreview) {
|
||||
const width = parseInt(imgAttributes.fwidth);
|
||||
let scale = 1;
|
||||
if(width>=800) scale = 2;
|
||||
if(width>=1600) scale = 3;
|
||||
if(width>=2400) scale = 4;
|
||||
const png = await ExcalidrawView.getPNG(JSON_parse(getJSON(content)[0]),exportSettings, scale);
|
||||
if(!png) return null;
|
||||
img.src = URL.createObjectURL(png);
|
||||
return img;
|
||||
}
|
||||
let svg = await ExcalidrawView.getSVG(JSON_parse(getJSON(content)[0]),exportSettings);
|
||||
if(!svg) return null;
|
||||
svg = ExcalidrawView.embedFontsInSVG(svg);
|
||||
const img = createEl("img");
|
||||
svg.removeAttribute('width');
|
||||
svg.removeAttribute('height');
|
||||
img.setAttribute("width",parts.fwidth);
|
||||
|
||||
if(parts.fheight) img.setAttribute("height",parts.fheight);
|
||||
img.addClass(parts.style);
|
||||
img.setAttribute("src","data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(svg.outerHTML.replaceAll(" "," ")))));
|
||||
return img;
|
||||
}
|
||||
@@ -169,12 +249,12 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
* @param ctx
|
||||
*/
|
||||
const markdownPostProcessor = async (el:HTMLElement,ctx:MarkdownPostProcessorContext) => {
|
||||
const drawings = el.querySelectorAll('.internal-embed');
|
||||
if(drawings.length==0) return;
|
||||
const embeddedItems = el.querySelectorAll('.internal-embed');
|
||||
if(embeddedItems.length==0) return;
|
||||
|
||||
let attr:imgElementAttributes={fname:"",fheight:"",fwidth:"",style:""};
|
||||
let alt:string, img:any, parts, div, file:TFile;
|
||||
for (const drawing of drawings) {
|
||||
let alt:string, parts, div, file:TFile;
|
||||
for (const drawing of embeddedItems) {
|
||||
attr.fname = drawing.getAttribute("src");
|
||||
file = this.app.metadataCache.getFirstLinkpathDest(attr.fname, ctx.sourcePath);
|
||||
if(file && file instanceof TFile && this.isExcalidrawFile(file)) {
|
||||
@@ -184,18 +264,19 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
if(alt == attr.fname) alt = ""; //when the filename starts with numbers followed by a space Obsidian recognizes the filename as alt-text
|
||||
attr.style = "excalidraw-svg";
|
||||
if(alt) {
|
||||
//for some reason ![]() is rendered in a DIV and ![[]] in a span by Obsidian
|
||||
//also the alt text of the DIV does not include the altext of the image
|
||||
//thus need to add an additional "|" character when its a span
|
||||
//for some reason Obsidian renders ![]() in a DIV and ![[]] in a SPAN
|
||||
//also the alt-text of the DIV does not include the alt-text of the image
|
||||
//thus need to add an additional "|" character when its a SPAN
|
||||
if(drawing.tagName.toLowerCase()=="span") alt = "|"+alt;
|
||||
parts = alt.match(/[^\|]*\|?(\d*)x?(\d*)\|?(.*)/);
|
||||
//1:width, 2:height, 3:style 1 2 3
|
||||
parts = alt.match(/[^\|]*\|?(\d*%?)x?(\d*%?)\|?(.*)/);
|
||||
attr.fwidth = parts[1]? parts[1] : this.settings.width;
|
||||
attr.fheight = parts[2];
|
||||
if(parts[3]!=attr.fname) attr.style = "excalidraw-svg" + (parts[3] ? "-" + parts[3] : "");
|
||||
}
|
||||
|
||||
|
||||
attr.fname = file?.path;
|
||||
img = await getIMG(attr);
|
||||
const img = await getIMG(attr);
|
||||
div = createDiv(attr.style, (el)=>{
|
||||
el.append(img);
|
||||
el.setAttribute("src",file.path);
|
||||
@@ -239,18 +320,17 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.hover.sourcePath = e.sourcePath;
|
||||
};
|
||||
this.registerEvent(
|
||||
//@ts-ignore
|
||||
this.app.workspace.on('hover-link',hoverEvent)
|
||||
);
|
||||
|
||||
//monitoring for div.popover.hover-popover.file-embed.is-loaded to be added to the DOM tree
|
||||
this.observer = new MutationObserver((m)=>{
|
||||
this.observer = new MutationObserver(async (m)=>{
|
||||
if(m.length == 0) return;
|
||||
if(!this.hover.linkText) return;
|
||||
const file = this.app.metadataCache.getFirstLinkpathDest(this.hover.linkText, this.hover.sourcePath?this.hover.sourcePath:"");
|
||||
if(!file || !(file instanceof TFile) || !this.isExcalidrawFile(file)) return
|
||||
|
||||
if((file as TFile).extension == "excalidraw") {
|
||||
if(file.extension == "excalidraw") {
|
||||
observerForLegacyFileFormat(m,file);
|
||||
return;
|
||||
}
|
||||
@@ -268,12 +348,14 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
if(m[i].addedNodes[0].firstElementChild?.firstElementChild?.className=="excalidraw-svg") return;
|
||||
|
||||
//@ts-ignore
|
||||
if(!m[i].addedNodes[0].matchParent(".hover-popover")) return;
|
||||
const hoverPopover = m[i].addedNodes[0].matchParent(".hover-popover");
|
||||
if(!hoverPopover) return;
|
||||
const node = m[i].addedNodes[0];
|
||||
|
||||
//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 div = createDiv("",async (el)=>{
|
||||
const img = await getIMG({fname:file.path,fwidth:"300",fheight:null,style:"excalidraw-svg"});
|
||||
const div = createDiv("", async (el)=>{
|
||||
const img = await getIMG({file:file,fname:file.path,fwidth:"300",fheight:null,style:"excalidraw-svg"});
|
||||
el.appendChild(img);
|
||||
el.setAttribute("src",file.path);
|
||||
el.onClickEvent((ev)=>{
|
||||
@@ -282,12 +364,11 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
if(src) this.openDrawing(this.app.vault.getAbstractFileByPath(src) as TFile,ev.ctrlKey||ev.metaKey);
|
||||
});
|
||||
});
|
||||
m[i].addedNodes[0].insertBefore(div,m[i].addedNodes[0].firstChild)
|
||||
|
||||
node.insertBefore(div,node.firstChild)
|
||||
});
|
||||
|
||||
//compatibility: .excalidraw file observer
|
||||
let observerForLegacyFileFormat = (m:MutationRecord[], file:TFile) => {
|
||||
let observerForLegacyFileFormat = async (m:MutationRecord[], file:TFile) => {
|
||||
if(!this.hover.linkText) return;
|
||||
if(m.length!=1) return;
|
||||
if(m[0].addedNodes.length != 1) return;
|
||||
@@ -298,8 +379,8 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
|
||||
//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:file,fname:file.path,fwidth:"300",fheight:null,style:"excalidraw-svg"});
|
||||
const div = createDiv("",async (el)=>{
|
||||
const img = await getIMG({fname:file.path,fwidth:"300",fheight:null,style:"excalidraw-svg"});
|
||||
el.appendChild(img);
|
||||
el.setAttribute("src",file.path);
|
||||
el.onClickEvent((ev)=>{
|
||||
@@ -325,35 +406,32 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.fileExplorerObserver = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Display characters configured in settings, in front of the filename, if the markdown file is an excalidraw drawing
|
||||
*/
|
||||
private experimentalFileTypeDisplay() {
|
||||
const insertFiletype = (el: HTMLElement) => {
|
||||
if(el.childElementCount != 1) return;
|
||||
//@ts-ignore
|
||||
if(this.isExcalidrawFile(this.app.vault.getAbstractFileByPath(el.attributes["data-path"].value))) {
|
||||
el.insertBefore(createDiv({cls:"nav-file-tag",text:this.settings.experimentalFileTag}),el.firstChild);
|
||||
}
|
||||
};
|
||||
|
||||
this.fileExplorerObserver = new MutationObserver((m)=>{
|
||||
|
||||
const mutationsWithNodes = m.filter((v)=>v.addedNodes.length > 0);
|
||||
mutationsWithNodes.forEach((mu)=>{
|
||||
mu.addedNodes.forEach((n)=>{
|
||||
if(!(n instanceof Element)) return;
|
||||
n.querySelectorAll(".nav-file-title").forEach((el)=>{
|
||||
if(el.childElementCount == 1) {
|
||||
//@ts-ignore
|
||||
if(this.isExcalidrawFile(this.app.vault.getAbstractFileByPath(el.attributes["data-path"].value))) {
|
||||
el.insertBefore(createDiv({cls:"nav-file-tag",text:this.settings.experimentalFileTag}),el.firstChild);
|
||||
}
|
||||
}
|
||||
});
|
||||
n.querySelectorAll(".nav-file-title").forEach(insertFiletype);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const self = this;
|
||||
this.app.workspace.onLayoutReady(()=>{
|
||||
document.querySelectorAll(".nav-file-title").forEach((el)=>{
|
||||
if(el.childElementCount == 1) {
|
||||
//@ts-ignore
|
||||
if(this.isExcalidrawFile(this.app.vault.getAbstractFileByPath(el.attributes["data-path"].value))) {
|
||||
el.insertBefore(createDiv({cls:"nav-file-tag",text:this.settings.experimentalFileTag}),el.firstChild);
|
||||
}
|
||||
}
|
||||
});
|
||||
document.querySelectorAll(".nav-file-title").forEach(insertFiletype); //apply filetype to files already displayed
|
||||
this.fileExplorerObserver.observe(document.querySelector(".workspace"), {childList: true, subtree: true});
|
||||
});
|
||||
|
||||
@@ -361,6 +439,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
|
||||
private registerCommands() {
|
||||
this.openDialog = new OpenFileDialog(this.app, this);
|
||||
this.insertLinkDialog = new InsertLinkDialog(this.app);
|
||||
|
||||
this.addRibbonIcon(ICON_NAME, t("CREATE_NEW"), async (e) => {
|
||||
this.createDrawing(this.getNextDefaultFilename(), e.ctrlKey||e.metaKey);
|
||||
@@ -417,7 +496,20 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.addCommand({
|
||||
id: "excalidraw-download-lib",
|
||||
name: t("DOWNLOAD_LIBRARY"),
|
||||
callback: () => {
|
||||
callback: async () => {
|
||||
if(this.app.isMobile) {
|
||||
const prompt = new Prompt(this.app, "Please provide a filename",'my-library','filename, leave blank to cancel action');
|
||||
prompt.openAndGetValue( async (filename:string)=> {
|
||||
if(!filename) return;
|
||||
filename = filename + ".excalidrawlib";
|
||||
const folderpath = normalizePath(this.settings.folder);
|
||||
await checkAndCreateFolder(this.app.vault,folderpath); //create folder if it does not exist
|
||||
const fname = getNewUniqueFilepath(this.app.vault,filename,folderpath);
|
||||
this.app.vault.create(fname,this.settings.library);
|
||||
new Notice("Exported library to " + fname,6000);
|
||||
});
|
||||
return;
|
||||
}
|
||||
download('data:text/plain;charset=utf-8',encodeURIComponent(this.settings.library), 'my-obsidian-library.excalidrawlib');
|
||||
},
|
||||
});
|
||||
@@ -480,6 +572,26 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
},
|
||||
});
|
||||
|
||||
const insertDrawingToDoc = async (inNewPane:boolean) => {
|
||||
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
|
||||
if(!activeView) return;
|
||||
let folder = this.app.vault.getConfig("attachmentFolderPath");
|
||||
// folder == null: save to vault root
|
||||
// folder == "./" save to same folder as current file
|
||||
// folder == "folder" save to specific folder in vault
|
||||
// folder == "./folder" save to specific subfolder of current active folder
|
||||
if(folder && folder.startsWith("./")) { // folder relative to current file
|
||||
const activeFileFolder = splitFolderAndFilename(activeView.file.path).folderpath + "/";
|
||||
folder = normalizePath(activeFileFolder + folder.substring(2));
|
||||
}
|
||||
if(!folder) folder = "";
|
||||
await checkAndCreateFolder(this.app.vault,folder);
|
||||
const filename = activeView.file.basename + "_" + window.moment().format(this.settings.drawingFilenameDateTime)
|
||||
+ (this.settings.compatibilityMode ? '.excalidraw' : '.excalidraw.md');
|
||||
this.embedDrawing(normalizePath(folder + "/" + filename));
|
||||
this.createDrawing(filename, inNewPane,folder==""?null:folder);
|
||||
}
|
||||
|
||||
this.addCommand({
|
||||
id: "excalidraw-autocreate-and-embed",
|
||||
name: t("NEW_IN_NEW_PANE_EMBED"),
|
||||
@@ -487,9 +599,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
if (checking) {
|
||||
return (this.app.workspace.activeLeaf.view.getViewType() == "markdown");
|
||||
} else {
|
||||
const filename = this.getNextDefaultFilename();
|
||||
this.embedDrawing(filename);
|
||||
this.createDrawing(filename, true);
|
||||
insertDrawingToDoc(true);
|
||||
return true;
|
||||
}
|
||||
},
|
||||
@@ -502,9 +612,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
if (checking) {
|
||||
return (this.app.workspace.activeLeaf.view.getViewType() == "markdown");
|
||||
} else {
|
||||
const filename = this.getNextDefaultFilename();
|
||||
this.embedDrawing(filename);
|
||||
this.createDrawing(filename, false);
|
||||
insertDrawingToDoc(false);
|
||||
return true;
|
||||
}
|
||||
},
|
||||
@@ -557,7 +665,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
} else {
|
||||
const view = this.app.workspace.activeLeaf.view;
|
||||
if (view instanceof ExcalidrawView) {
|
||||
view.lock(!view.isTextLocked);
|
||||
view.changeTextMode((view.textMode==TextMode.parsed)?TextMode.raw:TextMode.parsed);
|
||||
return true;
|
||||
}
|
||||
else return false;
|
||||
@@ -576,7 +684,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
} else {
|
||||
const view = this.app.workspace.activeLeaf.view;
|
||||
if (view instanceof ExcalidrawView) {
|
||||
this.openDialog.insertLink(view.file.path,view.addText);
|
||||
this.insertLinkDialog.start(view.file.path,view.addText);
|
||||
return true;
|
||||
}
|
||||
else return false;
|
||||
@@ -593,7 +701,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
} else {
|
||||
const view = this.app.workspace.activeLeaf.view;
|
||||
if (view instanceof ExcalidrawView) {
|
||||
const prompt = new Prompt(this.app, t("ENTER_LATEX"),'');
|
||||
const prompt = new Prompt(this.app, t("ENTER_LATEX"),'','$\\theta$');
|
||||
prompt.openAndGetValue( async (formula:string)=> {
|
||||
if(!formula) return;
|
||||
const el = createEl('p');
|
||||
@@ -675,9 +783,9 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
public async convertSingleExcalidrawToMD(file: TFile, replaceExtension:boolean = false, keepOriginal:boolean = false):Promise<TFile> {
|
||||
const data = await this.app.vault.read(file);
|
||||
const filename = file.name.substr(0,file.name.lastIndexOf(".excalidraw")) + (replaceExtension ? ".md" : ".excalidraw.md");
|
||||
const fname = this.getNewUniqueFilepath(filename,normalizePath(file.path.substr(0,file.path.lastIndexOf(file.name))));
|
||||
const fname = getNewUniqueFilepath(this.app.vault,filename,normalizePath(file.path.substr(0,file.path.lastIndexOf(file.name))));
|
||||
console.log(fname);
|
||||
const result = await this.app.vault.create(fname,FRONTMATTER + exportSceneToMD(data));
|
||||
const result = await this.app.vault.create(fname,FRONTMATTER + this.exportSceneToMD(data));
|
||||
if (this.settings.keepInSync) {
|
||||
['.svg','.png'].forEach( (ext:string)=>{
|
||||
const oldIMGpath = file.path.substring(0,file.path.lastIndexOf(".excalidraw")) + ext;
|
||||
@@ -835,7 +943,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
const deleteEventHandler = async (file:TFile) => {
|
||||
if (!(file instanceof TFile)) return;
|
||||
//@ts-ignore
|
||||
const isExcalidarwFile = (file.unsafeCachedData && file.unsafeCachedData.search(/---\n[\s\S]*excalidraw-plugin:\s*(locked|unlocked)\n[\s\S]*---/gm)>-1)
|
||||
const isExcalidarwFile = (file.unsafeCachedData && file.unsafeCachedData.search(/---[\r\n]+[\s\S]*excalidraw-plugin:\s*\w+[\r\n]+[\s\S]*---/gm)>-1)
|
||||
|| (file.extension=="excalidraw");
|
||||
if(!isExcalidarwFile) return;
|
||||
|
||||
@@ -863,14 +971,11 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
);
|
||||
|
||||
//save open drawings when user quits the application
|
||||
const quitEventHandler = (tasks: Tasks) => {
|
||||
const quitEventHandler = async (tasks: Tasks) => {
|
||||
const leaves = self.app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW);
|
||||
for (let i=0;i<leaves.length;i++) {
|
||||
(leaves[i].view as ExcalidrawView).save();
|
||||
await (leaves[i].view as ExcalidrawView).save(true);
|
||||
}
|
||||
this.settings.drawingOpenCount += this.opencount;
|
||||
this.settings.loadCount++;
|
||||
this.saveSettings();
|
||||
}
|
||||
self.registerEvent(
|
||||
self.app.workspace.on("quit",quitEventHandler)
|
||||
@@ -907,14 +1012,25 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
});
|
||||
this.settings.drawingOpenCount += this.opencount;
|
||||
this.settings.loadCount++;
|
||||
this.saveSettings();
|
||||
//this.saveSettings();
|
||||
}
|
||||
|
||||
public embedDrawing(data:string) {
|
||||
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
|
||||
if(activeView) {
|
||||
const editor = activeView.editor;
|
||||
editor.replaceSelection("![["+data+"]]");
|
||||
switch (this.settings.embedType) {
|
||||
case "excalidraw":
|
||||
editor.replaceSelection("![["+data+"]]");
|
||||
break;
|
||||
case "PNG":
|
||||
editor.replaceSelection("![["+data.substr(0,data.lastIndexOf("."))+".png]] ([["+data+"|*]])");
|
||||
break;
|
||||
case "SVG":
|
||||
editor.replaceSelection("![["+data.substr(0,data.lastIndexOf("."))+".svg]] ([["+data+"|*]])");
|
||||
break;
|
||||
}
|
||||
|
||||
editor.focus();
|
||||
}
|
||||
|
||||
@@ -933,7 +1049,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
}
|
||||
|
||||
public setStencilLibrary(library:string) {
|
||||
this.settings.library = library;
|
||||
this.settings.library = library;
|
||||
}
|
||||
|
||||
public triggerEmbedUpdates(filepath?:string){
|
||||
@@ -987,24 +1103,54 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
if (this.settings.compatibilityMode) {
|
||||
return BLANK_DRAWING;
|
||||
}
|
||||
return FRONTMATTER + '\n# Drawing\n'
|
||||
+ String.fromCharCode(96)+String.fromCharCode(96)+String.fromCharCode(96)+'json\n'
|
||||
+ BLANK_DRAWING + '\n'
|
||||
+ String.fromCharCode(96)+String.fromCharCode(96)+String.fromCharCode(96);
|
||||
return FRONTMATTER + '\n' + this.getMarkdownDrawingSection(BLANK_DRAWING);
|
||||
}
|
||||
|
||||
public async createDrawing(filename: string, onNewPane: boolean, foldername?: string, initData?:string) {
|
||||
const folderpath = normalizePath(foldername ? foldername: this.settings.folder);
|
||||
await this.checkAndCreateFolder(folderpath); //create folder if it does not exist
|
||||
public getMarkdownDrawingSection(jsonString: string) {
|
||||
return '%%\n# Drawing\n'
|
||||
+ String.fromCharCode(96)+String.fromCharCode(96)+String.fromCharCode(96)+'json\n'
|
||||
+ jsonString + '\n'
|
||||
+ String.fromCharCode(96)+String.fromCharCode(96)+String.fromCharCode(96) + '%%';
|
||||
}
|
||||
|
||||
const fname = this.getNewUniqueFilepath(filename,folderpath);
|
||||
/**
|
||||
* Extracts the text elements from an Excalidraw scene into a string of ids as headers followed by the text contents
|
||||
* @param {string} data - Excalidraw scene JSON string
|
||||
* @returns {string} - Text starting with the "# Text Elements" header and followed by each "## id-value" and text
|
||||
*/
|
||||
public exportSceneToMD(data:string): string {
|
||||
if(!data) return "";
|
||||
const excalidrawData = JSON_parse(data);
|
||||
const textElements = excalidrawData.elements?.filter((el:any)=> el.type=="text")
|
||||
let outString = '# Text Elements\n';
|
||||
let id:string;
|
||||
for (const te of textElements) {
|
||||
id = te.id;
|
||||
//replacing Excalidraw text IDs with my own, because default IDs may contain
|
||||
//characters not recognized by Obsidian block references
|
||||
//also Excalidraw IDs are inconveniently long
|
||||
if(te.id.length>8) {
|
||||
id=nanoid();
|
||||
data = data.replaceAll(te.id,id); //brute force approach to replace all occurances.
|
||||
}
|
||||
outString += te.text+' ^'+id+'\n\n';
|
||||
}
|
||||
return outString + this.getMarkdownDrawingSection(JSON.stringify(JSON_parse(data)));
|
||||
}
|
||||
|
||||
public async createDrawing(filename: string, onNewPane: boolean, foldername?: string, initData?:string):Promise<string> {
|
||||
const folderpath = normalizePath(foldername ? foldername: this.settings.folder);
|
||||
await checkAndCreateFolder(this.app.vault,folderpath); //create folder if it does not exist
|
||||
|
||||
const fname = getNewUniqueFilepath(this.app.vault,filename,folderpath);
|
||||
|
||||
if(initData) {
|
||||
this.openDrawing(await this.app.vault.create(fname,initData),onNewPane);
|
||||
return;
|
||||
return fname;
|
||||
}
|
||||
|
||||
this.openDrawing(await this.app.vault.create(fname,await this.getBlankDrawing()), onNewPane);
|
||||
return fname;
|
||||
}
|
||||
|
||||
public async setMarkdownView(leaf: WorkspaceLeaf) {
|
||||
@@ -1026,37 +1172,10 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
} as ViewState);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create new file, if file already exists find first unique filename by adding a number to the end of the filename
|
||||
* @param filename
|
||||
* @param folderpath
|
||||
* @returns
|
||||
*/
|
||||
getNewUniqueFilepath(filename:string, folderpath:string):string {
|
||||
let fname = normalizePath(folderpath +'/'+ filename);
|
||||
let file:TAbstractFile = this.app.vault.getAbstractFileByPath(fname);
|
||||
let i = 0;
|
||||
while(file) {
|
||||
fname = normalizePath(folderpath + '/' + filename.slice(0,filename.lastIndexOf("."))+"_"+i+filename.slice(filename.lastIndexOf(".")));
|
||||
i++;
|
||||
file = this.app.vault.getAbstractFileByPath(fname);
|
||||
}
|
||||
return fname;
|
||||
}
|
||||
|
||||
isExcalidrawFile(f:TFile) {
|
||||
public isExcalidrawFile(f:TFile) {
|
||||
if(f.extension=="excalidraw") return true;
|
||||
const fileCache = this.app.metadataCache.getFileCache(f);
|
||||
return !!fileCache?.frontmatter && !!fileCache.frontmatter[FRONTMATTER_KEY];
|
||||
}
|
||||
|
||||
/**
|
||||
* Open or create a folderpath if it does not exist
|
||||
* @param folderpath
|
||||
*/
|
||||
public async checkAndCreateFolder(folderpath:string) {
|
||||
let folder = this.app.vault.getAbstractFileByPath(folderpath);
|
||||
if(folder && folder instanceof TFolder) return;
|
||||
await this.app.vault.createFolder(folderpath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ import {t} from './lang/helpers'
|
||||
export enum openDialogAction {
|
||||
openFile,
|
||||
insertLinkToDrawing,
|
||||
insertLink
|
||||
}
|
||||
|
||||
export class OpenFileDialog extends FuzzySuggestModal<TFile> {
|
||||
@@ -20,8 +19,6 @@ export class OpenFileDialog extends FuzzySuggestModal<TFile> {
|
||||
private plugin: ExcalidrawPlugin;
|
||||
private action: openDialogAction;
|
||||
private onNewPane: boolean;
|
||||
private addText: Function;
|
||||
private drawingPath: string;
|
||||
|
||||
constructor(app: App, plugin: ExcalidrawPlugin) {
|
||||
super(app);
|
||||
@@ -29,6 +26,11 @@ export class OpenFileDialog extends FuzzySuggestModal<TFile> {
|
||||
this.action = openDialogAction.openFile;
|
||||
this.plugin = plugin;
|
||||
this.onNewPane = false;
|
||||
this.limit = 20;
|
||||
this.setInstructions([{
|
||||
command: t("TYPE_FILENAME"),
|
||||
purpose: "",
|
||||
}]);
|
||||
|
||||
this.inputEl.onkeyup = (e) => {
|
||||
if(e.key=="Enter" && this.action == openDialogAction.openFile) {
|
||||
@@ -42,10 +44,7 @@ export class OpenFileDialog extends FuzzySuggestModal<TFile> {
|
||||
|
||||
getItems(): TFile[] {
|
||||
const excalidrawFiles = this.app.vault.getFiles();
|
||||
return (excalidrawFiles || []).filter((f:TFile) => {
|
||||
if (this.action == openDialogAction.insertLink) return true;
|
||||
return this.plugin.isExcalidrawFile(f);
|
||||
});
|
||||
return (excalidrawFiles || []).filter((f:TFile) => this.plugin.isExcalidrawFile(f));
|
||||
}
|
||||
|
||||
getItemText(item: TFile): string {
|
||||
@@ -60,32 +59,10 @@ export class OpenFileDialog extends FuzzySuggestModal<TFile> {
|
||||
case(openDialogAction.insertLinkToDrawing):
|
||||
this.plugin.embedDrawing(item.path);
|
||||
break;
|
||||
case(openDialogAction.insertLink):
|
||||
//TO-DO
|
||||
const filepath = this.app.metadataCache.fileToLinktext(item,this.drawingPath,true);
|
||||
this.addText("[["+filepath+"]]");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public insertLink(drawingPath:string, addText: Function) {
|
||||
this.action = openDialogAction.insertLink;
|
||||
this.addText = addText;
|
||||
this.drawingPath = drawingPath;
|
||||
this.setInstructions([{
|
||||
command: t("SELECT_FILE"),
|
||||
purpose: "",
|
||||
}]);
|
||||
this.emptyStateText = t("NO_MATCH");
|
||||
this.setPlaceholder(t("SELECT_FILE_TO_LINK"));
|
||||
this.open();
|
||||
}
|
||||
|
||||
public start(action:openDialogAction, onNewPane: boolean): void {
|
||||
this.setInstructions([{
|
||||
command: t("TYPE_FILENAME"),
|
||||
purpose: "",
|
||||
}]);
|
||||
this.action = action;
|
||||
this.onNewPane = onNewPane;
|
||||
switch(action) {
|
||||
|
||||
295
src/settings.ts
295
src/settings.ts
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
App,
|
||||
DropdownComponent,
|
||||
PluginSettingTab,
|
||||
Setting,
|
||||
TFile
|
||||
@@ -8,24 +9,29 @@ import { VIEW_TYPE_EXCALIDRAW } from './constants';
|
||||
import ExcalidrawView from './ExcalidrawView';
|
||||
import { t } from './lang/helpers';
|
||||
import type ExcalidrawPlugin from "./main";
|
||||
import { splitFolderAndFilename } from './Utils';
|
||||
|
||||
export interface ExcalidrawSettings {
|
||||
folder: string,
|
||||
templateFilePath: string,
|
||||
drawingFilenamePrefix: string,
|
||||
drawingFilenameDateTime: string,
|
||||
displaySVGInPreview: boolean,
|
||||
width: string,
|
||||
zoomToFitOnResize: boolean,
|
||||
showLinkBrackets: boolean,
|
||||
linkPrefix: string,
|
||||
//autosave: boolean;
|
||||
urlPrefix: string,
|
||||
allowCtrlClick: boolean, //if disabled only the link button in the view header will open links
|
||||
forceWrap: boolean,
|
||||
pageTransclusionCharLimit: number,
|
||||
pngExportScale: number,
|
||||
exportWithTheme: boolean,
|
||||
exportWithBackground: boolean,
|
||||
keepInSync: boolean,
|
||||
autoexportSVG: boolean,
|
||||
autoexportPNG: boolean,
|
||||
autoexportExcalidraw: boolean,
|
||||
embedType: "excalidraw"|"PNG"|"SVG",
|
||||
syncExcalidraw: boolean,
|
||||
compatibilityMode: boolean,
|
||||
experimentalFileType: boolean,
|
||||
@@ -33,6 +39,7 @@ export interface ExcalidrawSettings {
|
||||
loadCount: number, //version 1.2 migration counter
|
||||
drawingOpenCount: number,
|
||||
library: string,
|
||||
patchCommentBlock: boolean, //1.3.12
|
||||
}
|
||||
|
||||
export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
@@ -40,17 +47,23 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
templateFilePath: 'Excalidraw/Template.excalidraw',
|
||||
drawingFilenamePrefix: 'Drawing ',
|
||||
drawingFilenameDateTime: 'YYYY-MM-DD HH.mm.ss',
|
||||
displaySVGInPreview: true,
|
||||
width: '400',
|
||||
linkPrefix: "🔸",
|
||||
zoomToFitOnResize: true,
|
||||
linkPrefix: "📍",
|
||||
urlPrefix: "🌐",
|
||||
showLinkBrackets: true,
|
||||
//autosave: false,
|
||||
allowCtrlClick: true,
|
||||
forceWrap: false,
|
||||
pageTransclusionCharLimit: 200,
|
||||
pngExportScale: 1,
|
||||
exportWithTheme: true,
|
||||
exportWithBackground: true,
|
||||
keepInSync: false,
|
||||
autoexportSVG: false,
|
||||
autoexportPNG: false,
|
||||
autoexportExcalidraw: false,
|
||||
embedType: "excalidraw",
|
||||
syncExcalidraw: false,
|
||||
experimentalFileType: false,
|
||||
experimentalFileTag: "✏️",
|
||||
@@ -58,20 +71,60 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
loadCount: 0,
|
||||
drawingOpenCount: 0,
|
||||
library: `{"type":"excalidrawlib","version":1,"library":[]}`,
|
||||
patchCommentBlock: true,
|
||||
}
|
||||
|
||||
export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
plugin: ExcalidrawPlugin;
|
||||
private requestEmbedUpdate:boolean = false;
|
||||
private requestReloadDrawings:boolean = false;
|
||||
private applyDebounceTimer: number = 0;
|
||||
|
||||
constructor(app: App, plugin: ExcalidrawPlugin) {
|
||||
super(app, plugin);
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
applySettingsUpdate(requestReloadDrawings:boolean = false) {
|
||||
clearTimeout(this.applyDebounceTimer);
|
||||
const plugin = this.plugin;
|
||||
this.applyDebounceTimer = window.setTimeout(() => {
|
||||
plugin.saveSettings();
|
||||
}, 200);
|
||||
if(requestReloadDrawings) this.requestReloadDrawings = true;
|
||||
}
|
||||
|
||||
async hide() {
|
||||
if(this.requestReloadDrawings) {
|
||||
const exs = this.plugin.app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW);
|
||||
for(const v of exs) {
|
||||
if(v.view instanceof ExcalidrawView) {
|
||||
await v.view.save(false);
|
||||
await v.view.reload(true);
|
||||
}
|
||||
}
|
||||
this.requestEmbedUpdate = true;
|
||||
}
|
||||
if(this.requestEmbedUpdate) this.plugin.triggerEmbedUpdates();
|
||||
}
|
||||
|
||||
display(): void {
|
||||
this.requestEmbedUpdate = false;
|
||||
this.requestReloadDrawings = false;
|
||||
let {containerEl} = this;
|
||||
this.containerEl.empty();
|
||||
|
||||
const coffeeDiv = containerEl.createDiv('coffee');
|
||||
coffeeDiv.addClass('ex-coffee-div');
|
||||
const coffeeLink = coffeeDiv.createEl('a', { href: 'https://ko-fi.com/zsolt' });
|
||||
const coffeeImg = coffeeLink.createEl('img', {
|
||||
attr: {
|
||||
src: 'https://cdn.ko-fi.com/cdn/kofi3.png?v=3',
|
||||
},
|
||||
});
|
||||
coffeeImg.height = 45;
|
||||
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(t("FOLDER_NAME"))
|
||||
.setDesc(t("FOLDER_DESC"))
|
||||
@@ -80,7 +133,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.folder)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.folder = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.applySettingsUpdate();
|
||||
}));
|
||||
|
||||
new Setting(containerEl)
|
||||
@@ -91,31 +144,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.templateFilePath)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.templateFilePath = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.applySettingsUpdate();
|
||||
}));
|
||||
|
||||
/* new Setting(containerEl)
|
||||
.setName(t("AUTOSAVE_NAME"))
|
||||
.setDesc(t("AUTOSAVE_DESC"))
|
||||
.addToggle(toggle => toggle
|
||||
.setValue(this.plugin.settings.autosave)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.autosave = value;
|
||||
await this.plugin.saveSettings();
|
||||
const exs = this.plugin.app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW);
|
||||
for(const v of exs) {
|
||||
if(v.view instanceof ExcalidrawView) {
|
||||
if(v.view.autosaveTimer) {
|
||||
clearInterval(v.view.autosaveTimer)
|
||||
v.view.autosaveTimer = null;
|
||||
}
|
||||
if(value) {
|
||||
v.view.setupAutosaveTimer();
|
||||
}
|
||||
}
|
||||
}
|
||||
}));*/
|
||||
|
||||
this.containerEl.createEl('h1', {text: t("FILENAME_HEAD")});
|
||||
containerEl.createDiv('',(el) => {
|
||||
el.innerHTML = t("FILENAME_DESC");
|
||||
@@ -141,7 +172,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
this.plugin.settings.drawingFilenamePrefix = value.replaceAll(/[<>:"/\\|?*]/g,'_');
|
||||
text.setValue(this.plugin.settings.drawingFilenamePrefix);
|
||||
filenameEl.innerHTML = getFilenameSample();
|
||||
await this.plugin.saveSettings();
|
||||
this.applySettingsUpdate();
|
||||
}));
|
||||
|
||||
new Setting(containerEl)
|
||||
@@ -154,23 +185,23 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
this.plugin.settings.drawingFilenameDateTime = value.replaceAll(/[<>:"/\\|?*]/g,'_');
|
||||
text.setValue(this.plugin.settings.drawingFilenameDateTime);
|
||||
filenameEl.innerHTML = getFilenameSample();
|
||||
await this.plugin.saveSettings();
|
||||
this.applySettingsUpdate();
|
||||
}));
|
||||
|
||||
this.containerEl.createEl('h1', {text: t("DISPLAY_HEAD")});
|
||||
new Setting(containerEl)
|
||||
.setName(t("ZOOM_TO_FIT_NAME"))
|
||||
.setDesc(t("ZOOM_TO_FIT_DESC"))
|
||||
.addToggle(toggle => toggle
|
||||
.setValue(this.plugin.settings.zoomToFitOnResize)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.zoomToFitOnResize = value;
|
||||
this.applySettingsUpdate();
|
||||
}));
|
||||
|
||||
this.containerEl.createEl('h1', {text: t("LINKS_HEAD")});
|
||||
this.containerEl.createEl('p',{
|
||||
text: t("LINKS_DESC")});
|
||||
|
||||
const reloadDrawings = async () => {
|
||||
const exs = this.plugin.app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW);
|
||||
for(const v of exs) {
|
||||
if(v.view instanceof ExcalidrawView) {
|
||||
await v.view.save(false);
|
||||
v.view.reload(true);
|
||||
}
|
||||
}
|
||||
this.plugin.triggerEmbedUpdates();
|
||||
}
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(t("LINK_BRACKETS_NAME"))
|
||||
@@ -179,20 +210,30 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.showLinkBrackets)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.showLinkBrackets = value;
|
||||
await this.plugin.saveSettings();
|
||||
reloadDrawings();
|
||||
this.applySettingsUpdate(true);
|
||||
}));
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(t("LINK_PREFIX_NAME"))
|
||||
.setDesc(t("LINK_PREFIX_DESC"))
|
||||
.addText(text => text
|
||||
.setPlaceholder('🔸')
|
||||
.setPlaceholder(t("INSERT_EMOJI"))
|
||||
.setValue(this.plugin.settings.linkPrefix)
|
||||
.onChange(async (value) => {
|
||||
.onChange((value) => {
|
||||
console.log(value);
|
||||
this.plugin.settings.linkPrefix = value;
|
||||
await this.plugin.saveSettings();
|
||||
reloadDrawings();
|
||||
this.applySettingsUpdate(true);
|
||||
}));
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(t("URL_PREFIX_NAME"))
|
||||
.setDesc(t("URL_PREFIX_DESC"))
|
||||
.addText(text => text
|
||||
.setPlaceholder(t("INSERT_EMOJI"))
|
||||
.setValue(this.plugin.settings.urlPrefix)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.urlPrefix = value;
|
||||
this.applySettingsUpdate(true);
|
||||
}));
|
||||
|
||||
new Setting(containerEl)
|
||||
@@ -202,11 +243,57 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.allowCtrlClick)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.allowCtrlClick = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.applySettingsUpdate();
|
||||
}));
|
||||
|
||||
const s = new Setting(containerEl)
|
||||
.setName(t("TRANSCLUSION_WRAP_NAME"))
|
||||
.setDesc(t("TRANSCLUSION_WRAP_DESC"))
|
||||
.addToggle(toggle => toggle
|
||||
.setValue(this.plugin.settings.forceWrap)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.forceWrap = value;
|
||||
this.applySettingsUpdate(true);
|
||||
}));
|
||||
s.descEl.innerHTML="<code>![[doc#^ref]]{number}</code> "+t("TRANSCLUSION_WRAP_DESC");
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(t("PAGE_TRANSCLUSION_CHARCOUNT_NAME"))
|
||||
.setDesc(t("PAGE_TRANSCLUSION_CHARCOUNT_DESC"))
|
||||
.addText(text => text
|
||||
.setPlaceholder('Enter a number')
|
||||
.setValue(this.plugin.settings.pageTransclusionCharLimit.toString())
|
||||
.onChange(async (value) => {
|
||||
const intVal = parseInt(value);
|
||||
if(isNaN(intVal) && value!=="") {
|
||||
text.setValue(this.plugin.settings.pageTransclusionCharLimit.toString());
|
||||
return;
|
||||
}
|
||||
this.requestEmbedUpdate = true;
|
||||
if(value === "") {
|
||||
this.plugin.settings.pageTransclusionCharLimit = 10;
|
||||
this.applySettingsUpdate(true);
|
||||
return;
|
||||
}
|
||||
this.plugin.settings.pageTransclusionCharLimit = intVal;
|
||||
text.setValue(this.plugin.settings.pageTransclusionCharLimit.toString());
|
||||
this.applySettingsUpdate(true);
|
||||
}));
|
||||
|
||||
this.containerEl.createEl('h1', {text: t("EMBED_HEAD")});
|
||||
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(t("EMBED_PREVIEW_SVG_NAME"))
|
||||
.setDesc(t("EMBED_PREVIEW_SVG_DESC"))
|
||||
.addToggle(toggle => toggle
|
||||
.setValue(this.plugin.settings.displaySVGInPreview)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.displaySVGInPreview = value;
|
||||
this.applySettingsUpdate();
|
||||
}));
|
||||
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(t("EMBED_WIDTH_NAME"))
|
||||
.setDesc(t("EMBED_WIDTH_DESC"))
|
||||
@@ -215,9 +302,62 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.width)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.width = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.plugin.triggerEmbedUpdates();
|
||||
}));
|
||||
this.applySettingsUpdate();
|
||||
this.requestEmbedUpdate = true;
|
||||
}));
|
||||
|
||||
let dropdown: DropdownComponent;
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(t("EMBED_TYPE_NAME"))
|
||||
.setDesc(t("EMBED_TYPE_DESC"))
|
||||
.addDropdown(async (d:DropdownComponent) => {
|
||||
dropdown = d;
|
||||
dropdown.addOption("excalidraw","excalidraw")
|
||||
if(this.plugin.settings.autoexportPNG) {
|
||||
dropdown.addOption("PNG","PNG");
|
||||
} else {
|
||||
if(this.plugin.settings.embedType === "PNG") {
|
||||
this.plugin.settings.embedType = "excalidraw";
|
||||
this.applySettingsUpdate();
|
||||
}
|
||||
}
|
||||
if(this.plugin.settings.autoexportSVG) {
|
||||
dropdown.addOption("SVG","SVG");
|
||||
} else {
|
||||
if(this.plugin.settings.embedType === "SVG") {
|
||||
this.plugin.settings.embedType = "excalidraw";
|
||||
this.applySettingsUpdate();
|
||||
}
|
||||
}
|
||||
dropdown
|
||||
.setValue(this.plugin.settings.embedType)
|
||||
.onChange(async (value)=>{
|
||||
//@ts-ignore
|
||||
this.plugin.settings.embedType = value;
|
||||
this.applySettingsUpdate();
|
||||
});
|
||||
});
|
||||
|
||||
let scaleText:HTMLDivElement;
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(t("EXPORT_PNG_SCALE_NAME"))
|
||||
.setDesc(t("EXPORT_PNG_SCALE_DESC"))
|
||||
.addSlider(slider => slider
|
||||
.setLimits(1,5,0.5)
|
||||
.setValue(this.plugin.settings.pngExportScale)
|
||||
.onChange(async (value)=> {
|
||||
scaleText.innerText = " " + value.toString();
|
||||
this.plugin.settings.pngExportScale = value;
|
||||
this.applySettingsUpdate();
|
||||
}))
|
||||
.settingEl.createDiv('',(el)=>{
|
||||
scaleText = el;
|
||||
el.style.minWidth = "2.3em";
|
||||
el.style.textAlign = "right";
|
||||
el.innerText = " " + this.plugin.settings.pngExportScale.toString();
|
||||
});
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(t("EXPORT_BACKGROUND_NAME"))
|
||||
@@ -226,8 +366,8 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.exportWithBackground)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.exportWithBackground = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.plugin.triggerEmbedUpdates();
|
||||
this.applySettingsUpdate();
|
||||
this.requestEmbedUpdate = true;
|
||||
}));
|
||||
|
||||
new Setting(containerEl)
|
||||
@@ -237,8 +377,8 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.exportWithTheme)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.exportWithTheme = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.plugin.triggerEmbedUpdates();
|
||||
this.applySettingsUpdate();
|
||||
this.requestEmbedUpdate = true;
|
||||
}));
|
||||
|
||||
this.containerEl.createEl('h1', {text: t("EXPORT_HEAD")});
|
||||
@@ -250,17 +390,35 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.keepInSync)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.keepInSync = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.applySettingsUpdate();
|
||||
}));
|
||||
|
||||
const removeDropdownOption = (opt: string) => {
|
||||
let i=0;
|
||||
for(i=0;i<dropdown.selectEl.options.length;i++) {
|
||||
if((dropdown.selectEl.item(i) as HTMLOptionElement).label===opt) {
|
||||
dropdown.selectEl.item(i).remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(t("EXPORT_SVG_NAME"))
|
||||
.setDesc(t("EXPORT_SVG_DESC"))
|
||||
.addToggle(toggle => toggle
|
||||
.setValue(this.plugin.settings.autoexportSVG)
|
||||
.onChange(async (value) => {
|
||||
if(value) {
|
||||
dropdown.addOption("SVG","SVG");
|
||||
} else {
|
||||
if (this.plugin.settings.embedType === "SVG") {
|
||||
dropdown.setValue("excalidraw");
|
||||
this.plugin.settings.embedType = "excalidraw";
|
||||
}
|
||||
removeDropdownOption("SVG");
|
||||
}
|
||||
this.plugin.settings.autoexportSVG = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.applySettingsUpdate();
|
||||
}));
|
||||
|
||||
|
||||
@@ -270,8 +428,17 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.addToggle(toggle => toggle
|
||||
.setValue(this.plugin.settings.autoexportPNG)
|
||||
.onChange(async (value) => {
|
||||
if(value) {
|
||||
dropdown.addOption("PNG","PNG");
|
||||
} else {
|
||||
if (this.plugin.settings.embedType === "PNG") {
|
||||
dropdown.setValue("excalidraw");
|
||||
this.plugin.settings.embedType = "excalidraw";
|
||||
}
|
||||
removeDropdownOption("PNG");
|
||||
}
|
||||
this.plugin.settings.autoexportPNG = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.applySettingsUpdate();
|
||||
}));
|
||||
|
||||
this.containerEl.createEl('h1', {text: t("COMPATIBILITY_HEAD")});
|
||||
@@ -283,7 +450,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.compatibilityMode)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.compatibilityMode = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.applySettingsUpdate();
|
||||
}));
|
||||
|
||||
new Setting(containerEl)
|
||||
@@ -293,7 +460,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.autoexportExcalidraw)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.autoexportExcalidraw = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.applySettingsUpdate();
|
||||
}));
|
||||
|
||||
new Setting(containerEl)
|
||||
@@ -303,7 +470,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.syncExcalidraw)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.syncExcalidraw = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.applySettingsUpdate();
|
||||
}));
|
||||
|
||||
this.containerEl.createEl('h1', {text: t("EXPERIMENTAL_HEAD")});
|
||||
@@ -317,18 +484,18 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.experimentalFileType = value;
|
||||
this.plugin.experimentalFileTypeDisplayToggle(value);
|
||||
await this.plugin.saveSettings();
|
||||
this.applySettingsUpdate();
|
||||
}));
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(t("FILETAG_NAME"))
|
||||
.setDesc(t("FILETAG_DESC"))
|
||||
.addText(text => text
|
||||
.setPlaceholder('✏️')
|
||||
.setPlaceholder(t("INSERT_EMOJI"))
|
||||
.setValue(this.plugin.settings.experimentalFileTag)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.experimentalFileTag = value;
|
||||
await this.plugin.saveSettings();
|
||||
this.applySettingsUpdate();
|
||||
}));
|
||||
}
|
||||
}
|
||||
39
styles.css
39
styles.css
@@ -63,12 +63,35 @@ button.ToolIcon_type_button[title="Export"] {
|
||||
flex-grow: 1;
|
||||
}
|
||||
|
||||
/*
|
||||
@font-face {
|
||||
font-family: "Virgil";
|
||||
src: url("https://excalidraw.com/Virgil.woff2");
|
||||
li[data-testid] {
|
||||
border: 0 !important;
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
width: 100% !important;
|
||||
}
|
||||
|
||||
.excalidraw .context-menu-option-separator {
|
||||
margin: 4px !important;
|
||||
}
|
||||
|
||||
.excalidraw .popover {
|
||||
padding: 0 !important;
|
||||
border-color: transparent !important;
|
||||
border: 0 !important;
|
||||
box-shadow: 0 !important;
|
||||
background-color: transparent !important;
|
||||
}
|
||||
|
||||
.disable-zen-mode--visible {
|
||||
color: var(--text-primary-color);
|
||||
}
|
||||
|
||||
.disable-zen-mode {
|
||||
width: 9em !important;
|
||||
}
|
||||
|
||||
.ex-coffee-div {
|
||||
text-align: center;
|
||||
margin-bottom: 20px;
|
||||
|
||||
}
|
||||
@font-face {
|
||||
font-family: "Cascadia";
|
||||
src: url("https://excalidraw.com/Cascadia.woff2");
|
||||
}*/
|
||||
|
||||
@@ -16,10 +16,10 @@
|
||||
"esnext",
|
||||
"DOM.Iterable"
|
||||
],
|
||||
"jsx": "react",
|
||||
"jsx": "react"
|
||||
},
|
||||
"include": [
|
||||
"**/*.ts",
|
||||
"**/*.tsx", "src/openDrawing.ts",
|
||||
"**/*.tsx", "src/openDrawing.ts"
|
||||
]
|
||||
}
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
"1.1.10": "0.11.13"
|
||||
"1.3.16": "0.11.13"
|
||||
}
|
||||
|
||||
57
yarn.lock
57
yarn.lock
@@ -882,11 +882,6 @@
|
||||
"@babel/helper-validator-identifier" "^7.14.5"
|
||||
"to-fast-properties" "^2.0.0"
|
||||
|
||||
"@excalidraw/excalidraw@^0.9.0":
|
||||
"integrity" "sha512-/LrmrZnrI7LLjT6+UOpxYOPVaR9sEEPJT4afodTGFk07ZedpmWbcLk59WekurDhwuiU2vyZW3Pc/fy3pPkFpxw=="
|
||||
"resolved" "https://registry.npmjs.org/@excalidraw/excalidraw/-/excalidraw-0.9.0.tgz"
|
||||
"version" "0.9.0"
|
||||
|
||||
"@rollup/plugin-babel@^5.3.0":
|
||||
"integrity" "sha512-9uIC8HZOnVLrLHxayq/PTzw+uS25E14KPUBh5ktF+18Mjo5yK0ToMMx6epY0uEgkjwJw0aBW4x2horYXh8juWw=="
|
||||
"resolved" "https://registry.npmjs.org/@rollup/plugin-babel/-/plugin-babel-5.3.0.tgz"
|
||||
@@ -1029,6 +1024,11 @@
|
||||
dependencies:
|
||||
"@types/estree" "*"
|
||||
|
||||
"@zsviczian/excalidraw@0.9.0-obsidian-image-support-3":
|
||||
"integrity" "sha512-Y+hIhIxoNsoyYS2AmhE9I8G0M6Q6KaQ3LxSn8p3JZbUGFqoAmDg+26fGHXhMsboaVXhKqonkw5UN1UlZYL5k1A=="
|
||||
"resolved" "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.9.0-obsidian-image-support-3.tgz"
|
||||
"version" "0.9.0-obsidian-image-support-3"
|
||||
|
||||
"abab@^1.0.3":
|
||||
"integrity" "sha1-X6rZwsB/YN12dw9xzwJbYqY8/U4="
|
||||
"resolved" "https://registry.npmjs.org/abab/-/abab-1.0.4.tgz"
|
||||
@@ -2788,12 +2788,6 @@
|
||||
optionalDependencies:
|
||||
"fsevents" "~2.3.2"
|
||||
|
||||
"chokidar2@file:./chokidar2":
|
||||
"resolved" "file:node_modules/watchpack/chokidar2"
|
||||
"version" "2.0.0"
|
||||
dependencies:
|
||||
"chokidar" "^2.1.8"
|
||||
|
||||
"ci-info@^1.5.0":
|
||||
"integrity" "sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A=="
|
||||
"resolved" "https://registry.npmjs.org/ci-info/-/ci-info-1.6.0.tgz"
|
||||
@@ -6897,14 +6891,13 @@
|
||||
dependencies:
|
||||
"isobject" "^3.0.1"
|
||||
|
||||
"obsidian@https://github.com/obsidianmd/obsidian-api/tarball/master":
|
||||
"integrity" "sha512-vXWcdTZ6XFfbzBJUOJ8axQq58KoIxkXQln0yyloUO8DhWSe1xt0xQNZIa0RxOTfsGfK5bgKk/0nOex4pJiW8bw=="
|
||||
"resolved" "https://github.com/obsidianmd/obsidian-api/tarball/master"
|
||||
"version" "0.11.13"
|
||||
"obsidian@^0.12.16":
|
||||
"integrity" "sha512-YwwhYrmlv71A/ntTiGOyGaqr9ONhKPE1OKN1tcHovLJC0N/BRZ7XlGpzaN1T3BnAE5H8DmYLsAI3h67u6eJPGQ=="
|
||||
"resolved" "https://registry.npmjs.org/obsidian/-/obsidian-0.12.16.tgz"
|
||||
"version" "0.12.16"
|
||||
dependencies:
|
||||
"@types/codemirror" "0.0.108"
|
||||
"moment" "2.29.1"
|
||||
"yaml" "2.0.0-4"
|
||||
|
||||
"obuf@^1.0.0", "obuf@^1.1.1":
|
||||
"integrity" "sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg=="
|
||||
@@ -7106,6 +7099,11 @@
|
||||
"resolved" "https://registry.npmjs.org/path-browserify/-/path-browserify-0.0.1.tgz"
|
||||
"version" "0.0.1"
|
||||
|
||||
"path-data-parser@^0.1.0", "path-data-parser@0.1.0":
|
||||
"integrity" "sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w=="
|
||||
"resolved" "https://registry.npmjs.org/path-data-parser/-/path-data-parser-0.1.0.tgz"
|
||||
"version" "0.1.0"
|
||||
|
||||
"path-dirname@^1.0.0":
|
||||
"integrity" "sha1-zDPSTVJeCZpTiMAzbG4yuRYGCeA="
|
||||
"resolved" "https://registry.npmjs.org/path-dirname/-/path-dirname-1.0.2.tgz"
|
||||
@@ -7238,6 +7236,19 @@
|
||||
"resolved" "https://registry.npmjs.org/pluralize/-/pluralize-7.0.0.tgz"
|
||||
"version" "7.0.0"
|
||||
|
||||
"points-on-curve@^0.2.0", "points-on-curve@0.2.0":
|
||||
"integrity" "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A=="
|
||||
"resolved" "https://registry.npmjs.org/points-on-curve/-/points-on-curve-0.2.0.tgz"
|
||||
"version" "0.2.0"
|
||||
|
||||
"points-on-path@^0.2.1":
|
||||
"integrity" "sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g=="
|
||||
"resolved" "https://registry.npmjs.org/points-on-path/-/points-on-path-0.2.1.tgz"
|
||||
"version" "0.2.1"
|
||||
dependencies:
|
||||
"path-data-parser" "0.1.0"
|
||||
"points-on-curve" "0.2.0"
|
||||
|
||||
"portfinder@^1.0.9":
|
||||
"integrity" "sha512-Se+2isanIcEqf2XMHjyUKskczxbPH7dQnlMjXX6+dybayyHvAf/TCgyMRlzf/B6QDhAEFOGes0pzRo3by4AbMA=="
|
||||
"resolved" "https://registry.npmjs.org/portfinder/-/portfinder-1.0.28.tgz"
|
||||
@@ -8412,6 +8423,15 @@
|
||||
optionalDependencies:
|
||||
"fsevents" "~2.3.2"
|
||||
|
||||
"roughjs@4.4.1":
|
||||
"integrity" "sha512-/RZvyVquID319VDc9HsF8wn8VPpbMBVdr4NMCi7mta9UeBBeqP6h5Hg4GZXG29DL6jwTkfMjyth/MF7Hn6Sq/w=="
|
||||
"resolved" "https://registry.npmjs.org/roughjs/-/roughjs-4.4.1.tgz"
|
||||
"version" "4.4.1"
|
||||
dependencies:
|
||||
"path-data-parser" "^0.1.0"
|
||||
"points-on-curve" "^0.2.0"
|
||||
"points-on-path" "^0.2.1"
|
||||
|
||||
"run-async@^2.2.0":
|
||||
"integrity" "sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ=="
|
||||
"resolved" "https://registry.npmjs.org/run-async/-/run-async-2.4.1.tgz"
|
||||
@@ -9961,11 +9981,6 @@
|
||||
"resolved" "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz"
|
||||
"version" "2.1.2"
|
||||
|
||||
"yaml@2.0.0-4":
|
||||
"integrity" "sha512-MoQoNhTFI400tkaeod+X0Vety1KD2L9dUa6pa1CVcyfcATjC/iDxoMLvqZ6U3D8c5KzxBrU2HnJH+PfaXOqI7w=="
|
||||
"resolved" "https://registry.npmjs.org/yaml/-/yaml-2.0.0-4.tgz"
|
||||
"version" "2.0.0-4"
|
||||
|
||||
"yargs-parser@^20.2.2":
|
||||
"integrity" "sha512-FiNkvbeHzB/syOjIUxFDCnhSfzAL8R5vs40MgLFBorXACCOAEaWu0gRZl14vG8MR9AOJIZbmkjhusqBYZ3HTHw=="
|
||||
"resolved" "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.7.tgz"
|
||||
|
||||
Reference in New Issue
Block a user