Compare commits

...

8 Commits

Author SHA1 Message Date
Zsolt Viczian
e6ad7aa304 Excalidraw 0.9 2021-07-10 20:45:09 +02:00
Zsolt Viczian
fdb71a0d03 JSON into codeblock, hover observer corrected 2021-07-10 17:11:02 +02:00
Zsolt Viczian
90c55211ba 1.2.0 2021-07-10 14:45:00 +02:00
zsviczian
8d2c064ee3 Update README1.2.md 2021-07-10 14:31:03 +02:00
Zsolt Viczian
b8a95392f1 readme 1.2 - draft 2021-07-10 14:20:20 +02:00
zsviczian
5430bc4b38 Update README1.2.md 2021-07-10 13:20:30 +02:00
Zsolt Viczian
c9d12c7295 readme 1.2 2021-07-10 12:26:44 +02:00
Zsolt Viczian
c37cbd7e31 improved hover preivew, experimental file tagging 2021-07-10 11:59:18 +02:00
12 changed files with 375 additions and 264 deletions

212
README.md
View File

@@ -1,185 +1,71 @@
The Obsidian-Excalidraw plugin integrates [Excalidraw](https://excalidraw.com/), a feature rich sketching tool, into Obsidian. You can store and edit Excalidraw files in your vault and you can transclude drawings into your documents. For a showcase of Excalidraw features, please read my blog post [here](https://www.zsolt.blog/2021/03/showcasing-excalidraw.html) and/or watch the videos below.
The Obsidian-Excalidraw plugin integrates [Excalidraw](https://excalidraw.com/), a feature rich sketching tool, into Obsidian. You can store and edit Excalidraw files in your vault, you can embed drawings into your documents, and you can link to documents and other drawings to/and from Excalidraw. For a showcase of Excalidraw features, please read my blog post [here](https://www.zsolt.blog/2021/03/showcasing-excalidraw.html) and/or watch the videos below.
![image](https://user-images.githubusercontent.com/14358394/115983515-d06c2c80-a5a1-11eb-8d12-c7df91d18107.png)
![image](https://user-images.githubusercontent.com/14358394/125159831-336d6880-e17a-11eb-8a3d-ceabc2555a08.png)
## Important notice to the 1.1.x update!
# Important notice to the 1.2.0 update
Thank you for updating to Excalidraw 1.1.x!
This version comes with tons of new features and possibilities.
I have improved how drawings are embedded! You no longer need an Excalidraw codeblock. You can now embed drawings just like any other images: `![[my drawing.excalidraw]]` or `![[my drawing.excalidraw|500|left]]` or `![[my drawing.excalidraw|right-wrap]]`, `![alttext|500|right](drawing.excalidraw)`, `![](folder/drawing.excalidraw)`, etc. You get the idea.
Drawings you've created with version 1.1.x need to be converted to take advantage of the new features. If you want, you can also continue to use your exisiting drawings in compatibility mode (e.g. if you use Logseq and Obsidian in parallel). During conversion your existing `*.excalidraw` files will be replaced with new `*.excalidraw.md` files.
### Detailed release notes are under the How to videos.
## Conversion and compatibility
To convert files you have the following options:
- Click `CONVERT FILES` in the migration dialog when installing 1.2.0
- In the Command Palette select `Excalidraw: Convert *.excalidraw files to *.excalidraw.md files` to convert all `*.excalidraw` files to `*.excalidraw.md` files.
- To convert files individually:
- Right click an `*.excalidraw` file in File Explorer and select one of the following options:
- `*.excalidraw => *.excalidraw.md`
- `*.excalidraw => *.md (Logseq compatibility)`: This option will retain the original *.excalidraw file next to the new Obsidian format. Make sure you also enable additional `Compatibility features` in `Settings` for a full solution.
- Open a legacy `*.excalidraw` file and select `Convert to new format` from the `Options Menu` in the Excalidraw view.
# Video walkthrough
| | | |
|----|----|----|
|[![Obsidian-Excalidraw 1.2.0 update - Major IMPROVEMENTS](https://user-images.githubusercontent.com/14358394/124356817-7b3f3d80-dc18-11eb-932d-363bb373c5ab.jpg)](https://youtu.be/UxJLLYtgDKE)|[![1 Getting Started](https://user-images.githubusercontent.com/14358394/125160304-7f211180-e17c-11eb-8363-c52723de1ffd.jpg)](https://youtu.be/sY4FoflGaiM)|[![2 Basic shapes and features](https://user-images.githubusercontent.com/14358394/125160312-8a743d00-e17c-11eb-9fa2-490ef4cbd59e.jpg)](https://youtu.be/Iy_oVTq12Gw)|
|[![3 Groups](https://user-images.githubusercontent.com/14358394/125160323-96f89580-e17c-11eb-9bce-8eb1067a51bb.jpg)](https://youtu.be/QOL1KF7-kdc)|[![4 Stencil](https://user-images.githubusercontent.com/14358394/125160332-9f50d080-e17c-11eb-98e9-fec60fe147d9.jpg)](https://youtu.be/aSgcbfspvfo)|[![5 embedding](https://user-images.githubusercontent.com/14358394/125160341-a546b180-e17c-11eb-9de8-d87fdc844c9c.jpg)](https://youtu.be/MaJ5jJwBRWs)|
|[![6 Links](https://user-images.githubusercontent.com/14358394/125160346-aa0b6580-e17c-11eb-930b-4024807040d1.jpg)](https://youtu.be/MXzeCOEExNo)|[![7 Markdown](https://user-images.githubusercontent.com/14358394/125160354-b2fc3700-e17c-11eb-81af-9e71e461f6dd.jpg)](https://youtu.be/R0IAg0s-wQE)|[![8 Templates](https://user-images.githubusercontent.com/14358394/125160360-b8f21800-e17c-11eb-8bd8-79d4e3f6e92d.jpg)](https://youtu.be/ibdS7ykwpW4)|
|[![9 Excalidraw Automate](https://user-images.githubusercontent.com/14358394/125160367-bdb6cc00-e17c-11eb-92f1-6f59faea85fd.jpg)](https://youtu.be/VRZVujfVab0)|[![10 Miscellaneous](https://user-images.githubusercontent.com/14358394/125160374-c3141680-e17c-11eb-8cc2-dfaffd903d15.jpg)](https://youtu.be/D1iBYo1_jjc)||
# Key features
- The plugin saves drawings to your vault as a file with the *.excalidraw* file extension.
- The plugin adds the following actions to the **command palette**:
- Create a new drawing
- Find and edit existing drawings in your vault,
- Transclude (embed) a drawing into a document, and
- Export a drawing as PNG or SVG.
- Insert vault internal-link into drawing
- You can also use the **file explorer** in your vault to open existing Excalidraw files.
- Use the **ribbon button** to create a new drawing, CTRL+Click to open on a new page.
- Open settings to set up
- a **default folder** for new drawings,
- a **Template** by first creating a drawing, customizing it the way you like it, and specifying the file as the template in settings,
- Excalidraw to **automatically export SVG and/or PNG** files for your drawings, and to keep those in sync with your drawing,
- default width of embedded drawings
- You can also customize the **size and position of the embedded image** using the `[[image.excalidraw|100]]`, `[[image.excalidraw|100x100]]`, `[[image.excalidraw|100|left]]`, `[[image.excalidraw|right-wrap]]`, formatting options. `[[<filename.excalidraw>|<width>x<height>|<alignment>]]`. You can add your custom alignment via css. Any text that appears in `<alignment>` will be added as style to the SVG element and the wrapper DIV element. Check below and styles.css for more insight.
- Supports hyperlinks e.g. `https://zsolt.blog` and internal links e.g. `[[My file in vault]]` in drawing text. Ctrl/meta + click on a text element.
- Square brackets can be omitted if the entire text element is an internal link. i.e. the following two text elements `Check out the [[requirements specification]]!!` and `requirements specification` will both represent a link to `requirements specification.md`.
- When files are moved/renamed in your vault, text elements that are recognized links will also get updated. Check corresponding setting.
- Includes full [Templater](https://silentvoid13.github.io/Templater/) and [Dataview](https://blacksmithgu.github.io/obsidian-dataview/docs/api/intro/) support through ExcalidrawAutomate. Read detailed help + examples: [here](https://zsviczian.github.io/obsidian-excalidraw-plugin/)
- REQUIRES AN OBSIDIAN SYNC SUBSCRIPTION: Temporary hack/workaround to enable Obsidian Sync for Excalidraw files. This enables almost real-time two-way sync for Excalidraw files between your devices. You can draw on your iPad with your pencil, on your Android with your stylus, and the image will be available in Obsidian on your desktop as well and vice versa.
# How to?
Part 1: Intro to Obsidian-Excalidraw - Start a new drawing (3:12)
[![Part 1: Intro to Obsidian-Excalidraw - Start a new drawing](https://user-images.githubusercontent.com/14358394/115983840-05797e80-a5a4-11eb-93cd-bae4b1973f72.jpg)](https://youtu.be/i-hIfY-Ecjg)
Part 2: Intro to Obsidian-Excalidraw - Basic features (6:06)
[![Part 2: Intro to Obsidian-Excalidraw - Basic features](https://user-images.githubusercontent.com/14358394/115983902-699c4280-a5a4-11eb-973d-2ba1bd7ac2db.jpg)](https://youtu.be/-dk7pvdl-H0)
Part 3: Intro to Obsidian-Excalidraw - Advanced features (3:26)
[![Part 3: Intro to Obsidian-Excalidraw - Advanced features](https://user-images.githubusercontent.com/14358394/115983916-7de03f80-a5a4-11eb-8f36-4ad516ef9e80.jpg)](https://youtu.be/2cKlEwo8WU0)
Part 4: Intro to Obsidian-Excalidraw - Setting up a template (1:45)
[![Part 4: Intro to Obsidian-Excalidraw - Setting up a template](https://user-images.githubusercontent.com/14358394/115983929-92bcd300-a5a4-11eb-9d4f-03e5cb9e3ebf.jpg)](https://youtu.be/oNPYZEpmuJ8)
Part 5: Intro to Obsidian-Excalidraw - Stencil Library (3:16)
[![Part 5: Intro to Obsidian-Excalidraw - Stencil Library](https://user-images.githubusercontent.com/14358394/115983944-a8ca9380-a5a4-11eb-8a69-e74ae00d95be.jpg)](https://youtu.be/rLx-9FvlzgI)
Part 6: Intro to Obsidian-Excalidraw: Embedding drawings (2:08)
[![Part 6: Intro to Obsidian-Excalidraw: Embedding drawings](https://user-images.githubusercontent.com/14358394/115983954-bbdd6380-a5a4-11eb-9243-f0151451afcd.jpg)](https://youtu.be/JQeJ-Hh-xAI)
# Release Notes
## 1.1.10
- When you CTRL-Click a grouped collection of objects Excalidraw will open the page based on the embedded text.
- I added a setting to disable the CTRL-click functionality should it interfere with default Excalidraw behavior for you. In my experience double-clicking achieves the same outcome as a CTRL-click on an element in a grouped collection of objects, but if you use the CTRL-click feature to select an element of a group frequently, and find the "CTRL-click to open a link" feature annoying, you can now disable it.
## 1.1.9
- I modified the behavior of Excalidraw text element links.
- The plugin aims to integrate Excalidraw seemlessly into Obsidian including Command Palette actions, File Explorer features, Option Menu commands, and the Ribbon Button.
- CTRL+Click on the ribbon button, or in the file explorer to create / open drawings in a new pane.
- Settings will allow you to customzie Excalidraw to your needs:
- Default folder for new drawings and define custom filename pattern for new drawings.
- Template for new drawings. The template will restore stroke properties. This means you can set up defaults in your template for stroke color, stroke width, opacity, font family, font size, fill style, stroke style, etc. This also applies to ExcalidrawAutomate.
- If portability is important to you: Auto-export SVG and/or PNG files including keep-in-sync feature so you can embed svg/png into your documents instead of embedding excalidraw files.
- Specify the default width of embedded drawings.
- Compatibility features to auto-export and keep in sync markdown excalidraw files and legacy .excalidraw files.
- Experimental feature to add custom TAG to file expolorer to mark drawing files.
- Enable / disable autosave.
- You can customize the size and position of the embedded images using the `[[image.excalidraw|100]]`, `[[image.excalidraw|100x100]]`, `[[image.excalidraw|100|left]]`, `[[image.excalidraw|right-wrap]]`, formatting options. `[[<filename.excalidraw>|<width>x<height>|<alignment>]]`. You can add your custom alignment via css. Any text that appears in `<alignment>` will be added to the rendered SVG element style and to the wrapper DIV element. Check below and styles.css for more insight.
- Supports hyperlinks e.g. `https://zsolt.blog`, `[Obsidian](https://obsidian.md)`, and internal links e.g. `[[My file in vault|Alias]]` in drawing text.
- Links will update when files are moved or renamed, if you have the Obsidian setting Files & Links/Automatically Update Internal Links 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
- For convenience you can also use the command palette to insert links into drawings
- 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
- CTRL/META + ALT + SHIFT + CLICK to create the file (if it does not yet exist) and open it in a new pane
- I added a setting to limit link functionality to `[[valid Obsidian links]]` only. By default, the full text of a text element is treated as a link unless it contains a `[[valid internal link]]`, in which case only the `[[internal link]]` is used. The new setting may be beneficial if you want to avoid unexpected updates to text in your drawings. This may happen if a text element in a drawing accidentally matches a file in your vault, and you happen to rename or move that file. By limiting the link behavior to `[[valid internal links]]` only, these accidental matches can be avoided. This is not frequent but happened to me recently.
- LaTeX symbol support. I resolved issue [#75](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/75) by adding a new command palette option ("Insert LaTeX-symbol") to insert an expression containing a LaTeX symbol or a simple formula. Some symbols may not display properly using the "Hand-drawn" font. If that is the case try using the "Normal" or "Code" fonts.
## 1.1.8
- Improvements to links
- You can now use square brackets to denote links. i.e. the text element `Which are my [[favorite books]]?` will be a link to `favorite books.md`.
- Square brackets can still be omitted if the entire text element is an internal link. i.e. the following two text elements `Check out the [[requirements specification]]!!` and `requirements specification` will both represent a link to `requirements specification.md`.
- When files are moved/renamed in your vault, text elements that are recognized links will also get updated in your drawings.
- I added a new command palette option to insert an internal link into a file in your vault to the active drawing. While a drawing is open press ctrl/cmd+p and select `Excalidraw: Insert link to file`.
- I Added CTRL/CMD + hover quick preview for Excalidraw files
[![Obsidian-Excalidraw 1.1.8 - Links enhanced](https://user-images.githubusercontent.com/14358394/120925953-31c40700-c6db-11eb-904d-65300e91815e.jpg)](https://youtu.be/qT_NQAojkzg)
## 1.1.6
[![Obsidian-Excalidraw 1.1.6 - Links](https://user-images.githubusercontent.com/14358394/119559279-bdb46580-bda2-11eb-88cb-7614dc452034.jpg)](https://youtu.be/FDsMH-aLw_I)
## 1.1.5
- The template will now restore stroke properties. This means you can set up defaults in your template for stroke color, stroke width, opacity, font family, font size, fill style, stroke style, etc. This also applies to ExcalidrawAutomate.
- Added settings to customize the autogenerated filename
- Minor fixes for occasional console.log errors.
## 1.1.0
- ALT+Enter and CTRL+ALT+Enter on the filename in edit mode will open up the Excalidraw editor. Click and CTRL+Click on the image in preview mode will also bring up the Excalidraw editor as expected.
- I have also added two new Command Palette commands. Both create a new drawing and immediately embed it in the document you are editing, one will open the drawing in a new workspace pane, the other within the currently active pane.
- [Ozan's Image in Editor Plugin](https://github.com/ozntel/oz-image-in-editor-obsidian)
In a nice collaboration with Ozan, his Image in Editor plugin now supports Excalidraw. I recommend installing his plugin to display drawings also in Edit mode.
### MIGRATION to 1.1.0
I have added a Migration command to the Command Palette. When you select this, the program will run a search and replace for all the excalidraw codeblocks in your vault and will convert them to the new format.
## 1.0.12 Freehand drawing
- now includes the new freehand drawing features from Excalidraw.com
- If you use Obsydian sync with Excalidraw sync, be sure to update all your devices to the new version, as the old excalidraw will simply delete the freehand drawn images and/or simply not show the drawing.
### Temporary workaround - use it only if you are ok with hacky solutions
- I implemented a temporary workaround to enable Obsidian Sync for Excalidraw files. This enables almost real-time two-way sync between your devices. You can draw on your iPad with your pencil, on your Android with your stylus, and the image will be available in Obsidian as well and vice versa.
- By enabling this feature Excalidraw will sync drawings to a sync folder where drawings are stored in an ".md" file. This will allow Obsidian sync to synchronize Excalidraw drawings as well... Whenever your drawing changes, the corresponding file in the sync folder will also get updated. Similarly, whenever a file is synchronized to the sync folder by Obsidian sync, Excalidraw will sync it with the .excalidraw file in your vault.
- Because this is a temporary workaround until Obsidian sync is ready, I didn't implement extensive application logic to manage sync. Sync might get confused requiring some manual intervention.
### QoL improvement
- I added an autosave feature. Your active drawing gets saved every 30 seconds if you've made changes to it. Drawings otherwise get saved when the window loses focus, or when you close the drawing, etc. Autosave limits the risk of accidental data loss on mobiles when you "swipe out" Obsidian to close it.
## 1.0.10
[![Obsidian-Excalidraw 1.0.10 update](https://user-images.githubusercontent.com/14358394/117579017-60a58800-b0f1-11eb-8553-7820964662aa.jpg)](https://youtu.be/W7pWXGIe4rQ)
## 1.0.8 and 1.0.9 (minor fixes)
[![Obsidian-Excalidraw 1.0.8 update](https://user-images.githubusercontent.com/14358394/117492534-029e6680-af72-11eb-90a3-086e67e70c1c.jpg)](https://youtu.be/AtEhmHJjnxM)
### QoL improvements
- Adds context menu to File Explorer to create new drawings
- Adds a new command to the palette: “Transclude (embed) the most recently edited Excalidraw drawing”
- Automatically update file-links in transclusions when you rename or move your drawing
- Saves drawing and updates all active pre-views when drawing loses focus
- File is closed and removed when you select “Delete file” from more options
- Saves drawing when exiting Obsidian
- Fixes pen positioning bug with sliding panes after panes scroll
### ExcalidrawAutomte full Templater and DataviewJS support
You now have ultimate flexibility over your Excalidraw templates using Templater and Dataview.
- Detailed documentation available [here](https://zsviczian.github.io/obsidian-excalidraw-plugin/)
- I created few examples from the simple to the more complex
- Simple use-case: Creating a drawing using a custom template and following a file and folder naming convention of your choice.
- Complex use-case: Create a mindmap from a tabulated outline.
![Drawing 2021-05-05 20 52 34](https://user-images.githubusercontent.com/14358394/117194124-00a69d00-ade4-11eb-8b75-5e18a9cbc3cd.png)
## 1.0.6 and 1.0.7
[![1.0.6 Update](https://user-images.githubusercontent.com/14358394/116312909-58725200-a7ad-11eb-89b9-c67cb48ffebb.jpg)](https://youtu.be/ipZPbcP2B0M)
### SVG styling when embedding
- 1.0.7 adds further flexibility to styling
- new formatting option for the code block embedding
- Valid values: `left`, `right`, `left-wrap`, `right-wrap`... but anything after the last `|` character will be added to the class of the SVG element and the wrapper DIV element.
Here is the corresponding CSS:
```css
img.excalidraw-svg-right-wrap {
float: right;
margin: 0px 0px 20px 20px;
}
img.excalidraw-svg-left-wrap {
float: left;
margin: 0px 35px 20px 0px;
}
img.excalidraw-svg-right {
float: right;
}
img.excalidraw-svg-left {
float: left;
}
div.excalidraw-svg-right,
div.excalidraw-svg-left {
display: table;
width: 100%;
}
```
- Using the block reference you can also reference & transclude text that appears on drawings, in other documents
- Insert LaTex symbols and simple formulas using the Command Palette action "Insert LaTeX-symbol". Some symbols may not display properly using the "Hand-drawn" font. If that is the case try using the "Normal" or "Code" fonts.
- Since 1.2.0 Drawing files are stored in Markdown files
- You can add tags to drawings
- You can add metadata to the YAML front matter of drawings
- Anything you add between the frontmatter and the `# Text Elements` heading will be ignored by Excalidraw, i.e. you can add whatever you like here, it will be preserved as part of the document.
- Excalidraw documents now show in graph view.
- 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.
# Known issues
- I have seen two cases when adding a stencil library did not work. In both cases, the end solution was a reinstall of Obsidian. The root cause is not clear, but maybe because of the incremental updates of Obsidian from an early version.
- Mobile support
- Positioning of the pen gets misaligned after you open the command palette.
- Partially mitigated in 1.0.10 by the introduction of autosave: Your drawing will not be saved when you terminate the mobile app by closing the Obsidian task.
### Resolved known issues:
- Resolved with 1.0.10 Temporary workaround:
- Sync does not support .excalidraw files. This issue will be addressed in a later release of Obsidian sync. Until then, you can use my temporary workaround.
- Resolved with Obsidian mobile 0.18:
- On mobile (iOS and Android): As you draw left to right it opens left sidebar. Draw right to left, opens right sidebar. Draw down, opens commands palette. So seems open is emulating the gestures, even when drawing towards the center.
# Tips and tricks
- If you want to sketch in fullscreen, I recommend installing the [Fullscreen Focus Mode](https://github.com/razumihin/obsidian-fullscreen-plugin) plugin.
- [Ozan's Image in Editor Plugin](https://github.com/ozntel/oz-image-in-editor-obsidian). In a nice collaboration with Ozan, his Image-in-Editor plugin now supports Excalidraw. I recommend installing his plugin to display drawings also in Edit mode.
- [Ozan's Image in Editor Plugin](https://github.com/ozntel/oz-image-in-editor-obsidian). In a nice collaboration with Ozan, his Image-in-Editor plugin now supports Excalidraw. I recommend installing his plugin to display drawings also in Edit mode. Note that Ozan's plugin will only display Excalidraw drawings if the link ends with `.md` or `.excalidraw`. i.e. the following drawing will show in Edit Mode `![[My Drawing.md]]`, but wiki links such as `[[My Drawing]]` will not.
# Feedback, questions, ideas, problems
Join the conversation about the Excalidraw plugin on [forum.obsidian.md](https://forum.obsidian.md/t/excalidraw-full-featured-sketching-plugin-in-obsidian)

View File

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

View File

@@ -11,7 +11,7 @@
"author": "",
"license": "MIT",
"dependencies": {
"@excalidraw/excalidraw": "^0.8.0",
"@excalidraw/excalidraw": "^0.9.0",
"monkey-around": "^2.2.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",

View File

@@ -3,7 +3,6 @@ import {
FillStyle,
StrokeStyle,
StrokeSharpness,
FontFamily,
} from "@excalidraw/excalidraw/types/element/types";
import {
normalizePath,
@@ -14,7 +13,6 @@ import { getJSON } from "./ExcalidrawData";
import {
FRONTMATTER,
nanoid,
JSON_stringify,
JSON_parse
} from "./constants";
@@ -35,7 +33,7 @@ export interface ExcalidrawAutomate extends Window {
roughness: number;
opacity: number;
strokeSharpness: StrokeSharpness;
fontFamily: FontFamily;
fontFamily: number;
fontSize: number;
textAlign: string;
verticalAlign: string;
@@ -163,7 +161,7 @@ export async function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
elements.push(this.elementsDict[this.elementIds[i]]);
}
navigator.clipboard.writeText(
JSON_stringify({
JSON.stringify({
"type":"excalidraw/clipboard",
"elements": elements,
}));
@@ -179,7 +177,7 @@ export async function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
params?.onNewPane ? params.onNewPane : false,
params?.foldername ? params.foldername : this.plugin.settings.folder,
FRONTMATTER + exportSceneToMD(
JSON_stringify({
JSON.stringify({
type: "excalidraw",
version: 2,
source: "https://excalidraw.com",
@@ -211,7 +209,7 @@ export async function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
for (let i=0;i<this.elementIds.length;i++) {
elements.push(this.elementsDict[this.elementIds[i]]);
}
return ExcalidrawView.getSVG(
return await ExcalidrawView.getSVG(
{//createDrawing
"type": "excalidraw",
"version": 2,
@@ -235,7 +233,7 @@ export async function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
elements.push(this.elementsDict[this.elementIds[i]]);
}
return ExcalidrawView.getPNG(
{ //JSON_stringify(
{
"type": "excalidraw",
"version": 2,
"source": "https://excalidraw.com",
@@ -244,7 +242,7 @@ export async function initExcalidrawAutomate(plugin: ExcalidrawPlugin) {
"theme": template ? template.appState.theme : this.canvas.theme,
"viewBackgroundColor": template? template.appState.viewBackgroundColor : this.canvas.viewBackgroundColor
}
},//),
},
{
withBackground: plugin.settings.exportWithBackground,
withTheme: plugin.settings.exportWithTheme
@@ -514,5 +512,9 @@ async function getTemplate(fileWithPath: string):Promise<{elements: any,appState
}
outString += te.text+' ^'+id+'\n\n';
}
return outString + '# Drawing\n'+ data.replaceAll("[","&#91;");
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);
//+data.replaceAll("[","&#91;");
}

View File

@@ -8,20 +8,21 @@ import { measureText } from "./ExcalidrawAutomate";
import ExcalidrawPlugin from "./main";
import { ExcalidrawSettings } from "./settings";
import {
JSON_stringify,
JSON_parse
} from "./constants";
const DRAWING_REG = /\n# Drawing\n(```json\n)?(.*)(```)?/gm;
//![[link|alias]]![alias](link)
//1 2 3 4 5 6
export const REG_LINK_BACKETS = /(!)?\[\[([^|\]]+)\|?(.+)?]]|(!)?\[(.*)\]\((.*)\)/g;
export function getJSON(data:string):string {
const findJSON = /\n# Drawing\n(.*)/gm
const findJSON = DRAWING_REG;
const res = data.matchAll(findJSON);
const parts = res.next();
if(parts.value && parts.value.length>1) {
return parts.value[1];
return parts.value[2];
}
return data;
}
@@ -68,10 +69,10 @@ export class ExcalidrawData {
}
//Load scene: Read the JSON string after "# Drawing"
let parts = data.matchAll(/\n# Drawing\n(.*)/gm).next();
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[1]);
this.scene = JSON_parse(parts.value[2]);
}
//Trim data to remove the JSON string
data = data.substring(0,parts.value.index);
@@ -98,6 +99,17 @@ export class ExcalidrawData {
return true;
}
public async loadLegacyData(data: string,file: TFile):Promise<boolean> {
this.file = file;
this.textElements = new Map<string,{raw:string, parsed:string}>();
this.setShowLinkBrackets();
this.setLinkPrefix();
this.scene = JSON.parse(data);
this.findNewTextElementsInScene();
await this.setAllowParse(false,true);
return true;
}
public async setAllowParse(allowParse:boolean,forceupdate:boolean=false) {
this.allowParse = allowParse;
await this.updateSceneTextElements(forceupdate);
@@ -146,7 +158,7 @@ export class ExcalidrawData {
//get scene text elements
const texts = this.scene.elements?.filter((el:any)=> el.type=="text")
let jsonString = JSON_stringify(this.scene);
let jsonString = JSON.stringify(this.scene);
let dirty:boolean = false; //to keep track if the json has changed
let id:string; //will be used to hold the new 8 char long ID for textelements that don't yet appear under # Text Elements
@@ -290,7 +302,10 @@ export class ExcalidrawData {
for(const key of this.textElements.keys()){
outString += this.textElements.get(key).raw+' ^'+key+'\n\n';
}
return outString + '# Drawing\n' + JSON_stringify(this.scene);
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);
}
public syncElements(newScene:any):boolean {

View File

@@ -27,7 +27,6 @@ import {
FRONTMATTER_KEY,
UNLOCK_ICON_NAME,
LOCK_ICON_NAME,
JSON_stringify,
JSON_parse
} from './constants';
import ExcalidrawPlugin from './main';
@@ -65,6 +64,7 @@ export default class ExcalidrawView extends TextFileView {
private lockedElement:HTMLElement;
private unlockedElement:HTMLElement;
private preventReload:boolean = true;
public compatibilityMode: boolean = false;
id: string = (this.leaf as any).id;
@@ -90,13 +90,13 @@ export default class ExcalidrawView extends TextFileView {
if (!this.getScene) return false;
scene = this.getScene();
}
const filepath = this.file.path.substring(0,this.file.path.lastIndexOf('.md')) + '.svg';
const filepath = this.file.path.substring(0,this.file.path.lastIndexOf(this.compatibilityMode ? '.excalidraw':'.md')) + '.svg';
const file = this.app.vault.getAbstractFileByPath(normalizePath(filepath));
const exportSettings: ExportSettings = {
withBackground: this.plugin.settings.exportWithBackground,
withTheme: this.plugin.settings.exportWithTheme
}
const svg = ExcalidrawView.getSVG(scene,exportSettings);
const svg = await ExcalidrawView.getSVG(scene,exportSettings);
if(!svg) return;
const svgString = ExcalidrawView.embedFontsInSVG(svg).outerHTML;
if(file && file instanceof TFile) await this.app.vault.modify(file,svgString);
@@ -125,7 +125,7 @@ export default class ExcalidrawView extends TextFileView {
}
const png = await ExcalidrawView.getPNG(scene,exportSettings);
if(!png) return;
const filepath = this.file.path.substring(0,this.file.path.lastIndexOf('.md')) + '.png';
const filepath = this.file.path.substring(0,this.file.path.lastIndexOf(this.compatibilityMode ? '.excalidraw':'.md')) + '.png';
const file = this.app.vault.getAbstractFileByPath(normalizePath(filepath));
if(file && file instanceof TFile) await this.app.vault.modifyBinary(file,await png.arrayBuffer());
else await this.app.vault.createBinary(filepath,await png.arrayBuffer());
@@ -141,7 +141,7 @@ export default class ExcalidrawView extends TextFileView {
// if drawing is in Text Element Edit Unlock, then everything is raw and parse and so an async function is not required here
getViewData () {
//console.log("ExcalidrawView.getViewData()");
if(this.getScene) {
if(this.getScene && !this.compatibilityMode) {
if(this.excalidrawData.syncElements(this.getScene())) {
this.loadDrawing(false);
@@ -159,6 +159,13 @@ export default class ExcalidrawView extends TextFileView {
.replace(/excalidraw-plugin:\s.*\n/,FRONTMATTER_KEY+": " + (this.isTextLocked ? "locked\n" : "unlocked\n"));
return header + this.excalidrawData.generateMD();
}
if(this.getScene && this.compatibilityMode) {
this.excalidrawData.syncElements(this.getScene());
const scene = this.excalidrawData.scene;
if(this.plugin.settings.autoexportSVG) this.saveSVG(scene);
if(this.plugin.settings.autoexportPNG) this.savePNG(scene);
return JSON.stringify(scene);
}
else return this.data;
}
@@ -296,13 +303,23 @@ export default class ExcalidrawView extends TextFileView {
}
async setViewData (data: string, clear: boolean) {
async setViewData (data: string, clear: boolean = false) {
this.app.workspace.onLayoutReady(async ()=>{
//console.log("ExcalidrawView.setViewData()");
this.compatibilityMode = this.file.extension == "excalidraw";
this.plugin.settings.drawingOpenCount++;
this.plugin.saveSettings();
this.lock(data.search("excalidraw-plugin: locked\n")>-1,false);
if(!(await this.excalidrawData.loadData(data, this.file,this.isTextLocked))) return;
if(this.compatibilityMode) {
this.unlockedElement.hide();
this.lockedElement.hide();
await this.excalidrawData.loadLegacyData(data,this.file);
if (!this.plugin.settings.compatibilityMode) {
new Notice(t("COMPATIBILITY_MODE"),4000);
}
} else {
this.lock(data.search("excalidraw-plugin: locked\n")>-1,false);
if(!(await this.excalidrawData.loadData(data, this.file,this.isTextLocked))) return;
}
if(clear) this.clear();
this.loadDrawing(true)
this.dirty = false;
@@ -331,9 +348,9 @@ export default class ExcalidrawView extends TextFileView {
}
//Compatibility mode with .excalidraw files
/* canAcceptExtension(extension: string) {
canAcceptExtension(extension: string) {
return extension == "excalidraw";
}*/
}
// gets the title of the document
getDisplayText() {
@@ -353,25 +370,38 @@ export default class ExcalidrawView extends TextFileView {
onMoreOptionsMenu(menu: Menu) {
// Add a menu item to force the board to markdown view
if(!this.compatibilityMode) {
menu
.addItem((item) => {
item
.setTitle(t("OPEN_AS_MD"))
.setIcon("document")
.onClick(async () => {
this.plugin.excalidrawFileModes[this.id || this.file.path] = "markdown";
this.plugin.setMarkdownView(this.leaf);
});
})
.addItem((item) => {
item
.setTitle(t("EXPORT_EXCALIDRAW"))
.setIcon(ICON_NAME)
.onClick( async (ev) => {
if(!this.getScene || !this.file) return;
this.download('data:text/plain;charset=utf-8',encodeURIComponent(JSON.stringify(this.getScene())), this.file.basename+'.excalidraw');
});
});
} else {
menu
.addItem((item) => {
item
.setTitle(t("CONVERT_FILE"))
.onClick(async () => {
await this.save();
this.plugin.openDrawing(await this.plugin.convertSingleExcalidrawToMD(this.file),false);
});
});
}
menu
.addItem((item) => {
item
.setTitle(t("OPEN_AS_MD"))
.setIcon("document")
.onClick(async () => {
this.plugin.excalidrawFileModes[this.id || this.file.path] = "markdown";
this.plugin.setMarkdownView(this.leaf);
});
})
.addItem((item) => {
item
.setTitle(t("EXPORT_EXCALIDRAW"))
.setIcon(ICON_NAME)
.onClick( async (ev) => {
if(!this.getScene || !this.file) return;
this.download('data:text/plain;charset=utf-8',encodeURIComponent(JSON.stringify(this.getScene())), this.file.basename+'.excalidraw');
});
})
.addItem((item) => {
item
.setTitle(t("SAVE_AS_PNG"))
@@ -408,7 +438,7 @@ export default class ExcalidrawView extends TextFileView {
withBackground: this.plugin.settings.exportWithBackground,
withTheme: this.plugin.settings.exportWithTheme
}
let svg = ExcalidrawView.getSVG(this.getScene(),exportSettings);
let svg = await ExcalidrawView.getSVG(this.getScene(),exportSettings);
if(!svg) return null;
svg = ExcalidrawView.embedFontsInSVG(svg);
this.download("data:image/svg+xml;base64",btoa(unescape(encodeURIComponent(svg.outerHTML))),this.file.basename+'.svg');
@@ -520,7 +550,7 @@ export default class ExcalidrawView extends TextFileView {
}
const el: ExcalidrawElement[] = excalidrawRef.current.getSceneElements();
const st: AppState = excalidrawRef.current.getAppState();
return { //JSON_stringify(
return {
type: "excalidraw",
version: 2,
source: "https://excalidraw.com",
@@ -544,7 +574,7 @@ export default class ExcalidrawView extends TextFileView {
currentItemLinearStrokeSharpness: st.currentItemLinearStrokeSharpness,
gridSize: st.gridSize,
}
};//);
};
};
this.refresh = () => {
@@ -584,6 +614,19 @@ export default class ExcalidrawView extends TextFileView {
if(!this.getSelectedId()) return;
this.handleLinkClick(this,e);
},
onKeyDown: (ev:any) => {
if(!this.isTextLocked) return; //text is not locked
if(ev.keyCode!=13) return; //not an enter
if(!(ev.target instanceof HTMLDivElement)) return;
if(!this.getSelectedId()) return;
const event = new MouseEvent('dblclick', {
'view': window,
'bubbles': true,
'cancelable': true,
});
ev.target.querySelector("canvas").dispatchEvent(event);
new Notice(t("UNLOCK_TO_EDIT"));
},
},
React.createElement(Excalidraw.default, {
@@ -595,7 +638,9 @@ export default class ExcalidrawView extends TextFileView {
loadScene: false,
saveScene: false,
saveAsScene: false,
export: false
export: { saveFileToDisk: false },
saveAsImage: false,
saveToActiveFile: false,
},
},
initialData: initdata,
@@ -633,7 +678,7 @@ export default class ExcalidrawView extends TextFileView {
ReactDOM.render(reactElement,(this as any).contentEl);
}
public static getSVG(scene:any, exportSettings:ExportSettings):SVGSVGElement {
public static async getSVG(scene:any, exportSettings:ExportSettings):Promise<SVGSVGElement> {
try {
return exportToSvg({
elements: scene.elements,
@@ -642,7 +687,7 @@ export default class ExcalidrawView extends TextFileView {
exportWithDarkMode: exportSettings.withTheme ? (scene.appState?.theme=="light" ? false : true) : false,
... scene.appState,},
exportPadding:10,
metadata: "Generated by Excalidraw-Obsidian plugin",
//metadata: "Generated by Excalidraw-Obsidian plugin",
});
} catch (error) {
return null;

View File

@@ -23,19 +23,20 @@ export class MigrationPrompt extends Modal {
const div = this.contentEl.createDiv();
div.addClass("excalidarw-prompt-div");
div.style.maxWidth = "600px";
div.createEl('p',{text: "This version comes with many new features and possibilities. Please read the description in Community Plugins to find out more."});
div.createEl('p',{text: "This version comes with tons of new features and possibilities. Please read the description in Community Plugins to find out more."});
div.createEl('p',{text: ""} , (el) => {
el.innerHTML = "<b>⚠ ATTENTION</b>: Drawings you've created with version 1.1.x need to be converted, they WILL NOT WORK out of the box. "+
el.innerHTML = "Drawings you've created with version 1.1.x need to be converted to take advantage of the new features. You can also continue to use them in compatibility mode. "+
"During conversion your old *.excalidraw files will be replaced with new *.excalidraw.md files.";
});
div.createEl('p',{text: ""}, (el) => {//files manually follow one of two options:
el.innerHTML = "To convert your drawings you have the following options:<br><ul>" +
"<li>Click <code>CONVERT</code> to convert all of your *.excalidraw files now, or if you prefer to make a backup first, then click <code>CANCEL</code>.</li>" +
"<li>Using the Command Palette select <code>Excalidraw: Convert *.excalidraw files to *.excalidraw.md files</code></li>" +
"<li>Right click an *.excalidraw file in File Explorer and select one of the following to convert files individually: <ul>"+
"<li>Click <code>CONVERT FILES</code> now to convert all of your *.excalidraw files, or if you prefer to make a backup first, then click <code>CANCEL</code>.</li>" +
"<li>In the Command Palette select <code>Excalidraw: Convert *.excalidraw files to *.excalidraw.md files</code></li>" +
"<li>Right click an <code>*.excalidraw</code> file in File Explorer and select one of the following options to convert files one by one: <ul>"+
"<li><code>*.excalidraw => *.excalidraw.md</code></li>"+
"<li><code>*.excalidraw => *.md (Logseq compatibility)</code>. This option will retain the original *.excalidraw file next to the new Obsidian format. " +
"Make sure you also enable <code>Compatibility features</code> in Settings for a full solution.</li></ul></li></ul>";
"Make sure you also enable <code>Compatibility features</code> in Settings for a full solution.</li></ul></li>" +
"<li>Open a drawing in compatibility mode and select <code>Convert to new format</code> from the <code>Options Menu</code></li></ul>";
});
div.createEl('p',{text: "This message will only appear maximum 3 times in case you have *.excalidraw files in your Vault."});
const bConvert = div.createEl('button', {text: "CONVERT FILES"});

View File

@@ -1,5 +1,5 @@
//This is to avoid brackets littering graph view with links
export function JSON_stringify(x:any):string {return JSON.stringify(x).replaceAll("[","&#91;");}
//export function JSON_stringify(x:any):string {return JSON.stringify(x).replaceAll("[","&#91;");}
export function JSON_parse(x:string):any {return JSON.parse(x.replaceAll("&#91;","["));}
import {customAlphabet} from "nanoid";

View File

@@ -42,6 +42,8 @@ export default {
LOCK: "Text Elements are unlocked. Click to LOCK.",
UNLOCK: "Text Elements are locked. Click to UNLOCK.",
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",
//settings.ts
FOLDER_NAME: "Excalidraw folder",
@@ -49,7 +51,9 @@ 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.excalidraw, the setting would be: Excalidraw/Template.excalidraw",
"Template.md, the setting would be: Excalidraw/Template.md " +
"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",
AUTOSAVE_DESC: "Automatically save the active drawing every 30 seconds. Save normally happens when you close Excalidraw or Obsidian, or move "+
"focus to another pane. In rare cases autosave may slightly disrupt your drawing flow. I created this feature with mobile " +
@@ -110,6 +114,18 @@ export default {
SYNC_EXCALIDRAW_NAME: "Sync *.excalidraw with *.md version of the same drawing",
SYNC_EXCALIDRAW_DESC: "If the modified date of the *.excalidraw file is more recent than the modified date of the *.md file " +
"then update the drawing in the .md file based on the .excalidraw file",
COMPATIBILITY_MODE_NAME: "New drawings as legacy files",
COMPATIBILITY_MODE_DESC: "By enabling this feature drawings you create with the ribbon icon, the command palette actions, "+
"and the file explorer are going to be all legacy *.excalidraw files. This setting will also turn off the reminder message " +
"when you open a legacy file for editing.",
EXPERIMENTAL_HEAD: "Experimental features",
EXPERIMENTAL_DESC: "These setting will not take effect immediately, only when the File Explorer is refreshed, or Obsidian restarted.",
FILETYPE_NAME: "Display type (✏️) for excalidraw.md files in File Explorer",
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.",
//openDrawings.ts
SELECT_FILE: "Select a file then press enter.",

View File

@@ -68,6 +68,7 @@ export default class ExcalidrawPlugin extends Plugin {
public lastActiveExcalidrawFilePath: string = null;
private hover: {linkText: string, sourcePath: string} = {linkText: null, sourcePath: null};
private observer: MutationObserver;
private fileExplorerObserver: MutationObserver;
constructor(app: App, manifest: PluginManifest) {
super(app, manifest);
@@ -90,7 +91,11 @@ export default class ExcalidrawPlugin extends Plugin {
(leaf: WorkspaceLeaf) => new ExcalidrawView(leaf, this)
);
//Compatibility mode with .excalidraw files
this.registerExtensions(["excalidraw"],VIEW_TYPE_EXCALIDRAW);
this.addMarkdownPostProcessor();
this.experimentalFileTypeDisplayToggle(this.settings.experimentalFileType);
this.registerCommands();
this.registerEventListeners();
@@ -98,6 +103,7 @@ export default class ExcalidrawPlugin extends Plugin {
//https://github.com/mgmeyers/obsidian-kanban/blob/44118e25661bff9ebfe54f71ae33805dc88ffa53/src/main.ts#L267
this.registerMonkeyPatches();
if(this.settings.loadCount<3) this.migrationNotice();
}
private migrationNotice(){
@@ -140,7 +146,7 @@ export default class ExcalidrawPlugin extends Plugin {
withBackground: this.settings.exportWithBackground,
withTheme: this.settings.exportWithTheme
}
let svg = ExcalidrawView.getSVG(JSON_parse(getJSON(content)),exportSettings);
let svg = await ExcalidrawView.getSVG(JSON_parse(getJSON(content)),exportSettings);
if(!svg) return null;
svg = ExcalidrawView.embedFontsInSVG(svg);
const img = createEl("img");
@@ -161,6 +167,8 @@ export default class ExcalidrawPlugin extends Plugin {
*/
const markdownPostProcessor = async (el:HTMLElement,ctx:MarkdownPostProcessorContext) => {
const drawings = el.querySelectorAll('.internal-embed');
if(drawings.length==0) return;
let attr:imgElementAttributes={fname:"",fheight:"",fwidth:"",style:""};
let alt:string, img:any, parts, div, file:TFile;
for (const drawing of drawings) {
@@ -220,17 +228,12 @@ export default class ExcalidrawPlugin extends Plugin {
* @returns
*/
const hoverEvent = (e:any) => {
if(!(e.event.ctrlKey||e.event.metaKey)) return;
if(!e.linktext) return;
this.hover.linkText = e.linktext;
this.hover.sourcePath = e.sourcePath;
const file = this.app.vault.getAbstractFileByPath(e.linktext);
if(file && file instanceof TFile && !this.isExcalidrawFile(file)) {
this.hover.linkText = null;
return;
if(!e.linktext) {
this.hover.linkText = null;
return;
}
this.hover.linkText = e.linktext;
this.hover.sourcePath = e.sourcePath;
};
this.registerEvent(
//@ts-ignore
@@ -239,8 +242,16 @@ export default class ExcalidrawPlugin extends Plugin {
//monitoring for div.popover.hover-popover.file-embed.is-loaded to be added to the DOM tree
this.observer = new MutationObserver((m)=>{
if(!this.hover.linkText) return;
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") {
observerForLegacyFileFormat(m,file);
return;
}
let i=0;
//@ts-ignore
while(i<m.length && m[i].target?.className!="markdown-preview-sizer markdown-preview-section") i++;
@@ -253,24 +264,96 @@ export default class ExcalidrawPlugin extends Plugin {
//@ts-ignore
if(m[i].addedNodes[0].firstElementChild?.firstElementChild?.className=="excalidraw-svg") return;
const file = this.app.metadataCache.getFirstLinkpathDest(this.hover.linkText, this.hover.sourcePath?this.hover.sourcePath:"");
if(file) {
//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"});
el.appendChild(img);
el.setAttribute("src",file.path);
el.onClickEvent((ev)=>{
ev.stopImmediatePropagation();
let src = el.getAttribute("src");
if(src) this.openDrawing(this.app.vault.getAbstractFileByPath(src) as TFile,ev.ctrlKey||ev.metaKey);
//@ts-ignore
if(!m[i].addedNodes[0].matchParent(".hover-popover")) return;
//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"});
el.appendChild(img);
el.setAttribute("src",file.path);
el.onClickEvent((ev)=>{
ev.stopImmediatePropagation();
let src = el.getAttribute("src");
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)
});
//compatibility: .excalidraw file observer
let observerForLegacyFileFormat = (m:MutationRecord[], file:TFile) => {
if(!this.hover.linkText) return;
if(m.length!=1) return;
if(m[0].addedNodes.length != 1) return;
//@ts-ignore
if(m[0].addedNodes[0].className!="popover hover-popover file-embed is-loaded") return;
const node = m[0].addedNodes[0];
node.empty();
//this div will be on top of original DIV. By stopping the propagation of the click
//I prevent the default Obsidian feature of openning the link in the native app
const 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)=>{
ev.stopImmediatePropagation();
let src = el.getAttribute("src");
if(src) this.openDrawing(this.app.vault.getAbstractFileByPath(src) as TFile,ev.ctrlKey||ev.metaKey);
});
});
node.appendChild(div);
}
this.observer.observe(document, {childList: true, subtree: true});
}
public experimentalFileTypeDisplayToggle(enabled: boolean) {
if(enabled) {
this.experimentalFileTypeDisplay();
return;
}
if(this.fileExplorerObserver) this.fileExplorerObserver.disconnect();
this.fileExplorerObserver = null;
}
private experimentalFileTypeDisplay() {
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);
}
}
});
});
m[i].addedNodes[0].insertBefore(div,m[i].addedNodes[0].firstChild)
}
});
});
this.observer.observe(document, {childList: true, subtree: true});
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);
}
}
});
this.fileExplorerObserver.observe(document.querySelector(".workspace"), {childList: true, subtree: true});
});
}
private registerCommands() {
@@ -422,6 +505,10 @@ export default class ExcalidrawPlugin extends Plugin {
checkCallback: (checking: boolean) => {
if (checking) {
return this.app.workspace.activeLeaf.view.getViewType() == VIEW_TYPE_EXCALIDRAW;
/* if(this.app.workspace.activeLeaf.view.getViewType() == VIEW_TYPE_EXCALIDRAW) {
return !(this.app.workspace.activeLeaf.view as ExcalidrawView).compatibilityMode;
}
return false;*/
} else {
const view = this.app.workspace.activeLeaf.view;
if (view instanceof ExcalidrawView) {
@@ -456,7 +543,10 @@ export default class ExcalidrawPlugin extends Plugin {
name: t("TOGGLE_LOCK"),
checkCallback: (checking: boolean) => {
if (checking) {
return this.app.workspace.activeLeaf.view.getViewType() == VIEW_TYPE_EXCALIDRAW;
if(this.app.workspace.activeLeaf.view.getViewType() == VIEW_TYPE_EXCALIDRAW) {
return !(this.app.workspace.activeLeaf.view as ExcalidrawView).compatibilityMode;
}
return false;
} else {
const view = this.app.workspace.activeLeaf.view;
if (view instanceof ExcalidrawView) {
@@ -520,6 +610,9 @@ export default class ExcalidrawPlugin extends Plugin {
const fileIsExcalidraw = this.isExcalidrawFile(activeFile);
if (checking) {
if(this.app.workspace.activeLeaf.view.getViewType() == VIEW_TYPE_EXCALIDRAW) {
return !(this.app.workspace.activeLeaf.view as ExcalidrawView).compatibilityMode;
}
return fileIsExcalidraw;
}
@@ -572,13 +665,14 @@ export default class ExcalidrawPlugin extends Plugin {
});
}
public async convertSingleExcalidrawToMD(file: TFile, replaceExtension:boolean = false, keepOriginal:boolean = false) {
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))));
console.log(fname);
await this.app.vault.create(fname,FRONTMATTER + exportSceneToMD(data));
const result = await this.app.vault.create(fname,FRONTMATTER + exportSceneToMD(data));
if (!keepOriginal) this.app.vault.delete(file);
return result;
}
public async convertExcalidrawToMD(replaceExtension:boolean = false, keepOriginal:boolean = false) {
@@ -782,6 +876,7 @@ export default class ExcalidrawPlugin extends Plugin {
onunload() {
destroyExcalidrawAutomate();
this.observer.disconnect();
if (this.fileExplorerObserver) this.fileExplorerObserver.disconnect();
const excalidrawLeaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW);
excalidrawLeaves.forEach((leaf) => {
this.setMarkdownView(leaf);
@@ -841,17 +936,27 @@ export default class ExcalidrawPlugin extends Plugin {
}
private getNextDefaultFilename():string {
return this.settings.drawingFilenamePrefix + window.moment().format(this.settings.drawingFilenameDateTime)+'.excalidraw.md';
return this.settings.drawingFilenamePrefix + window.moment().format(this.settings.drawingFilenameDateTime)
+ (this.settings.compatibilityMode ? '.excalidraw' : '.excalidraw.md');
}
private async getBlankDrawing():Promise<string> {
const template = this.app.metadataCache.getFirstLinkpathDest(normalizePath(this.settings.templateFilePath),"");
if(template && template instanceof TFile) {
const data = await this.app.vault.read(template);
if (data) return data;
if( (template.extension == "md" && !this.settings.compatibilityMode)
|| (template.extension == "excalidraw" && this.settings.compatibilityMode)) {
const data = await this.app.vault.read(template);
if (data) return data;
}
}
return FRONTMATTER + '\n# Drawing\n'+ BLANK_DRAWING;
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);
}
public async createDrawing(filename: string, onNewPane: boolean, foldername?: string, initData?:string) {
@@ -909,6 +1014,7 @@ export default class ExcalidrawPlugin extends Plugin {
}
isExcalidrawFile(f:TFile) {
if(f.extension=="excalidraw") return true;
const fileCache = this.app.metadataCache.getFileCache(f);
return !!fileCache?.frontmatter && !!fileCache.frontmatter[FRONTMATTER_KEY];
}

View File

@@ -26,6 +26,9 @@ export interface ExcalidrawSettings {
autoexportExcalidraw: boolean,
syncExcalidraw: boolean,
library: string,
compatibilityMode: boolean,
experimentalFileType: boolean,
experimentalFileTag: string,
loadCount: number, //version 1.2 migration counter
drawingOpenCount: number,
}
@@ -48,6 +51,9 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
autoexportExcalidraw: false,
syncExcalidraw: false,
library: `{"type":"excalidrawlib","version":1,"library":[]}`,
experimentalFileType: false,
experimentalFileTag: "✏️",
compatibilityMode: false,
loadCount: 0,
drawingOpenCount: 0,
}
@@ -268,6 +274,16 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.containerEl.createEl('h1', {text: t("COMPATIBILITY_HEAD")});
new Setting(containerEl)
.setName(t("COMPATIBILITY_MODE_NAME"))
.setDesc(t("COMPATIBILITY_MODE_DESC"))
.addToggle(toggle => toggle
.setValue(this.plugin.settings.compatibilityMode)
.onChange(async (value) => {
this.plugin.settings.compatibilityMode = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName(t("EXPORT_EXCALIDRAW_NAME"))
.setDesc(t("EXPORT_EXCALIDRAW_DESC"))
@@ -287,6 +303,30 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.plugin.settings.syncExcalidraw = value;
await this.plugin.saveSettings();
}));
this.containerEl.createEl('h1', {text: t("EXPERIMENTAL_HEAD")});
this.containerEl.createEl('p', {text: t("EXPERIMENTAL_DESC")});
new Setting(containerEl)
.setName(t("FILETYPE_NAME"))
.setDesc(t("FILETYPE_DESC"))
.addToggle(toggle => toggle
.setValue(this.plugin.settings.experimentalFileType)
.onChange(async (value) => {
this.plugin.settings.experimentalFileType = value;
this.plugin.experimentalFileTypeDisplayToggle(value);
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName(t("FILETAG_NAME"))
.setDesc(t("FILETAG_DESC"))
.addText(text => text
.setPlaceholder('✏️')
.setValue(this.plugin.settings.experimentalFileTag)
.onChange(async (value) => {
this.plugin.settings.experimentalFileTag = value;
await this.plugin.saveSettings();
}));
}
}

View File

@@ -882,10 +882,10 @@
"@babel/helper-validator-identifier" "^7.14.5"
"to-fast-properties" "^2.0.0"
"@excalidraw/excalidraw@^0.8.0":
"integrity" "sha512-QSCorwl2NVZr1kv6+pSfMgxwb85v7qmjW37p0n+LMWrW+VgGWQxa3LtQqTIJ8OvdLNLNfO3kN7nHXNC4Z1h3ug=="
"resolved" "https://registry.npmjs.org/@excalidraw/excalidraw/-/excalidraw-0.8.0.tgz"
"version" "0.8.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=="
@@ -7914,7 +7914,7 @@
"strip-ansi" "3.0.1"
"text-table" "0.2.0"
"react-dom@^17.0.1", "react-dom@^17.0.2":
"react-dom@^17.0.2":
"integrity" "sha512-s4h96KtLDUQlsENhMn1ar8t2bEa+q/YAtj8pPPdIjPDGBDIVNsrD9aXNWqspUe6AzKCIG0C1HZZLqLV7qpOBGA=="
"resolved" "https://registry.npmjs.org/react-dom/-/react-dom-17.0.2.tgz"
"version" "17.0.2"
@@ -7979,7 +7979,7 @@
optionalDependencies:
"fsevents" "^1.1.3"
"react@^17.0.1", "react@^17.0.2", "react@17.0.2":
"react@^17.0.2", "react@17.0.2":
"integrity" "sha512-gnhPt75i/dq/z3/6q/0asP78D0u592D5L1pd7M8P+dck6Fu/jJeL6iVVK23fptSUZj8Vjf++7wXA8UNclGQcbA=="
"resolved" "https://registry.npmjs.org/react/-/react-17.0.2.tgz"
"version" "17.0.2"