Compare commits

...

7 Commits

Author SHA1 Message Date
Zsolt Viczian
8a1cf72095 1.4.2 2021-10-28 23:55:03 +02:00
Zsolt Viczian
f02425dcac 1.4.1 2021-10-26 23:06:00 +02:00
Zsolt Viczian
6e3cf60eab 1.4.0 2021-10-24 20:40:36 +02:00
zsviczian
32fdbf9dc2 Update README.md 2021-10-24 20:29:43 +02:00
Zsolt Viczian
1aed684ebe Fixed Mac CTRL vs. CMD button issue 2021-10-24 20:07:22 +02:00
Zsolt Viczian
1ad791d9bc 1.4.0 pre-release 2 2021-10-24 13:40:11 +02:00
zsviczian
bb9925024d Merge pull request #209 from zsviczian/Image-Element
Image element
2021-10-24 06:56:12 +02:00
16 changed files with 523 additions and 235 deletions

View File

@@ -2,33 +2,17 @@ The Obsidian-Excalidraw plugin integrates [Excalidraw](https://excalidraw.com/),
![image](https://user-images.githubusercontent.com/14358394/125159831-336d6880-e17a-11eb-8a3d-ceabc2555a08.png)
# Important notice to the 1.2.0 update
This version comes with tons of new features and possibilities.
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.
## 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)||
|[![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)|[![Image Elements](https://user-images.githubusercontent.com/14358394/138607067-ccb62f92-48a4-4880-ac6e-68c1bf86ac2c.png)](https://www.youtube.com/watch?v=_c_0zpBJ4Xc&)|
# Key features
- 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.
- CTRL/CMD+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.
@@ -46,13 +30,23 @@ To convert files you have the following options:
- `![[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
- CTRL/META + ALT + SHIFT + CLICK to create the file (if it does not yet exist) and open it in a new pane
- CTRL/CMD + hover to bring up the Obsidian quick preview for the link. (On Mac it is CTRL+CMD+hover).
- CTRL/CMD + CLICK a text element to open it as a link.
- CTRL/CMD + ALT + CLICK to create the file (if it does not yet exist) and open it
- CTRL/CMD + SHIFT + CLICK to open the file in a new pane
- CTRL/CMD + ALT + SHIFT + CLICK to create the file (if it does not yet exist) and open it in a new pane
- Using the block reference you can also reference & transclude text that appears on drawings, in other documents
- 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.
- Drag & Drop support
- You can drag files from the Obsidian file explorer and they will become links to those files in Excalidraw.
- Dragging image files (PNG, SVG, JPG, Excalidraw) from obsidian files explorer while pressing the CTRL/CMD button will embed the image into your drawing.
- You can drag and drop images from outside obsidian onto Excalidraw. These images will be embedded into your drawing and saved to Obsidian.
- You can drag and drop text from Markdown views onto Excalidraw.
- You can drag and drop web addresses from your browser and they will become links.
- Image support
- On iOS and Android you can add images from your camera by pressing the add image button in Excalidraw.
- You can copy/paste images into your drawing. Images will be saved in your vault.
- You can drag and drop images as explained above.
- 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
@@ -62,18 +56,17 @@ To convert files you have the following options:
- `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/)
- Includes full [QuickAdd](https://github.com/chhoumann/quickadd), [Templater](https://silentvoid13.github.io/Templater/) and [Dataview](https://blacksmithgu.github.io/obsidian-dataview/docs/api/intro/) support through ExcalidrawAutomate. Check out the [detailed help + examples](https://zsviczian.github.io/obsidian-excalidraw-plugin/). I also have a [YouTube ExcalidrawAutomate Playlist](https://www.youtube.com/playlist?list=PL6mqgtMZ4NP1IR4nXxSlMA4PA5E-qpyHZ) with lots of examples.
- 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
- 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.
- Text elements "jumps off screen" when editing, if drawing is zoomed in and text element does not fit the visible screen area. I am working on a resolution.
# 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. 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.
- [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.
# 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.3.20",
"version": "1.4.2",
"minAppVersion": "0.12.0",
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
"author": "Zsolt Viczian",

View File

@@ -11,7 +11,7 @@
"author": "",
"license": "MIT",
"dependencies": {
"@zsviczian/excalidraw": "0.10.0-obsidian-2",
"@zsviczian/excalidraw": "0.10.0-obsidian-7",
"monkey-around": "^2.2.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",

View File

@@ -11,7 +11,7 @@ import {
JSON_parse
} from "./constants";
import { TextMode } from "./ExcalidrawView";
import { getAttachmentsFolderAndFilePath, getBinaryFileFromDataURL, wrapText } from "./Utils";
import { getAttachmentsFolderAndFilePath, getBinaryFileFromDataURL, isObsidianThemeDark, wrapText } from "./Utils";
import { ExcalidrawImageElement, ExcalidrawTextElement, FileId } from "@zsviczian/excalidraw/types/element/types";
import { BinaryFiles, SceneData } from "@zsviczian/excalidraw/types/types";
@@ -81,11 +81,26 @@ export function getSVGString(data:string):string {
let parts;
parts = res.next();
if(parts.value && parts.value.length>1) {
return parts.value[1];
return parts.value[1].replaceAll("\n","");
}
return null;
}
export function getMarkdownDrawingSection(jsonString: string,svgString: 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)
+ (svgString ? //&& this.settings.saveSVGSnapshots
'\n\n# SVG snapshot\n'
+ "==⚠ Remove all linebreaks from SVG string before use. Linebreaks were added to improve markdown view speed. ⚠==\n"
+ String.fromCharCode(96)+String.fromCharCode(96)+String.fromCharCode(96)+'html\n'
+ svgString + '\n'
+ String.fromCharCode(96)+String.fromCharCode(96)+String.fromCharCode(96)
: '')
+ '\n%%';
}
export class ExcalidrawData {
public svgSnapshot: string = null;
private textElements:Map<string,{raw:string, parsed:string}> = null;
@@ -153,6 +168,10 @@ export class ExcalidrawData {
this.scene.files = {}; //loading legacy scenes that do not yet have the files attribute.
}
if(this.plugin.settings.matchThemeAlways) {
this.scene.appState.theme = isObsidianThemeDark() ? "dark" : "light";
}
this.svgSnapshot = getSVGString(data.substr(pos+scene.length));
data = data.substring(0,pos);
@@ -215,6 +234,9 @@ export class ExcalidrawData {
if(!this.scene.files) {
this.scene.files = {}; //loading legacy scenes without the files element
}
if(this.plugin.settings.matchThemeAlways) {
this.scene.appState.theme = isObsidianThemeDark() ? "dark" : "light";
}
this.files.clear();
this.findNewTextElementsInScene();
await this.setTextMode(TextMode.raw,true); //legacy files are always displayed in raw mode.
@@ -488,7 +510,9 @@ export class ExcalidrawData {
}
outString += '\n';
}
return outString + this.plugin.getMarkdownDrawingSection(JSON.stringify(this.scene,null,"\t"),this.svgSnapshot);
const sceneJSONstring = JSON.stringify(this.scene,null,"\t");
return outString + getMarkdownDrawingSection(sceneJSONstring,this.svgSnapshot);
}
private async syncFiles(scene:SceneDataWithFiles):Promise<boolean> {

View File

@@ -20,8 +20,6 @@ import {
VIEW_TYPE_EXCALIDRAW,
ICON_NAME,
EXCALIDRAW_LIB_HEADER,
VIRGIL_FONT,
CASCADIA_FONT,
DISK_ICON_NAME,
PNG_ICON_NAME,
SVG_ICON_NAME,
@@ -39,7 +37,6 @@ import { ExcalidrawData, REG_LINKINDEX_HYPERLINK, REGEX_LINK } from "./Excalidra
import { checkAndCreateFolder, download, embedFontsInSVG, generateSVGString, getNewOrAdjacentLeaf, getNewUniqueFilepath, getPNG, getSVG, loadSceneFiles, rotatedDimensions, scaleLoadedImage, splitFolderAndFilename, svgToBase64, viewportCoordsToSceneCoords } from "./Utils";
import { Prompt } from "./Prompt";
import { ClipboardData } from "@zsviczian/excalidraw/types/clipboard";
import { ifStatement } from "@babel/types";
declare let window: ExcalidrawAutomate;
@@ -496,12 +493,6 @@ export default class ExcalidrawView extends TextFileView {
}
setMarkdownView() {
if(this.excalidrawRef) {
const el = this.excalidrawAPI.getSceneElements();
if(el.filter((e:any)=>e.type==="image").length>0) {
new Notice(t("DRAWING_CONTAINS_IMAGE"),6000);
}
}
this.plugin.excalidrawFileModes[this.id || this.file.path] = "markdown";
this.plugin.setMarkdownView(this.leaf);
}
@@ -559,7 +550,7 @@ export default class ExcalidrawView extends TextFileView {
.setIcon(PNG_ICON_NAME)
.onClick( async (ev)=> {
if(!this.getScene || !this.file) return;
if(ev.ctrlKey || ev.metaKey) {
if(ev.ctrlKey||ev.metaKey) {
const exportSettings: ExportSettings = {
withBackground: this.plugin.settings.exportWithBackground,
withTheme: this.plugin.settings.exportWithTheme
@@ -584,7 +575,7 @@ export default class ExcalidrawView extends TextFileView {
.setIcon(SVG_ICON_NAME)
.onClick(async (ev)=> {
if(!this.getScene || !this.file) return;
if(ev.ctrlKey || ev.metaKey) {
if(ev.ctrlKey||ev.metaKey) {
const exportSettings: ExportSettings = {
withBackground: this.plugin.settings.exportWithBackground,
withTheme: this.plugin.settings.exportWithTheme
@@ -785,7 +776,7 @@ export default class ExcalidrawView extends TextFileView {
const files = this.excalidrawAPI.getFiles();
if(files) {
const imgIds = el.filter((e)=>e.type=="image").map((e:any)=>e.fileId);
const imgIds = el.filter((e)=>e.type==="image").map((e:any)=>e.fileId);
const toDelete = Object.keys(files).filter((k)=>!imgIds.contains(k));
toDelete.forEach((k)=>delete files[k]);
}
@@ -829,14 +820,17 @@ export default class ExcalidrawView extends TextFileView {
let timestamp = 0;
let blockOnMouseButtonDown = false;
const getElementsAtPointer = (pointer:any, elements:ExcalidrawElement[], type:string):ExcalidrawElement[] => {
return elements.filter((e:ExcalidrawElement)=>{
if (e.type !== type) return false;
const [x,y,w,h] = rotatedDimensions(e);
return x<=pointer.x && x+w>=pointer.x
&& y<=pointer.y && y+h>=pointer.y;
});
}
const getTextElementAtPointer = (pointer:any) => {
const elements = this.excalidrawAPI.getSceneElements()
.filter((e:ExcalidrawElement)=>{
if (e.type !== "text") return false;
const [x,y,w,h] = rotatedDimensions(e);
return x<=pointer.x && x+w>=pointer.x
&& y<=pointer.y && y+h>=pointer.y;
});
const elements = getElementsAtPointer(pointer,this.excalidrawAPI.getSceneElements(),'text') as ExcalidrawTextElement[];
if(elements.length==0) return {id:null, text:null};
if(elements.length===1) return {id:elements[0].id,text:elements[0].text};
//if more than 1 text elements are at the location, look for one that has a link
@@ -857,13 +851,7 @@ export default class ExcalidrawView extends TextFileView {
}
const getImageElementAtPointer = (pointer:any) => {
const elements = this.excalidrawAPI.getSceneElements()
.filter((e:ExcalidrawElement)=>{
if (e.type !== "image") return false;
const [x,y,w,h] = rotatedDimensions(e);
return x<=pointer.x && x+w>=pointer.x
&& y<=pointer.y && y+h>=pointer.y;
});
const elements = getElementsAtPointer(pointer,this.excalidrawAPI.getSceneElements(),'image') as ExcalidrawImageElement[];
if(elements.length===0) return {id:null, fileId:null};
if(elements.length>=1) return {id:elements[0].id,fileId:elements[0].fileId};
//if more than 1 image elements are at the location, return the first
@@ -885,8 +873,6 @@ export default class ExcalidrawView extends TextFileView {
const dropAction = (transfer: DataTransfer) => {
// Return a 'copy' or 'link' action according to the content types, or undefined if no recognized type
//if (transfer.types.includes('text/uri-list')) return 'link';
let files = (this.app as any).dragManager.draggable?.files;
if(files) {
if(files[0] == this.file) {
@@ -895,20 +881,23 @@ export default class ExcalidrawView extends TextFileView {
}
}
if (['file', 'files'].includes((this.app as any).dragManager.draggable?.type)) return 'link';
if (transfer.types?.includes('text/html') || transfer.types?.includes('text/plain')) return 'copy';
if ( transfer.types?.includes('text/html')
|| transfer.types?.includes('text/plain')
|| transfer.types?.includes('Files')
) return 'copy';
}
let viewModeEnabled = false;
const handleLinkClick = () => {
selectedTextElement = getTextElementAtPointer(currentPosition);
if(selectedTextElement && selectedTextElement.id) {
const event = new MouseEvent("click", {ctrlKey: true, shiftKey: this.shiftKeyDown, altKey:this.altKeyDown});
const event = new MouseEvent("click", {ctrlKey:true, metaKey:true, shiftKey:this.shiftKeyDown, altKey:this.altKeyDown});
this.handleLinkClick(this,event);
selectedTextElement = null;
}
selectedImageElement = getImageElementAtPointer(currentPosition);
if(selectedImageElement && selectedImageElement.id) {
const event = new MouseEvent("click", {ctrlKey: true, shiftKey: this.shiftKeyDown, altKey:this.altKeyDown});
const event = new MouseEvent("click", {ctrlKey:true, metaKey:true, shiftKey:this.shiftKeyDown, altKey:this.altKeyDown});
this.handleLinkClick(this,event);
selectedImageElement = null;
}
@@ -931,11 +920,11 @@ export default class ExcalidrawView extends TextFileView {
this.zoomToFit();
}
this.ctrlKeyDown = e.ctrlKey || e.metaKey;
this.ctrlKeyDown = e.ctrlKey||e.metaKey;
this.shiftKeyDown = e.shiftKey;
this.altKeyDown = e.altKey;
if(e.ctrlKey && !e.shiftKey && !e.altKey) { // && !e.metaKey) {
if((e.ctrlKey||e.metaKey) && !e.shiftKey && !e.altKey) {
const selectedElement = getTextElementAtPointer(currentPosition);
if(!selectedElement) return;
@@ -974,12 +963,11 @@ export default class ExcalidrawView extends TextFileView {
}
},
onKeyUp: (e:any) => {
this.ctrlKeyDown = e.ctrlKey || e.metaKey;
this.ctrlKeyDown = e.ctrlKey||e.metaKey;
this.shiftKeyDown = e.shiftKey;
this.altKeyDown = e.altKey;
},
onClick: (e:MouseEvent):any => {
//@ts-ignore
if(!(e.ctrlKey||e.metaKey)) return;
if(!(this.plugin.settings.allowCtrlClick)) return;
if(!(this.getSelectedTextElement().id || this.getSelectedImageElement().id)) return;
@@ -1022,7 +1010,7 @@ export default class ExcalidrawView extends TextFileView {
currentPosition = p.pointer;
if(hoverPreviewTarget && (Math.abs(hoverPoint.x-p.pointer.x)>50 || Math.abs(hoverPoint.y-p.pointer.y)>50)) clearHoverPreview();
if(!viewModeEnabled) return;
const buttonDown = !blockOnMouseButtonDown && p.button === "down";
if(buttonDown) {
blockOnMouseButtonDown = true;
@@ -1112,7 +1100,7 @@ export default class ExcalidrawView extends TextFileView {
switch(draggable?.type) {
case "file":
if (!onDropHook("file",[draggable.file],null)) {
if((event.ctrlKey || event.metaKey)
if((event.ctrlKey||event.metaKey)
&& (IMAGE_TYPES.contains(draggable.file.extension)
|| this.plugin.isExcalidrawFile(draggable.file))) {
const f = draggable.file;
@@ -1143,6 +1131,33 @@ export default class ExcalidrawView extends TextFileView {
const text:string = event.dataTransfer.getData("text");
if(!text) return true;
if (!onDropHook("text",null,text)) {
if(this.plugin.settings.iframelyAllowed && text.match(/^https?:\/\/\S*$/)) {
let linkAdded = false;
const self = this;
ajaxPromise({
url: `http://iframely.server.crestify.com/iframely?url=${text}`
}).then((res) => {
if(!res || linkAdded) return false;
linkAdded = true;
const data = JSON.parse(res);
if(!data || !(data.meta?.title)) {
this.addText(text);
return false;
}
this.addText(`[${data.meta.title}](${text})`);
return false;
},()=>{
if(linkAdded) return false;
linkAdded = true;
self.addText(text)
});
setTimeout(()=>{
if(linkAdded) return;
linkAdded = true;
self.addText(text)
},600);
return false;
}
this.addText(text.replace(/(!\[\[.*#[^\]]*\]\])/g,"$1{40}"));
}
return false;
@@ -1210,13 +1225,14 @@ export default class ExcalidrawView extends TextFileView {
public zoomToFit(delay:boolean = true) {
if(!this.excalidrawRef) return;
const maxZoom = this.plugin.settings.zoomToFitMaxLevel;
const current = this.excalidrawAPI;
const fullscreen = (document.fullscreenElement==this.contentEl);
const elements = current.getSceneElements();
if(delay) { //time for the DOM to render, I am sure there is a more elegant solution
setTimeout(() => current.zoomToFit(elements,2,fullscreen?0:0.05),100);
setTimeout(() => current.zoomToFit(elements,maxZoom,fullscreen?0:0.05),100);
} else {
current.zoomToFit(elements,2,fullscreen?0:0.05);
current.zoomToFit(elements,maxZoom,fullscreen?0:0.05);
}
}
}

53
src/InsertImageDialog.ts Normal file
View File

@@ -0,0 +1,53 @@
import {
App,
FuzzySuggestModal,
TFile
} from "obsidian";
import { IMAGE_TYPES } from "./constants";
import { ExcalidrawAutomate } from "./ExcalidrawAutomate";
import ExcalidrawView from "./ExcalidrawView";
import {t} from './lang/helpers'
declare let window: ExcalidrawAutomate;
export class InsertImageDialog extends FuzzySuggestModal<TFile> {
public app: App;
private view: ExcalidrawView;
constructor(app: App) {
super(app);
this.app = app;
this.limit = 20;
this.setInstructions([{
command: t("SELECT_FILE"),
purpose: "",
}]);
this.setPlaceholder(t("SELECT_DRAWING"));
this.emptyStateText = t("NO_MATCH");
}
getItems(): TFile[] {
return (this.app.vault.getFiles() || []).filter((f:TFile) => IMAGE_TYPES.contains(f.extension));
}
getItemText(item: TFile): string {
return item.path;
}
onChooseItem(item: TFile, _evt: MouseEvent | KeyboardEvent): void {
const ea = window.ExcalidrawAutomate;
ea.reset();
ea.setView(this.view);
(async () => {
await ea.addImage(0,0,item);
ea.addElementsToView(true,false);
})();
}
public start(view: ExcalidrawView) {
this.view = view;
this.open();
}
}

View File

@@ -1,54 +0,0 @@
import { App, Modal } from "obsidian";
import { t } from "./lang/helpers";
import ExcalidrawPlugin from "./main";
export class MigrationPrompt extends Modal {
private plugin: ExcalidrawPlugin;
constructor(app: App, plugin:ExcalidrawPlugin) {
super(app);
this.plugin = plugin;
}
onOpen(): void {
this.titleEl.setText("Welcome to Excalidraw 1.2");
this.createForm();
}
onClose(): void {
this.contentEl.empty();
}
createForm(): void {
const div = this.contentEl.createDiv();
div.addClass("excalidraw-prompt-div");
div.style.maxWidth = "600px";
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 = "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 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>" +
"<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"});
bConvert.onclick = (ev)=>{
this.plugin.convertExcalidrawToMD();
this.close();
};
const bCancel = div.createEl('button', {text: "CANCEL"});
bCancel.onclick = (ev)=>{
this.close();
};
}
}

203
src/OneOffs.ts Normal file
View File

@@ -0,0 +1,203 @@
import { App, Modal, Notice, TFile } from "obsidian";
import { getJSON } from "./ExcalidrawData";
import ExcalidrawPlugin from "./main";
export class OneOffs {
private plugin:ExcalidrawPlugin
constructor(plugin: ExcalidrawPlugin) {
this.plugin = plugin;
}
public patchCommentBlock() {
//This is a once off cleanup process to remediate incorrectly placed comment %% before # Text Elements
if(!this.plugin.settings.patchCommentBlock) return;
const plugin = this.plugin;
console.log(window.moment().format("HH:mm:ss") + ": Excalidraw will patch drawings in 5 minutes");
setTimeout(async ()=>{
await plugin.loadSettings();
if (!plugin.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 = plugin.app.vault.getFiles();
for (const f of (excalidrawFiles || []).filter((f:TFile) => plugin.isExcalidrawFile(f))) {
if ( (f.extension !== "excalidraw") //legacy files do not need to be touched
&& (plugin.app.workspace.getActiveFile() !== f)) { //file is currently being edited
let drawing = await plugin.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 plugin.app.vault.modify(f,drawing);
}
}
}
plugin.settings.patchCommentBlock = false;
plugin.saveSettings();
console.log(window.moment().format("HH:mm:ss") + ": Excalidraw patched in total " + i + " files");
},300000) //5 minutes
}
public migrationNotice () {
if(this.plugin.settings.loadCount>0) return;
const plugin = this.plugin;
plugin.app.workspace.onLayoutReady(async () => {
plugin.settings.loadCount++;
plugin.saveSettings();
const files = plugin.app.vault.getFiles().filter((f)=>f.extension==="excalidraw");
if(files.length>0) {
const prompt = new MigrationPrompt(plugin.app, plugin);
prompt.open();
}
});
}
public imageElementLaunchNotice () {
if(!this.plugin.settings.imageElementNotice) return;
const plugin = this.plugin;
plugin.app.workspace.onLayoutReady(async () => {
const prompt = new ImageElementNotice(plugin.app, plugin);
prompt.open();
});
}
}
class MigrationPrompt extends Modal {
private plugin: ExcalidrawPlugin;
constructor(app: App, plugin:ExcalidrawPlugin) {
super(app);
this.plugin = plugin;
}
onOpen(): void {
this.titleEl.setText("Welcome to Excalidraw 1.2");
this.createForm();
}
onClose(): void {
this.contentEl.empty();
}
createForm(): void {
const div = this.contentEl.createDiv();
// div.addClass("excalidraw-prompt-div");
// div.style.maxWidth = "600px";
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 = "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 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>" +
"<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"});
bConvert.onclick = (ev)=>{
this.plugin.convertExcalidrawToMD();
this.close();
};
const bCancel = div.createEl('button', {text: "CANCEL"});
bCancel.onclick = (ev)=>{
this.close();
};
}
}
class ImageElementNotice extends Modal {
private plugin: ExcalidrawPlugin;
private saveChanges: boolean = false;
constructor(app: App, plugin:ExcalidrawPlugin) {
super(app);
this.plugin = plugin;
}
onOpen(): void {
this.titleEl.setText("Image Elements have arrived!");
this.createForm();
}
async onClose() {
this.contentEl.empty();
if(!this.saveChanges) return;
await this.plugin.loadSettings();
this.plugin.settings.imageElementNotice = false;
this.plugin.saveSettings();
}
createForm(): void {
const div = this.contentEl.createDiv();
//div.addClass("excalidraw-prompt-div");
//div.style.maxWidth = "600px";
div.createEl('p',{text: ""},(el) => {
el.innerHTML = "Welcome to Obsidian-Excalidraw 1.4! I've added Image Elements. "
+ "Please watch the video below to learn how to use this new feature.";
});
div.createEl('p',{text: ""}, (el) => {
el.innerHTML = "<u>⚠ WARNING:</u> Opening new drawings with an older version of the plugin will lead to loss of images. "
+ "Update the plugin on all your devices.";
});
div.createEl('p',{text: ""}, (el) => {
el.innerHTML = "Since March, I have spent most of my free time building this plugin. Close to 75 workdays worth of my time (assuming 8-hour days). "
+ "Some of you have already bought me a coffee. THANK YOU! Your support really means a lot to me! If you have not yet done so, please consider clicking the button below.";
});
const coffeeDiv = div.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;
div.createEl('p',{text: ""}, (el) => {//files manually follow one of two options:
el.style.textAlign = "center";
el.innerHTML = '<iframe width="560" height="315" src="https://www.youtube.com/embed/_c_0zpBJ4Xc?start=20" title="YouTube video player" '
+'frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" '
+ 'allowfullscreen></iframe>';
});
div.createEl('p',{text: ""}, (el) => {//files manually follow one of two options:
el.style.textAlign = "right";
const bOk = el.createEl('button', {text: "OK - Don't show this again"});
bOk.onclick = (ev)=>{
this.saveChanges = true;
this.close();
}
const bCancel = el.createEl('button', {text: "CANCEL - Read next time"});
bCancel.onclick = (ev)=>{
this.saveChanges = false;
this.close();
};
});
}
}

View File

@@ -9,7 +9,7 @@ import ExcalidrawPlugin from "./main";
import { ExcalidrawElement, FileId } from "@zsviczian/excalidraw/types/element/types";
import { ExportSettings } from "./ExcalidrawView";
import { ExcalidrawSettings } from "./settings";
import { html_beautify } from "js-beautify"
import { html_beautify } from "js-beautify";
declare module "obsidian" {
interface Workspace {
@@ -326,9 +326,8 @@ export const generateSVGString = async (scene:any, settings: ExcalidrawSettings)
withTheme: settings.exportWithTheme
}
const svg = await getSVG(scene,exportSettings);
if(svg) {
return html_beautify(svg.outerHTML,{"indent_with_tabs": true});
if(svg) {
return wrapText(html_beautify(svg.outerHTML,{"indent_with_tabs": true}),4096,true);// html_beautify(svg.outerHTML,{"indent_with_tabs": true});
}
return null;
}
@@ -413,4 +412,6 @@ export const scaleLoadedImage = (scene:any, files:any):[boolean,any] => {
});
return [dirty,scene];
}
}
}
export const isObsidianThemeDark = () => document.body.classList.contains("theme-dark");

View File

@@ -3,8 +3,8 @@ export function JSON_parse(x:string):any {return JSON.parse(x.replaceAll("&#91;"
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 IMAGE_TYPES = ['jpeg', 'jpg', 'png', 'gif', 'svg'];
export const MAX_IMAGE_SIZE = 500;
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";

View File

@@ -23,18 +23,19 @@ export default {
EXPORT_PNG: "Save as PNG next to the current file",
TOGGLE_LOCK: "Toggle Text Element edit RAW/PREVIEW",
INSERT_LINK: "Insert link to file",
INSERT_IMAGE: "Insert image from vault",
INSERT_LATEX: "Insert LaTeX-symbol (e.g. $\\theta$)",
ENTER_LATEX: "Enter a valid LaTeX expression",
//ExcalidrawView.ts
OPEN_AS_MD: "Open as Markdown",
SAVE_AS_PNG: "Save as PNG into Vault (CTRL/META+CLICK to export)",
SAVE_AS_SVG: "Save as SVG into Vault (CTRL/META+CLICK to export)",
SAVE_AS_PNG: "Save as PNG into Vault (CTRL/CMD+CLICK to export)",
SAVE_AS_SVG: "Save as SVG into Vault (CTRL/CMD+CLICK to export)",
OPEN_LINK: "Open selected text as link\n(SHIFT+CLICK to open in a new pane)",
EXPORT_EXCALIDRAW: "Export to an .Excalidraw file",
LINK_BUTTON_CLICK_NO_TEXT: 'Select a an ImageElement, or select a TextElement that contains an internal or external link.\n'+
'SHIFT CLICK this button to open the link in a new pane.\n'+
'CTRL/META CLICK the Image or TextElement on the canvas has the same effect!',
'CTRL/CMD CLICK the Image or TextElement on the canvas has the same effect!',
TEXT_ELEMENT_EMPTY: "No ImageElement is selected or TextElement is empty, or [[valid-link|alias]] or [alias](valid-link) is not found",
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.",
@@ -44,8 +45,6 @@ export default {
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",
@@ -71,21 +70,30 @@ 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",
/*SVG_IN_MD_NAME: "SVG Snapshot to markdown file",
SVG_IN_MD_DESC: "If the switch is 'on' Excalidraw will include an SVG snapshot in the markdown file. "+
"When SVG snapshots are saved to the Excalidraw.md file, drawings that include large png, jpg, gif images may take extreme long time to open in markdown view. " +
"On the other hand, SVG snapshots provide some level of platform independence and longevity to your drawings. Even if Excalidraw will no longer exist, the snapshot " +
"can be opened with an app that reads SVGs. In addition hover previews will be less resource intensive if SVG snapshots are enabled.",*/
DISPLAY_HEAD: "Display",
MATCH_THEME_NAME: "New drawing to match Obsidian theme",
MATCH_THEME_DESC: "If theme is dark, new drawing will be created in dark mode. This does not apply when you use a template for new drawings. " +
"Also this will not effect when you open an existing drawing. Those will follow the theme of the template/drawing respectively.",
MATCH_THEME_ALWAYS_NAME: "Existing drawings to match Obsidian theme",
MATCH_THEME_ALWAYS_DESC: "If theme is dark, drawings will be opened in dark mode. If your theme is light, they will be opened in light mode. ",
ZOOM_TO_FIT_NAME: "Zoom to fit on view resize",
ZOOM_TO_FIT_DESC: "Zoom to fit drawing when the pane is resized",
ZOOM_TO_FIT_MAX_LEVEL_NAME: "Zoom to fit max ZOOM level",
ZOOM_TO_FIT_MAX_LEVEL_DESC: "Set the maximum level to which zoom to fit will enlarge the drawing. Minimum is 0.5 (50%) and maximum is 10 (1000%).",
LINKS_HEAD: "Links and transclusion",
LINKS_DESC: "CTRL/META + CLICK on Text Elements to open them as links. " +
LINKS_DESC: "CTRL/CMD + 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 " +
"the plugin will open it in a browser. " +
"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]].",
ADJACENT_PANE_NAME: "Open in adjacent pane",
ADJACENT_PANE_DESC: "When CTRL+SHIFT clicking a link in Excalidraw by default the plugin will open the link in a new pane. " +
ADJACENT_PANE_DESC: "When CTRL/CMD+SHIFT clicking a link in Excalidraw by default the plugin will open the link in a new pane. " +
"Turning this setting on, Excalidraw will first look for an existing adjacent pane, and try to open the link there. " +
"Excalidraw will first look too the right, then to the left, then down, then up. If no pane is found, Excalidraw will open " +
"a new pane.",
@@ -101,7 +109,7 @@ export default {
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_NAME: "CTRL/CMD + 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",
@@ -111,6 +119,8 @@ export default {
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.",
GET_URL_TITLE_NAME: "Use iframely to resolve page title",
GET_URL_TITLE_DESC: "Use the http://iframely.server.crestify.com/iframely?url= to get title of page when dropping a link into Excalidraw",
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.",
@@ -163,7 +173,8 @@ export default {
//openDrawings.ts
SELECT_FILE: "Select a file then press enter.",
NO_MATCH: "No file matches your query.",
SELECT_FILE_TO_LINK: "Select the file you want to insert the link for.",
SELECT_FILE_TO_LINK: "Select the file you want to insert the link for.",
SELECT_DRAWING: "Select the drawing you want to insert",
TYPE_FILENAME: "Type name of drawing to select.",
SELECT_FILE_OR_TYPE_NEW: "Select existing drawing or type name of a new drawing then press Enter.",
SELECT_TO_EMBED: "Select the drawing to insert into active document.",

View File

@@ -29,13 +29,13 @@ export default {
//ExcalidrawView.ts
OPEN_AS_MD: "打开为 Markdown 文件",
SAVE_AS_PNG: "保存成 PNG 文件到库里CTRL/META 加左键点击来指定导出位置)",
SAVE_AS_SVG: "保存成 SVG 文件到库里CTRL/META 加左键点击来指定导出位置)",
SAVE_AS_PNG: "保存成 PNG 文件到库里CTRL/CMD 加左键点击来指定导出位置)",
SAVE_AS_SVG: "保存成 SVG 文件到库里CTRL/CMD 加左键点击来指定导出位置)",
OPEN_LINK: "以链接的方式打开文本 \n按住 SHIFT 来在新面板中打开)",
EXPORT_EXCALIDRAW: "导出为 .Excalidraw 文件",
LINK_BUTTON_CLICK_NO_TEXT: '选择带有外部链接或内部链接的文本。\n'+
'SHIFT 加左键点击按钮来在新面板中打开链接。\n'+
'CTRL/META 加左键在画布中点击文本元素也可以打开对应的链接。',
'CTRL/CMD 加左键在画布中点击文本元素也可以打开对应的链接。',
TEXT_ELEMENT_EMPTY: "文本元素没有链接任何东西.",
FILENAME_INVALID_CHARS: '文件名不能包含以下符号: * " \\ < > : | ?',
FILE_DOES_NOT_EXIST: "文件不存在。按住 ALT或者 ALT + SHIFT加左键点击来创建新文件。",
@@ -71,7 +71,7 @@ export default {
FILENAME_DATE_NAME: "文件名日期",
FILENAME_DATE_DESC: "文件名的第二部分",
LINKS_HEAD: "链接",
LINKS_DESC: "CTRL/META 加左键点击文本元素来打开链接。" +
LINKS_DESC: "CTRL/CMD 加左键点击文本元素来打开链接。" +
"如果选中的文本指向多个双链,只会打开其中第一个。" +
"如果选中的文本为超链接 (i.e. https:// or http://),然后" +
"插件会在浏览器中打开超链接。" +
@@ -85,7 +85,7 @@ export default {
LINK_PREFIX_DESC:"在预览(锁定)模式,如果文本元素包含链接,在文本之前加上这些字符。" +
"你可以在文件的 Frontmatter 中加入 \'" + FRONTMATTER_KEY_CUSTOM_PREFIX +
': "👉 "\' 单独更改',
LINK_CTRL_CLICK_NAME: "CTRL 加左键点击文本来打开链接",
LINK_CTRL_CLICK_NAME: "CTRL/CMD 加左键点击文本来打开链接",
LINK_CTRL_CLICK_DESC: "如果此功能干扰了您要使用的 Excalidraw 功能,您可以将其关闭。 如果" +
"关闭此选项,则只有绘图标题栏中的链接按钮可以让你打开链接。",
EMBED_HEAD: "嵌入 & 导出",

View File

@@ -35,7 +35,7 @@ import {
DARK_BLANK_DRAWING
} from "./constants";
import ExcalidrawView, {ExportSettings, TextMode} from "./ExcalidrawView";
import {getJSON, getSVGString} from "./ExcalidrawData";
import {getJSON, getMarkdownDrawingSection, getSVGString} from "./ExcalidrawData";
import {
ExcalidrawSettings,
DEFAULT_SETTINGS,
@@ -48,6 +48,9 @@ import {
import {
InsertLinkDialog
} from "./InsertLinkDialog";
import {
InsertImageDialog
} from "./InsertImageDialog";
import {
initExcalidrawAutomate,
destroyExcalidrawAutomate
@@ -55,8 +58,8 @@ import {
import { Prompt } from "./Prompt";
import { around } from "monkey-around";
import { t } from "./lang/helpers";
import { MigrationPrompt } from "./MigrationPrompt";
import { checkAndCreateFolder, download, embedFontsInSVG, generateSVGString, getAttachmentsFolderAndFilePath, getIMGPathFromExcalidrawFile, getNewUniqueFilepath, getPNG, getSVG, splitFolderAndFilename, svgToBase64 } from "./Utils";
import { checkAndCreateFolder, download, embedFontsInSVG, generateSVGString, getAttachmentsFolderAndFilePath, getIMGPathFromExcalidrawFile, getNewUniqueFilepath, getPNG, getSVG, isObsidianThemeDark, splitFolderAndFilename, svgToBase64 } from "./Utils";
import { OneOffs } from "./OneOffs";
declare module "obsidian" {
interface App {
@@ -73,6 +76,7 @@ export default class ExcalidrawPlugin extends Plugin {
public settings: ExcalidrawSettings;
private openDialog: OpenFileDialog;
private insertLinkDialog: InsertLinkDialog;
private insertImageDialog: InsertImageDialog;
private activeExcalidrawView: ExcalidrawView = null;
public lastActiveExcalidrawFilePath: string = null;
public hover: {linkText: string, sourcePath: string} = {linkText: null, sourcePath: null};
@@ -106,53 +110,24 @@ export default class ExcalidrawPlugin extends Plugin {
this.experimentalFileTypeDisplayToggle(this.settings.experimentalFileType);
this.registerCommands();
this.registerEventListeners();
//inspiration taken from kanban:
//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
if(!this.app.isMobile) {
const electron:string = process?.versions?.electron;
if(electron && 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);
}
}
const patches = new OneOffs(this);
patches.migrationNotice();
patches.patchCommentBlock();
patches.imageElementLaunchNotice();
this.switchToExcalidarwAfterLoad()
}
private switchToExcalidarwAfterLoad() {
@@ -169,19 +144,6 @@ export default class ExcalidrawPlugin extends Plugin {
});
}
private migrationNotice(){
const self = this;
this.app.workspace.onLayoutReady(async () => {
self.settings.loadCount++;
self.saveSettings();
const files = this.app.vault.getFiles().filter((f)=>f.extension=="excalidraw");
if(files.length>0) {
const prompt = new MigrationPrompt(self.app, self);
prompt.open();
}
});
}
/**
* Displays a transcluded .excalidraw image in markdown preview mode
*/
@@ -453,6 +415,7 @@ export default class ExcalidrawPlugin extends Plugin {
private registerCommands() {
this.openDialog = new OpenFileDialog(this.app, this);
this.insertLinkDialog = new InsertLinkDialog(this.app);
this.insertImageDialog = new InsertImageDialog(this.app);
this.addRibbonIcon(ICON_NAME, t("CREATE_NEW"), async (e) => {
this.createDrawing(this.getNextDefaultFilename(), e.ctrlKey||e.metaKey);
@@ -695,6 +658,24 @@ export default class ExcalidrawPlugin extends Plugin {
},
});
this.addCommand({
id: "insert-image",
name: t("INSERT_IMAGE"),
checkCallback: (checking: boolean) => {
if (checking) {
const view = this.app.workspace.activeLeaf.view;
return (view instanceof ExcalidrawView);
} else {
const view = this.app.workspace.activeLeaf.view;
if (view instanceof ExcalidrawView) {
this.insertImageDialog.start(view);
return true;
}
else return false;
}
},
});
this.addCommand({
id: "insert-LaTeX-symbol",
name: t("INSERT_LATEX"),
@@ -987,17 +968,22 @@ export default class ExcalidrawPlugin extends Plugin {
//save Excalidraw leaf and update embeds when switching to another leaf
const activeLeafChangeEventHandler = async (leaf:WorkspaceLeaf) => {
const activeExcalidrawView = self.activeExcalidrawView;
const newActiveview:ExcalidrawView = (leaf.view instanceof ExcalidrawView) ? leaf.view as ExcalidrawView : null;
if(activeExcalidrawView && activeExcalidrawView != newActiveview) {
await activeExcalidrawView.save(false);
if(activeExcalidrawView.file) {
self.triggerEmbedUpdates(activeExcalidrawView.file.path);
}
}
const newActiveview:ExcalidrawView = (leaf.view instanceof ExcalidrawView) ? leaf.view : null;
self.activeExcalidrawView = newActiveview;
if(newActiveview) {
self.lastActiveExcalidrawFilePath = newActiveview.file?.path;
}
if(activeExcalidrawView && activeExcalidrawView != newActiveview) {
if(activeExcalidrawView.leaf != leaf) {
//if loading new view to same leaf then don't save. Excalidarw view will take care of saving anyway.
//avoid double saving
await activeExcalidrawView.save(false);
}
if(activeExcalidrawView.file) {
self.triggerEmbedUpdates(activeExcalidrawView.file.path);
}
}
};
self.registerEvent(
self.app.workspace.on("active-leaf-change",activeLeafChangeEventHandler)
@@ -1104,24 +1090,10 @@ export default class ExcalidrawPlugin extends Plugin {
}
}
if (this.settings.compatibilityMode) {
return this.settings.matchTheme && document.body.classList.contains("theme-dark") ? DARK_BLANK_DRAWING : BLANK_DRAWING;
return this.settings.matchTheme && isObsidianThemeDark() ? DARK_BLANK_DRAWING : BLANK_DRAWING;
}
const blank = this.settings.matchTheme && document.body.classList.contains("theme-dark") ? DARK_BLANK_DRAWING : BLANK_DRAWING;
return FRONTMATTER + '\n' + this.getMarkdownDrawingSection(blank,'<SVG></SVG>');
}
public getMarkdownDrawingSection(jsonString: string,svgString: 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)
+ (svgString ?
'\n\n# SVG snapshot\n'
+ String.fromCharCode(96)+String.fromCharCode(96)+String.fromCharCode(96)+'html\n'
+ svgString + '\n'
+ String.fromCharCode(96)+String.fromCharCode(96)+String.fromCharCode(96)
: '')
+ '\n%%';
const blank = this.settings.matchTheme && isObsidianThemeDark() ? DARK_BLANK_DRAWING : BLANK_DRAWING;
return FRONTMATTER + '\n' + getMarkdownDrawingSection(blank,'<SVG></SVG>');
}
/**
@@ -1147,7 +1119,7 @@ export default class ExcalidrawPlugin extends Plugin {
}
outString += te.text+' ^'+id+'\n\n';
}
return outString + this.getMarkdownDrawingSection(JSON.stringify(JSON_parse(data),null,"\t"),svgString);
return outString + getMarkdownDrawingSection(JSON.stringify(JSON_parse(data),null,"\t"),svgString);
}
public async createDrawing(filename: string, onNewPane: boolean, foldername?: string, initData?:string):Promise<string> {
@@ -1166,10 +1138,17 @@ export default class ExcalidrawPlugin extends Plugin {
}
public async setMarkdownView(leaf: WorkspaceLeaf) {
const state=leaf.view.getState();
await leaf.setViewState({
type:VIEW_TYPE_EXCALIDRAW,
state: {file:null}
});
await leaf.setViewState(
{
type: "markdown",
state: leaf.view.getState(),
state: state,
popstate: true,
} as ViewState,
{ focus: true }

View File

@@ -15,10 +15,13 @@ export interface ExcalidrawSettings {
templateFilePath: string,
drawingFilenamePrefix: string,
drawingFilenameDateTime: string,
// saveSVGSnapshots: boolean,
//displaySVGInPreview: boolean,
width: string,
matchTheme: boolean,
matchThemeAlways: boolean,
zoomToFitOnResize: boolean,
zoomToFitMaxLevel: number,
openInAdjacentPane: boolean,
showLinkBrackets: boolean,
linkPrefix: string,
@@ -26,6 +29,7 @@ export interface ExcalidrawSettings {
allowCtrlClick: boolean, //if disabled only the link button in the view header will open links
forceWrap: boolean,
pageTransclusionCharLimit: number,
iframelyAllowed: boolean,
pngExportScale: number,
exportWithTheme: boolean,
exportWithBackground: boolean,
@@ -42,6 +46,7 @@ export interface ExcalidrawSettings {
drawingOpenCount: number,
library: string,
patchCommentBlock: boolean, //1.3.12
imageElementNotice: boolean, //1.4.0
}
export const DEFAULT_SETTINGS: ExcalidrawSettings = {
@@ -49,10 +54,13 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
templateFilePath: 'Excalidraw/Template.excalidraw',
drawingFilenamePrefix: 'Drawing ',
drawingFilenameDateTime: 'YYYY-MM-DD HH.mm.ss',
// saveSVGSnapshots: true,
//displaySVGInPreview: true,
width: '400',
matchTheme: false,
matchThemeAlways: false,
zoomToFitOnResize: true,
zoomToFitMaxLevel: 2,
linkPrefix: "📍",
urlPrefix: "🌐",
openInAdjacentPane: false,
@@ -60,6 +68,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
allowCtrlClick: true,
forceWrap: false,
pageTransclusionCharLimit: 200,
iframelyAllowed: true,
pngExportScale: 1,
exportWithTheme: true,
exportWithBackground: true,
@@ -76,6 +85,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
drawingOpenCount: 0,
library: `{"type":"excalidrawlib","version":1,"library":[]}`,
patchCommentBlock: true,
imageElementNotice: true,
}
export class ExcalidrawSettingTab extends PluginSettingTab {
@@ -192,6 +202,17 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
}));
/* new Setting(containerEl)
.setName(t("SVG_IN_MD_NAME"))
.setDesc(t("SVG_IN_MD_DESC"))
.addToggle(toggle => toggle
.setValue(this.plugin.settings.saveSVGSnapshots)
.onChange(async (value) => {
this.plugin.settings.saveSVGSnapshots = value;
this.applySettingsUpdate();
}));*/
this.containerEl.createEl('h1', {text: t("DISPLAY_HEAD")});
new Setting(containerEl)
@@ -204,6 +225,16 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
}));
new Setting(containerEl)
.setName(t("MATCH_THEME_ALWAYS_NAME"))
.setDesc(t("MATCH_THEME_ALWAYS_DESC"))
.addToggle(toggle => toggle
.setValue(this.plugin.settings.matchThemeAlways)
.onChange(async (value) => {
this.plugin.settings.matchThemeAlways = value;
this.applySettingsUpdate();
}));
new Setting(containerEl)
.setName(t("ZOOM_TO_FIT_NAME"))
.setDesc(t("ZOOM_TO_FIT_DESC"))
@@ -214,6 +245,27 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
}));
let zoomText:HTMLDivElement;
new Setting(containerEl)
.setName(t("ZOOM_TO_FIT_MAX_LEVEL_NAME"))
.setDesc(t("ZOOM_TO_FIT_MAX_LEVEL_DESC"))
.addSlider(slider => slider
.setLimits(0.5,10,0.5)
.setValue(this.plugin.settings.zoomToFitMaxLevel)
.onChange(async (value)=> {
zoomText.innerText = " " + value.toString();
this.plugin.settings.zoomToFitMaxLevel = value;
this.applySettingsUpdate();
}))
.settingEl.createDiv('',(el)=>{
zoomText = el;
el.style.minWidth = "2.3em";
el.style.textAlign = "right";
el.innerText = " " + this.plugin.settings.zoomToFitMaxLevel.toString();
});
this.containerEl.createEl('h1', {text: t("LINKS_HEAD")});
this.containerEl.createEl('p',{
text: t("LINKS_DESC")});
@@ -305,6 +357,16 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate(true);
}));
new Setting(containerEl)
.setName(t("GET_URL_TITLE_NAME"))
.setDesc(t("GET_URL_TITLE_DESC"))
.addToggle(toggle => toggle
.setValue(this.plugin.settings.iframelyAllowed)
.onChange(async (value) => {
this.plugin.settings.iframelyAllowed = value;
this.applySettingsUpdate();
}));
this.containerEl.createEl('h1', {text: t("EMBED_HEAD")});
//Removed in 1.4.0 when implementing ImageElement.

View File

@@ -1,3 +1,3 @@
{
"1.3.20": "0.11.13"
"1.4.2": "0.11.13"
}

View File

@@ -1067,10 +1067,10 @@
dependencies:
"@types/estree" "*"
"@zsviczian/excalidraw@0.10.0-obsidian-2":
"integrity" "sha512-H9w7cB0ZgQIHujMB7Zwz82zoZl85ZGDtmxkX9swrPJXYcrJjx5j4oNqEK+dUSYwUlnN2iycdX9l93MjXjAK0+A=="
"resolved" "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.10.0-obsidian-2.tgz"
"version" "0.10.0-obsidian-2"
"@zsviczian/excalidraw@0.10.0-obsidian-7":
"integrity" "sha512-PkbuZLPplGxtrWmno5N16Q4EvUSfNN6aLNvLMh8k2SLEi/ADMHtdh9h/BHNcK78+oQK4H4koeHuPsLCtpz2lXQ=="
"resolved" "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.10.0-obsidian-7.tgz"
"version" "0.10.0-obsidian-7"
"abab@^1.0.3":
"integrity" "sha1-X6rZwsB/YN12dw9xzwJbYqY8/U4="