Compare commits
161 Commits
PDF-export
...
inside-arr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6e60df0b47 | ||
|
|
e574d84b84 | ||
|
|
8f3ace89ea | ||
|
|
e4e4a07aa8 | ||
|
|
7a90bf753f | ||
|
|
6221d985ac | ||
|
|
41065ce9f9 | ||
|
|
351977f0d3 | ||
|
|
01b0b64a08 | ||
|
|
938e93cc43 | ||
|
|
cebcd2b43c | ||
|
|
80b6e30040 | ||
|
|
6e92a6a399 | ||
|
|
992ae8b238 | ||
|
|
5cd07e7766 | ||
|
|
07817a4d2d | ||
|
|
a22bb4c58c | ||
|
|
43e00a51be | ||
|
|
049b5bfa85 | ||
|
|
743afa73b4 | ||
|
|
6469eec051 | ||
|
|
9f46821a41 | ||
|
|
1fb3a47bdc | ||
|
|
bcd0cdda65 | ||
|
|
207fea3f57 | ||
|
|
e55ba3cc21 | ||
|
|
71c87a7630 | ||
|
|
e598a91f43 | ||
|
|
972fe1baea | ||
|
|
d7e1268afa | ||
|
|
7a3b937ea7 | ||
|
|
c850cd15ae | ||
|
|
e9f70fd09e | ||
|
|
2083443dfe | ||
|
|
69d9b8c1c9 | ||
|
|
65f4c9f3b3 | ||
|
|
b89a106523 | ||
|
|
6434a6e58a | ||
|
|
68180db2aa | ||
|
|
63505d17e9 | ||
|
|
0851b45977 | ||
|
|
16332a3e83 | ||
|
|
8240d87fa8 | ||
|
|
a7db044715 | ||
|
|
339c274f1b | ||
|
|
d5a19cbc09 | ||
|
|
400cffcd01 | ||
|
|
e5438c1e56 | ||
|
|
7e2ef3f115 | ||
|
|
ad091df4d9 | ||
|
|
0837c017a1 | ||
|
|
32d0301366 | ||
|
|
5accd657d9 | ||
|
|
8da97a63e0 | ||
|
|
a5d7731533 | ||
|
|
acb83fd697 | ||
|
|
271f21f85a | ||
|
|
371fb54787 | ||
|
|
3f19f9771a | ||
|
|
5a8596d113 | ||
|
|
6edd8b9a4e | ||
|
|
778346b0dd | ||
|
|
85ac633263 | ||
|
|
ff404e4dd6 | ||
|
|
d0845a7d68 | ||
|
|
954eaefe29 | ||
|
|
175b202a6f | ||
|
|
b77b4df56d | ||
|
|
dd7abe2547 | ||
|
|
cac27fb936 | ||
|
|
d9aef84e13 | ||
|
|
c6a81bef24 | ||
|
|
6824a1aa68 | ||
|
|
00de9d639b | ||
|
|
5a66c78428 | ||
|
|
d1be193125 | ||
|
|
f4c8d21a33 | ||
|
|
d588f749d2 | ||
|
|
c1f909427b | ||
|
|
2b38c03840 | ||
|
|
8cca77dcab | ||
|
|
5b341cb5fb | ||
|
|
526299e41f | ||
|
|
ae82bce4da | ||
|
|
499ca87759 | ||
|
|
aa4fbe1f6c | ||
|
|
05b72f9f07 | ||
|
|
53ffa50b15 | ||
|
|
bd9721f308 | ||
|
|
875bd4cb35 | ||
|
|
ec575c307a | ||
|
|
05087874e2 | ||
|
|
4a803f4b46 | ||
|
|
a48222022e | ||
|
|
eebbde1c40 | ||
|
|
c0a7686338 | ||
|
|
4840470b60 | ||
|
|
091d9b9669 | ||
|
|
d5b86289b6 | ||
|
|
dceb6ce690 | ||
|
|
c29c25d252 | ||
|
|
a2fb36671d | ||
|
|
6e57d4e69a | ||
|
|
063bef92b9 | ||
|
|
2bf9156808 | ||
|
|
391363c419 | ||
|
|
85ae7f7bec | ||
|
|
03718bc927 | ||
|
|
768aebf5d2 | ||
|
|
9e31e74d15 | ||
|
|
2acc99d307 | ||
|
|
20892f8541 | ||
|
|
e0f96a2650 | ||
|
|
e793526cb2 | ||
|
|
d1eb4cae57 | ||
|
|
f33fa33a08 | ||
|
|
858ae11c8b | ||
|
|
99a7e74825 | ||
|
|
304cef4d7d | ||
|
|
7dba9b88dc | ||
|
|
bfb5de1525 | ||
|
|
8071a2888b | ||
|
|
8b9abb13d0 | ||
|
|
6dbae61212 | ||
|
|
75c65d61c5 | ||
|
|
37e0de41af | ||
|
|
57f9e43508 | ||
|
|
3b7f931f28 | ||
|
|
b37a7aad4f | ||
|
|
667ab31ed9 | ||
|
|
b15ddef7fe | ||
|
|
ef785e5fb0 | ||
|
|
15ba4146ac | ||
|
|
9956fd1756 | ||
|
|
b6f2161f1c | ||
|
|
e6fca1a2d0 | ||
|
|
a9cad8c9f1 | ||
|
|
22b8b1f707 | ||
|
|
98f6871caa | ||
|
|
aae588249a | ||
|
|
ef890d51e3 | ||
|
|
b0bc03437a | ||
|
|
23b94da8f0 | ||
|
|
1f227ddd24 | ||
|
|
01a88a25a2 | ||
|
|
12152665af | ||
|
|
064e17b29d | ||
|
|
0aaba80c82 | ||
|
|
1744668fbd | ||
|
|
8e3e2ffb25 | ||
|
|
f5475bfde6 | ||
|
|
27fa270b42 | ||
|
|
15ece75b5d | ||
|
|
a796621f93 | ||
|
|
3c943c6685 | ||
|
|
4209774b4e | ||
|
|
b18637f7d0 | ||
|
|
af8a848d14 | ||
|
|
01e392158d | ||
|
|
fc47b7aa0d | ||
|
|
a0e0627a49 |
17
.devcontainer/devcontainer.json
Normal file
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "Node.js 20",
|
||||
"image": "mcr.microsoft.com/devcontainers/javascript-node:20",
|
||||
"features": {
|
||||
"ghcr.io/devcontainers/features/node:1": {
|
||||
"version": "20"
|
||||
}
|
||||
},
|
||||
"postCreateCommand": "npm install",
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
"extensions": [
|
||||
"ms-vscode.vscode-typescript-next"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
2
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@@ -13,7 +13,7 @@ body:
|
||||
1. **Review recent [release notes](https://github.com/zsviczian/obsidian-excalidraw-plugin/releases)** – maybe there is already an answer.
|
||||
2. **[Search issues](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues) (including closed ones)** to see if there is anything similar.
|
||||
3. **[Watch the Feature Walkthrough Video](https://youtu.be/P_Q6avJGoWI)**: As it infact answers 90% of the typical questions I receive
|
||||
4. **[Consult NotebookLM with your question](https://excalidraw-obsidian.online/WIKI/09+Video+Transcripts/Videos/Turn+any+YouTube+Channel+into+your+AI+Mentor+-+Obsidian+is+the+ultimate+automation+workbench+for+PKM)**
|
||||
4. **[Consult NotebookLM with your question](https://excalidraw-obsidian.online/WIKI/09+Video+Transcripts/Videos/Turn+any+YouTube+Channel+into+your+AI+Mentor+-+Obsidian+is+the+ultimate+automation+workbench+for+PKM)** Here's the [direct link to a preloaded NotebookLM](https://notebooklm.google.com/notebook/42d76a2f-c11d-4002-9286-1683c43d0ab0)
|
||||
|
||||
- type: markdown
|
||||
attributes:
|
||||
|
||||
7
.github/dependabot.yml
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
target-branch: "master"
|
||||
@@ -161,7 +161,7 @@ Number between 0 and 100. The opacity of an object, both stroke and fill.
|
||||
### strokeSharpness, setStrokeSharpness()
|
||||
```typescript
|
||||
type StrokeSharpness = "round" | "sharp";
|
||||
setStrokeSharpness(val:nmuber);
|
||||
setStrokeSharpness(val:number);
|
||||
```
|
||||
strokeSharpness is a string.
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ async function getImageSize(src: string): Promise<{ height: number; width: numbe
|
||||
export async function tex2dataURL(
|
||||
tex: string,
|
||||
scale: number = 4,
|
||||
app?: any
|
||||
plugin?: any
|
||||
): Promise<{
|
||||
mimeType: string;
|
||||
fileId: FileId;
|
||||
@@ -50,9 +50,9 @@ export async function tex2dataURL(
|
||||
let output: SVG<unknown, unknown, unknown>;
|
||||
|
||||
if(!adaptor) {
|
||||
if (app) {
|
||||
const file = app.vault.getAbstractFileByPath("preamble.sty");
|
||||
preamble = file ? await app.vault.read(file) : null;
|
||||
if (plugin) {
|
||||
const file = plugin.app.vault.getAbstractFileByPath(plugin.settings.latexPreambleLocation || "preamble.sty");
|
||||
preamble = file ? await plugin.app.vault.read(file) : null;
|
||||
}
|
||||
adaptor = liteAdaptor();
|
||||
RegisterHTMLHandler(adaptor);
|
||||
@@ -69,10 +69,18 @@ export async function tex2dataURL(
|
||||
|
||||
try {
|
||||
const node = html.convert(
|
||||
preamble ? `${preamble}${tex}` : tex,
|
||||
preamble ? `${preamble}\n${tex}` : tex,
|
||||
{ display: true, scale }
|
||||
);
|
||||
const svg = new DOMParser().parseFromString(adaptor.innerHTML(node), "image/svg+xml").firstChild as SVGSVGElement;
|
||||
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2195
|
||||
//https://stackoverflow.com/a/77181931
|
||||
let styleNode = document.createElement('style');
|
||||
styleNode.setAttribute("type", "text/css");
|
||||
styleNode.appendChild(document.createTextNode(".mjx-solid { stroke-width: 80px; }"));
|
||||
svg.appendChild(styleNode);
|
||||
|
||||
if (svg) {
|
||||
if(svg.width.baseVal.valueInSpecifiedUnits < 2) {
|
||||
svg.width.baseVal.valueAsString = `${(svg.width.baseVal.valueInSpecifiedUnits+1).toFixed(3)}ex`;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Excalidraw
|
||||
|
||||
[简体中文](./docs/zh-cn/README.md)
|
||||
【English | [简体中文](./docs/zh-cn/README.md)】
|
||||
|
||||
👉👉👉 Check out and contribute to the new [Obsidian-Excalidraw Community Wiki](https://excalidraw-obsidian.online/WIKI/Welcome+to+the+WIKI)
|
||||
|
||||
@@ -89,8 +89,8 @@ Plugin settings are grouped into the following sections:
|
||||
- **Basic settings**: such as default folders to use.
|
||||
- **Saving**: compression and autosave timer.
|
||||
- **Filename**: configure the automatically created Excalidraw filename.
|
||||
- **Display**: settings that effect the handling of Excalidraw (e.g.: left-handed mode, theme settings, mouse wheel and pinch zoom settings, zoom to fit settings).
|
||||
- **Links and transclusions**: Settings that effect how links and embedded items behave on the Excalidraw canvas.
|
||||
- **Display**: settings that affect the handling of Excalidraw (e.g.: left-handed mode, theme settings, mouse wheel and pinch zoom settings, zoom to fit settings).
|
||||
- **Links and transclusions**: Settings that affect how links and embedded items behave on the Excalidraw canvas.
|
||||
- **Markdown-embed settings**: These settings control how markdown documents from your Vault embedded into Excalidraw drawings will behave.
|
||||
- **Embed & Export**: Settings that control how Excalidraw images are displayed when embedding them into markdown documents.
|
||||
- **Auto-export Settings**: You can configure Excalidraw to create a PNG or SVG copy of your drawing each time it gets saved.
|
||||
|
||||
4
docs/API/ExcalidrawAutomate.d.ts
vendored
@@ -1,5 +1,5 @@
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { FillStyle, StrokeStyle, ExcalidrawElement, ExcalidrawBindableElement, FileId, NonDeletedExcalidrawElement, ExcalidrawImageElement, StrokeRoundness, RoundnessType } from "@zsviczian/excalidraw/types/excalidraw/element/types";
|
||||
import { FillStyle, StrokeStyle, ExcalidrawElement, ExcalidrawBindableElement, FileId, NonDeletedExcalidrawElement, ExcalidrawImageElement, StrokeRoundness, RoundnessType } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ColorMap, MimeType } from "./EmbeddedFileLoader";
|
||||
import { Editor, OpenViewState, RequestUrlResponse, TFile, TFolder, WorkspaceLeaf } from "obsidian";
|
||||
import * as obsidian_module from "obsidian";
|
||||
@@ -11,7 +11,7 @@ import { ColorMaster } from "@zsviczian/colormaster";
|
||||
import { TInput } from "@zsviczian/colormaster/types";
|
||||
import { ClipboardData } from "@zsviczian/excalidraw/types/excalidraw/clipboard";
|
||||
import { PaneTarget } from "src/utils/modifierkeyHelper";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { EmbeddableMDCustomProps } from "./Dialogs/EmbeddableSettings";
|
||||
import { AIRequest } from "../utils/AIUtils";
|
||||
import { AddImageOptions, ImageInfo, SVGColorInfo } from "src/types/excalidrawAutomateTypes";
|
||||
|
||||
@@ -54,7 +54,7 @@ Number between 0 and 100. The opacity of an object, both stroke and fill.
|
||||
### strokeSharpness, setStrokeSharpness()
|
||||
```typescript
|
||||
type StrokeSharpness = "round" | "sharp";
|
||||
setStrokeSharpness(val:nmuber);
|
||||
setStrokeSharpness(val:number);
|
||||
```
|
||||
strokeSharpness is a string.
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# [◀ Excalidraw Automate How To](./readme.md)
|
||||
|
||||
【English | [简体中文](zh-cn/docs/ExcalidrawScriptsEngine.md)】
|
||||
|
||||
[](https://youtu.be/hePJcObHIso)
|
||||
|
||||
## Introduction
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# Excalidraw Automate How To
|
||||
|
||||
【English | [简体中文](zh-cn/docs/readme.md)】
|
||||
|
||||
Use ExcalidrawAutomate to create or manipulate Excalidraw drawings using the [ExcalidrawAutomate Script Engine](ExcalidrawScriptsEngine.md), the [Templater](https://silentvoid13.github.io/Templater/docs/) or the [QuickAdd](https://github.com/chhoumann/quickadd) plugins, and to generate embedded SVG and PNG images using [DataviewJS](https://blacksmithgu.github.io/obsidian-dataview/docs/api/intro/)
|
||||
|
||||
With a little work, using ExcalidrawAutomate you can generate simple mindmaps, build a family tree, fill out SVG forms, create customized charts, or automate simple tasks (i.e. create macros) in Excalidraw.
|
||||
|
||||
@@ -167,7 +167,7 @@ strokeStyle 是一个字符串。
|
||||
### strokeSharpness, setStrokeSharpness()
|
||||
```typescript
|
||||
type StrokeSharpness = "round" | "sharp";
|
||||
setStrokeSharpness(val:nmuber);
|
||||
setStrokeSharpness(val:number);
|
||||
```
|
||||
strokeSharpness 是一个字符串。
|
||||
|
||||
@@ -282,7 +282,7 @@ addToGroup(objectIds:[]):void
|
||||
```
|
||||
将 `objectIds` 中列出的对象进行分组。
|
||||
|
||||
## Utility functions
|
||||
## 实用函数
|
||||
### clear()
|
||||
`clear()` 将从缓存中清除对象,但会保留元素样式设置。
|
||||
|
||||
@@ -407,7 +407,7 @@ async createPNG(templatePath?:string)
|
||||
- Test 3.1
|
||||
```
|
||||
|
||||
The script:
|
||||
脚本:
|
||||
|
||||
*使用 <kbd>CTRL+Shift+V</kbd> 将代码粘贴到 Obsidian 中!*
|
||||
```javascript
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
> 此说明当前更新至 `5569cff`。
|
||||
|
||||
[English](../../README.md)
|
||||
【[English](../../README.md) | 简体中文】
|
||||
|
||||
👉👉👉 快来查看并为新的 [Obsidian-Excalidraw 社区维基](https://excalidraw-obsidian.online/Hobbies/Excalidraw+Blog/WIKI/Welcome+to+the+WIKI)贡献你的力量吧
|
||||
|
||||
@@ -107,7 +107,7 @@ Obsidian-Excalidraw 插件将 [Excalidraw](https://excalidraw.com/) 这一功能
|
||||
|
||||
#### 模板
|
||||
|
||||
- 新绘图的模板。该模板将恢复笔画属性。这意味着您可以在模板中设置笔画颜色、笔画宽度、不透明度、字体系列、字体大小、填充样式、笔画样式等的默认值。这同样适用于 ExcalidrawAutomate。
|
||||
- 新绘图的模板。该模板将恢复笔画属性。这意味着您可以在模板中设置笔画颜色、笔画宽度、不透明度、字体系列、字体大小、填充样式、笔画样式等的默认值。这同样适用于 ExcalidrawAutomate。对于 1.6.13 或更高版本,在编辑模板中的 JSON 之前,请确保在设置中启用"在 Markdown 视图中解压缩 Excalidraw JSON"。完成更改后可以禁用此选项。
|
||||
- 通过模板,您可以自定义 Excalidraw 使用的调色板。
|
||||
- 切换到 Markdown 视图。
|
||||
- 滚动到文件底部,找到 `"AppState": {`。
|
||||
@@ -218,6 +218,7 @@ Obsidian-Excalidraw 插件将 [Excalidraw](https://excalidraw.com/) 这一功能
|
||||
- `excalidraw-export-dark`: true == 深色模式 / false == 浅色模式。
|
||||
- `excalidraw-export-padding`:指定图像的导出边距。
|
||||
- `excalidraw-export-pngscale`:这仅影响导出为 PNG。指定图像的导出比例。典型范围在 0.5 到 5 之间,但您也可以尝试其他值。
|
||||
- 从 1.6.13 版本开始,如果您想修改任何 JSON 内容,请在设置中启用"在 Markdown 视图中解压缩 Excalidraw JSON"。
|
||||
|
||||
### 将完整的 Markdown 文件嵌入到您的绘图中
|
||||
|
||||
|
||||
1119
docs/zh-cn/docs/API/ExcalidrawAutomate.d.ts
vendored
Normal file
782
docs/zh-cn/docs/API/attributes_functions_overview.md
Normal file
@@ -0,0 +1,782 @@
|
||||
# [◀ Excalidraw 自动化使用指南](../readme.md)
|
||||
|
||||
## 属性和函数概览
|
||||
|
||||
以下是 ExcalidrawAutomate 实现的接口:
|
||||
|
||||
你可以在这里找到源文件: [ExcalidrawAutomate.d.ts](ExcalidrawAutomate.d.ts)。
|
||||
|
||||
```javascript
|
||||
/// <reference types="react" />
|
||||
import ExcalidrawPlugin from "src/main";
|
||||
import { FillStyle, StrokeStyle, ExcalidrawElement, ExcalidrawBindableElement, FileId, NonDeletedExcalidrawElement, ExcalidrawImageElement, StrokeRoundness, RoundnessType } from "@zsviczian/excalidraw/types/element/types";
|
||||
import { Editor, OpenViewState, TFile, WorkspaceLeaf } from "obsidian";
|
||||
import * as obsidian_module from "obsidian";
|
||||
import ExcalidrawView, { ExportSettings } from "src/ExcalidrawView";
|
||||
import { AppState, BinaryFileData, DataURL, ExcalidrawImperativeAPI, Point } from "@zsviczian/excalidraw/types/types";
|
||||
import { EmbeddedFilesLoader } from "src/EmbeddedFileLoader";
|
||||
import { ConnectionPoint, DeviceType } from "src/types";
|
||||
import { ColorMaster } from "colormaster";
|
||||
import { TInput } from "colormaster/types";
|
||||
import { ClipboardData } from "@zsviczian/excalidraw/types/clipboard";
|
||||
import { PaneTarget } from "src/utils/modifierkeyHelper";
|
||||
export declare class ExcalidrawAutomate {
|
||||
/**
|
||||
* Utility function that returns the Obsidian Module object.
|
||||
*/
|
||||
get obsidian(): typeof obsidian_module;
|
||||
get DEVICE(): DeviceType;
|
||||
getAttachmentFilepath(filename: string): Promise<string>;
|
||||
/**
|
||||
* Prompts the user with a dialog to select new file action.
|
||||
* - create markdown file
|
||||
* - create excalidraw file
|
||||
* - cancel action
|
||||
* The new file will be relative to this.targetView.file.path, unless parentFile is provided.
|
||||
* If shouldOpenNewFile is true, the new file will be opened in a workspace leaf.
|
||||
* targetPane control which leaf will be used for the new file.
|
||||
* Returns the TFile for the new file or null if the user cancelled the action.
|
||||
* @param newFileNameOrPath
|
||||
* @param shouldOpenNewFile
|
||||
* @param targetPane //type PaneTarget = "active-pane"|"new-pane"|"popout-window"|"new-tab"|"md-properties";
|
||||
* @param parentFile
|
||||
* @returns
|
||||
*/
|
||||
newFilePrompt(newFileNameOrPath: string, shouldOpenNewFile: boolean, targetPane?: PaneTarget, parentFile?: TFile): Promise<TFile | null>;
|
||||
/**
|
||||
* Generates a new Obsidian Leaf following Excalidraw plugin settings such as open in Main Workspace or not, open in adjacent pane if available, etc.
|
||||
* @param origo // the currently active leaf, the origin of the new leaf
|
||||
* @param targetPane //type PaneTarget = "active-pane"|"new-pane"|"popout-window"|"new-tab"|"md-properties";
|
||||
* @returns
|
||||
*/
|
||||
getLeaf(origo: WorkspaceLeaf, targetPane?: PaneTarget): WorkspaceLeaf;
|
||||
/**
|
||||
* Returns the editor or leaf.view of the currently active embedded obsidian file.
|
||||
* If view is not provided, ea.targetView is used.
|
||||
* If the embedded file is a markdown document the function will return
|
||||
* {file:TFile, editor:Editor} otherwise it will return {view:any}. You can check view type with view.getViewType();
|
||||
* @param view
|
||||
* @returns
|
||||
*/
|
||||
getActiveEmbeddableViewOrEditor(view?: ExcalidrawView): {
|
||||
view: any;
|
||||
} | {
|
||||
file: TFile;
|
||||
editor: Editor;
|
||||
} | null;
|
||||
plugin: ExcalidrawPlugin;
|
||||
elementsDict: {
|
||||
[key: string]: any;
|
||||
};
|
||||
imagesDict: {
|
||||
[key: FileId]: any;
|
||||
};
|
||||
mostRecentMarkdownSVG: SVGSVGElement;
|
||||
style: {
|
||||
strokeColor: string;
|
||||
backgroundColor: string;
|
||||
angle: number;
|
||||
fillStyle: FillStyle;
|
||||
strokeWidth: number;
|
||||
strokeStyle: StrokeStyle;
|
||||
roughness: number;
|
||||
opacity: number;
|
||||
strokeSharpness?: StrokeRoundness;
|
||||
roundness: null | {
|
||||
type: RoundnessType;
|
||||
value?: number;
|
||||
};
|
||||
fontFamily: number;
|
||||
fontSize: number;
|
||||
textAlign: string;
|
||||
verticalAlign: string;
|
||||
startArrowHead: string;
|
||||
endArrowHead: string;
|
||||
};
|
||||
canvas: {
|
||||
theme: string;
|
||||
viewBackgroundColor: string;
|
||||
gridSize: number;
|
||||
};
|
||||
colorPalette: {};
|
||||
constructor(plugin: ExcalidrawPlugin, view?: ExcalidrawView);
|
||||
/**
|
||||
*
|
||||
* @returns the last recorded pointer position on the Excalidraw canvas
|
||||
*/
|
||||
getViewLastPointerPosition(): {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
/**
|
||||
*
|
||||
* @returns
|
||||
*/
|
||||
getAPI(view?: ExcalidrawView): ExcalidrawAutomate;
|
||||
/**
|
||||
* @param val //0:"hachure", 1:"cross-hatch" 2:"solid"
|
||||
* @returns
|
||||
*/
|
||||
setFillStyle(val: number): "hachure" | "cross-hatch" | "solid";
|
||||
/**
|
||||
* @param val //0:"solid", 1:"dashed", 2:"dotted"
|
||||
* @returns
|
||||
*/
|
||||
setStrokeStyle(val: number): "solid" | "dashed" | "dotted";
|
||||
/**
|
||||
* @param val //0:"round", 1:"sharp"
|
||||
* @returns
|
||||
*/
|
||||
setStrokeSharpness(val: number): "round" | "sharp";
|
||||
/**
|
||||
* @param val //1: Virgil, 2:Helvetica, 3:Cascadia
|
||||
* @returns
|
||||
*/
|
||||
setFontFamily(val: number): "Virgil, Segoe UI Emoji" | "Helvetica, Segoe UI Emoji" | "Cascadia, Segoe UI Emoji" | "LocalFont";
|
||||
/**
|
||||
* @param val //0:"light", 1:"dark"
|
||||
* @returns
|
||||
*/
|
||||
setTheme(val: number): "light" | "dark";
|
||||
/**
|
||||
* @param objectIds
|
||||
* @returns
|
||||
*/
|
||||
addToGroup(objectIds: string[]): string;
|
||||
/**
|
||||
* @param templatePath
|
||||
*/
|
||||
toClipboard(templatePath?: string): Promise<void>;
|
||||
/**
|
||||
* @param file: TFile
|
||||
* @returns ExcalidrawScene
|
||||
*/
|
||||
getSceneFromFile(file: TFile): Promise<{
|
||||
elements: ExcalidrawElement[];
|
||||
appState: AppState;
|
||||
}>;
|
||||
/**
|
||||
* get all elements from ExcalidrawAutomate elementsDict
|
||||
* @returns elements from elementsDict
|
||||
*/
|
||||
getElements(): ExcalidrawElement[];
|
||||
/**
|
||||
* get single element from ExcalidrawAutomate elementsDict
|
||||
* @param id
|
||||
* @returns
|
||||
*/
|
||||
getElement(id: string): ExcalidrawElement;
|
||||
/**
|
||||
* create a drawing and save it to filename
|
||||
* @param params
|
||||
* filename: if null, default filename as defined in Excalidraw settings
|
||||
* foldername: if null, default folder as defined in Excalidraw settings
|
||||
* @returns
|
||||
*/
|
||||
create(params?: {
|
||||
filename?: string;
|
||||
foldername?: string;
|
||||
templatePath?: string;
|
||||
onNewPane?: boolean;
|
||||
frontmatterKeys?: {
|
||||
"excalidraw-plugin"?: "raw" | "parsed";
|
||||
"excalidraw-link-prefix"?: string;
|
||||
"excalidraw-link-brackets"?: boolean;
|
||||
"excalidraw-url-prefix"?: string;
|
||||
"excalidraw-export-transparent"?: boolean;
|
||||
"excalidraw-export-dark"?: boolean;
|
||||
"excalidraw-export-padding"?: number;
|
||||
"excalidraw-export-pngscale"?: number;
|
||||
"excalidraw-default-mode"?: "view" | "zen";
|
||||
"excalidraw-onload-script"?: string;
|
||||
"excalidraw-linkbutton-opacity"?: number;
|
||||
"excalidraw-autoexport"?: boolean;
|
||||
};
|
||||
plaintext?: string;
|
||||
}): Promise<string>;
|
||||
/**
|
||||
*
|
||||
* @param templatePath
|
||||
* @param embedFont
|
||||
* @param exportSettings use ExcalidrawAutomate.getExportSettings(boolean,boolean)
|
||||
* @param loader use ExcalidrawAutomate.getEmbeddedFilesLoader(boolean?)
|
||||
* @param theme
|
||||
* @returns
|
||||
*/
|
||||
createSVG(templatePath?: string, embedFont?: boolean, exportSettings?: ExportSettings, loader?: EmbeddedFilesLoader, theme?: string, padding?: number): Promise<SVGSVGElement>;
|
||||
/**
|
||||
*
|
||||
* @param templatePath
|
||||
* @param scale
|
||||
* @param exportSettings use ExcalidrawAutomate.getExportSettings(boolean,boolean)
|
||||
* @param loader use ExcalidrawAutomate.getEmbeddedFilesLoader(boolean?)
|
||||
* @param theme
|
||||
* @returns
|
||||
*/
|
||||
createPNG(templatePath?: string, scale?: number, exportSettings?: ExportSettings, loader?: EmbeddedFilesLoader, theme?: string, padding?: number): Promise<any>;
|
||||
/**
|
||||
*
|
||||
* @param text
|
||||
* @param lineLen
|
||||
* @returns
|
||||
*/
|
||||
wrapText(text: string, lineLen: number): string;
|
||||
private boxedElement;
|
||||
addIFrame(topX: number, topY: number, width: number, height: number, url?: string, file?: TFile): string;
|
||||
/**
|
||||
*
|
||||
* @param topX
|
||||
* @param topY
|
||||
* @param width
|
||||
* @param height
|
||||
* @returns
|
||||
*/
|
||||
addEmbeddable(topX: number, topY: number, width: number, height: number, url?: string, file?: TFile): string;
|
||||
/**
|
||||
*
|
||||
* @param topX
|
||||
* @param topY
|
||||
* @param width
|
||||
* @param height
|
||||
* @returns
|
||||
*/
|
||||
addRect(topX: number, topY: number, width: number, height: number): string;
|
||||
/**
|
||||
*
|
||||
* @param topX
|
||||
* @param topY
|
||||
* @param width
|
||||
* @param height
|
||||
* @returns
|
||||
*/
|
||||
addDiamond(topX: number, topY: number, width: number, height: number): string;
|
||||
/**
|
||||
*
|
||||
* @param topX
|
||||
* @param topY
|
||||
* @param width
|
||||
* @param height
|
||||
* @returns
|
||||
*/
|
||||
addEllipse(topX: number, topY: number, width: number, height: number): string;
|
||||
/**
|
||||
*
|
||||
* @param topX
|
||||
* @param topY
|
||||
* @param width
|
||||
* @param height
|
||||
* @returns
|
||||
*/
|
||||
addBlob(topX: number, topY: number, width: number, height: number): string;
|
||||
/**
|
||||
* Refresh the size of a text element to fit its contents
|
||||
* @param id - the id of the text element
|
||||
*/
|
||||
refreshTextElementSize(id: string): void;
|
||||
/**
|
||||
*
|
||||
* @param topX
|
||||
* @param topY
|
||||
* @param text
|
||||
* @param formatting
|
||||
* box: if !null, text will be boxed
|
||||
* @param id
|
||||
* @returns
|
||||
*/
|
||||
addText(topX: number, topY: number, text: string, formatting?: {
|
||||
wrapAt?: number;
|
||||
width?: number;
|
||||
height?: number;
|
||||
textAlign?: "left" | "center" | "right";
|
||||
box?: boolean | "box" | "blob" | "ellipse" | "diamond";
|
||||
boxPadding?: number;
|
||||
boxStrokeColor?: string;
|
||||
textVerticalAlign?: "top" | "middle" | "bottom";
|
||||
}, id?: string): string;
|
||||
/**
|
||||
*
|
||||
* @param points
|
||||
* @returns
|
||||
*/
|
||||
addLine(points: [[x: number, y: number]]): string;
|
||||
/**
|
||||
*
|
||||
* @param points
|
||||
* @param formatting
|
||||
* @returns
|
||||
*/
|
||||
addArrow(points: [x: number, y: number][], formatting?: {
|
||||
startArrowHead?: string;
|
||||
endArrowHead?: string;
|
||||
startObjectId?: string;
|
||||
endObjectId?: string;
|
||||
}): string;
|
||||
/**
|
||||
*
|
||||
* @param topX
|
||||
* @param topY
|
||||
* @param imageFile
|
||||
* @returns
|
||||
*/
|
||||
addImage(topX: number, topY: number, imageFile: TFile | string, scale?: boolean, //default is true which will scale the image to MAX_IMAGE_SIZE, false will insert image at 100% of its size
|
||||
anchor?: boolean): Promise<string>;
|
||||
/**
|
||||
*
|
||||
* @param topX
|
||||
* @param topY
|
||||
* @param tex
|
||||
* @returns
|
||||
*/
|
||||
addLaTex(topX: number, topY: number, tex: string): Promise<string>;
|
||||
/**
|
||||
*
|
||||
* @param objectA
|
||||
* @param connectionA type ConnectionPoint = "top" | "bottom" | "left" | "right" | null
|
||||
* @param objectB
|
||||
* @param connectionB when passed null, Excalidraw will automatically decide
|
||||
* @param formatting
|
||||
* numberOfPoints: points on the line. Default is 0 ie. line will only have a start and end point
|
||||
* startArrowHead: "triangle"|"dot"|"arrow"|"bar"|null
|
||||
* endArrowHead: "triangle"|"dot"|"arrow"|"bar"|null
|
||||
* padding:
|
||||
* @returns
|
||||
*/
|
||||
connectObjects(objectA: string, connectionA: ConnectionPoint | null, objectB: string, connectionB: ConnectionPoint | null, formatting?: {
|
||||
numberOfPoints?: number;
|
||||
startArrowHead?: "triangle" | "dot" | "arrow" | "bar" | null;
|
||||
endArrowHead?: "triangle" | "dot" | "arrow" | "bar" | null;
|
||||
padding?: number;
|
||||
}): string;
|
||||
/**
|
||||
* Adds a text label to a line or arrow. Currently only works with a straight (2 point - start & end - line)
|
||||
* @param lineId id of the line or arrow object in elementsDict
|
||||
* @param label the label text
|
||||
* @returns undefined (if unsuccessful) or the id of the new text element
|
||||
*/
|
||||
addLabelToLine(lineId: string, label: string): string;
|
||||
/**
|
||||
* clear elementsDict and imagesDict only
|
||||
*/
|
||||
clear(): void;
|
||||
/**
|
||||
* clear() + reset all style values to default
|
||||
*/
|
||||
reset(): void;
|
||||
/**
|
||||
* returns true if MD file is an Excalidraw file
|
||||
* @param f
|
||||
* @returns
|
||||
*/
|
||||
isExcalidrawFile(f: TFile): boolean;
|
||||
targetView: ExcalidrawView;
|
||||
/**
|
||||
* sets the target view for EA. All the view operations and the access to Excalidraw API will be performend on this view
|
||||
* if view is null or undefined, the function will first try setView("active"), then setView("first").
|
||||
* @param view
|
||||
* @returns targetView
|
||||
*/
|
||||
setView(view?: ExcalidrawView | "first" | "active"): ExcalidrawView;
|
||||
/**
|
||||
*
|
||||
* @returns https://github.com/excalidraw/excalidraw/tree/master/src/packages/excalidraw#ref
|
||||
*/
|
||||
getExcalidrawAPI(): any;
|
||||
/**
|
||||
* get elements in View
|
||||
* @returns
|
||||
*/
|
||||
getViewElements(): ExcalidrawElement[];
|
||||
/**
|
||||
*
|
||||
* @param elToDelete
|
||||
* @returns
|
||||
*/
|
||||
deleteViewElements(elToDelete: ExcalidrawElement[]): boolean;
|
||||
/**
|
||||
* get the selected element in the view, if more are selected, get the first
|
||||
* @returns
|
||||
*/
|
||||
getViewSelectedElement(): any;
|
||||
/**
|
||||
*
|
||||
* @returns
|
||||
*/
|
||||
getViewSelectedElements(): any[];
|
||||
/**
|
||||
*
|
||||
* @param el
|
||||
* @returns TFile file handle for the image element
|
||||
*/
|
||||
getViewFileForImageElement(el: ExcalidrawElement): TFile | null;
|
||||
/**
|
||||
* copies elements from view to elementsDict for editing
|
||||
* @param elements
|
||||
*/
|
||||
copyViewElementsToEAforEditing(elements: ExcalidrawElement[]): void;
|
||||
/**
|
||||
*
|
||||
* @param forceViewMode
|
||||
* @returns
|
||||
*/
|
||||
viewToggleFullScreen(forceViewMode?: boolean): void;
|
||||
setViewModeEnabled(enabled: boolean): void;
|
||||
/**
|
||||
* This function gives you a more hands on access to Excalidraw.
|
||||
* @param scene - The scene you want to load to Excalidraw
|
||||
* @param restore - Use this if the scene includes legacy excalidraw file elements that need to be converted to the latest excalidraw data format (not a typical usecase)
|
||||
* @returns
|
||||
*/
|
||||
viewUpdateScene(scene: {
|
||||
elements?: ExcalidrawElement[];
|
||||
appState?: AppState;
|
||||
files?: BinaryFileData;
|
||||
commitToHistory?: boolean;
|
||||
}, restore?: boolean): void;
|
||||
/**
|
||||
* connect an object to the selected element in the view
|
||||
* @param objectA ID of the element
|
||||
* @param connectionA
|
||||
* @param connectionB
|
||||
* @param formatting
|
||||
* @returns
|
||||
*/
|
||||
connectObjectWithViewSelectedElement(objectA: string, connectionA: ConnectionPoint | null, connectionB: ConnectionPoint | null, formatting?: {
|
||||
numberOfPoints?: number;
|
||||
startArrowHead?: "triangle" | "dot" | "arrow" | "bar" | null;
|
||||
endArrowHead?: "triangle" | "dot" | "arrow" | "bar" | null;
|
||||
padding?: number;
|
||||
}): boolean;
|
||||
/**
|
||||
* zoom tarteView to fit elements provided as input
|
||||
* elements === [] will zoom to fit the entire scene
|
||||
* selectElements toggles whether the elements should be in a selected state at the end of the operation
|
||||
* @param selectElements
|
||||
* @param elements
|
||||
*/
|
||||
viewZoomToElements(selectElements: boolean, elements: ExcalidrawElement[]): void;
|
||||
/**
|
||||
* Adds elements from elementsDict to the current view
|
||||
* @param repositionToCursor default is false
|
||||
* @param save default is true
|
||||
* @param newElementsOnTop controls whether elements created with ExcalidrawAutomate
|
||||
* are added at the bottom of the stack or the top of the stack of elements already in the view
|
||||
* Note that elements copied to the view with copyViewElementsToEAforEditing retain their
|
||||
* position in the stack of elements in the view even if modified using EA
|
||||
* default is false, i.e. the new elements get to the bottom of the stack
|
||||
* @param shouldRestoreElements - restore elements - auto-corrects broken, incomplete or old elements included in the update
|
||||
* @returns
|
||||
*/
|
||||
addElementsToView(repositionToCursor?: boolean, save?: boolean, newElementsOnTop?: boolean, shouldRestoreElements?: boolean): Promise<boolean>;
|
||||
/**
|
||||
* Register instance of EA to use for hooks with TargetView
|
||||
* By default ExcalidrawViews will check window.ExcalidrawAutomate for event hooks.
|
||||
* Using this event you can set a different instance of Excalidraw Automate for hooks
|
||||
* @returns true if successful
|
||||
*/
|
||||
registerThisAsViewEA(): boolean;
|
||||
/**
|
||||
* Sets the targetView EA to window.ExcalidrawAutomate
|
||||
* @returns true if successful
|
||||
*/
|
||||
deregisterThisAsViewEA(): boolean;
|
||||
/**
|
||||
* If set, this callback is triggered when the user closes an Excalidraw view.
|
||||
*/
|
||||
onViewUnloadHook: (view: ExcalidrawView) => void;
|
||||
/**
|
||||
* If set, this callback is triggered, when the user changes the view mode.
|
||||
* You can use this callback in case you want to do something additional when the user switches to view mode and back.
|
||||
*/
|
||||
onViewModeChangeHook: (isViewModeEnabled: boolean, view: ExcalidrawView, ea: ExcalidrawAutomate) => void;
|
||||
/**
|
||||
* If set, this callback is triggered, when the user hovers a link in the scene.
|
||||
* You can use this callback in case you want to do something additional when the onLinkHover event occurs.
|
||||
* This callback must return a boolean value.
|
||||
* In case you want to prevent the excalidraw onLinkHover action you must return false, it will stop the native excalidraw onLinkHover management flow.
|
||||
*/
|
||||
onLinkHoverHook: (element: NonDeletedExcalidrawElement, linkText: string, view: ExcalidrawView, ea: ExcalidrawAutomate) => boolean;
|
||||
/**
|
||||
* If set, this callback is triggered, when the user clicks a link in the scene.
|
||||
* You can use this callback in case you want to do something additional when the onLinkClick event occurs.
|
||||
* This callback must return a boolean value.
|
||||
* In case you want to prevent the excalidraw onLinkClick action you must return false, it will stop the native excalidraw onLinkClick management flow.
|
||||
*/
|
||||
onLinkClickHook: (element: ExcalidrawElement, linkText: string, event: MouseEvent, view: ExcalidrawView, ea: ExcalidrawAutomate) => boolean;
|
||||
/**
|
||||
* If set, this callback is triggered, when Excalidraw receives an onDrop event.
|
||||
* You can use this callback in case you want to do something additional when the onDrop event occurs.
|
||||
* This callback must return a boolean value.
|
||||
* In case you want to prevent the excalidraw onDrop action you must return false, it will stop the native excalidraw onDrop management flow.
|
||||
*/
|
||||
onDropHook: (data: {
|
||||
ea: ExcalidrawAutomate;
|
||||
event: React.DragEvent<HTMLDivElement>;
|
||||
draggable: any;
|
||||
type: "file" | "text" | "unknown";
|
||||
payload: {
|
||||
files: TFile[];
|
||||
text: string;
|
||||
};
|
||||
excalidrawFile: TFile;
|
||||
view: ExcalidrawView;
|
||||
pointerPosition: {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
}) => boolean;
|
||||
/**
|
||||
* If set, this callback is triggered, when Excalidraw receives an onPaste event.
|
||||
* You can use this callback in case you want to do something additional when the
|
||||
* onPaste event occurs.
|
||||
* This callback must return a boolean value.
|
||||
* In case you want to prevent the excalidraw onPaste action you must return false,
|
||||
* it will stop the native excalidraw onPaste management flow.
|
||||
*/
|
||||
onPasteHook: (data: {
|
||||
ea: ExcalidrawAutomate;
|
||||
payload: ClipboardData;
|
||||
event: ClipboardEvent;
|
||||
excalidrawFile: TFile;
|
||||
view: ExcalidrawView;
|
||||
pointerPosition: {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
}) => boolean;
|
||||
/**
|
||||
* if set, this callback is triggered, when an Excalidraw file is opened
|
||||
* You can use this callback in case you want to do something additional when the file is opened.
|
||||
* This will run before the file level script defined in the `excalidraw-onload-script` frontmatter.
|
||||
*/
|
||||
onFileOpenHook: (data: {
|
||||
ea: ExcalidrawAutomate;
|
||||
excalidrawFile: TFile;
|
||||
view: ExcalidrawView;
|
||||
}) => Promise<void>;
|
||||
/**
|
||||
* if set, this callback is triggered, when an Excalidraw file is created
|
||||
* see also: https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1124
|
||||
*/
|
||||
onFileCreateHook: (data: {
|
||||
ea: ExcalidrawAutomate;
|
||||
excalidrawFile: TFile;
|
||||
view: ExcalidrawView;
|
||||
}) => Promise<void>;
|
||||
/**
|
||||
* If set, this callback is triggered whenever the active canvas color changes
|
||||
*/
|
||||
onCanvasColorChangeHook: (ea: ExcalidrawAutomate, view: ExcalidrawView, //the excalidraw view
|
||||
color: string) => void;
|
||||
/**
|
||||
* utility function to generate EmbeddedFilesLoader object
|
||||
* @param isDark
|
||||
* @returns
|
||||
*/
|
||||
getEmbeddedFilesLoader(isDark?: boolean): EmbeddedFilesLoader;
|
||||
/**
|
||||
* utility function to generate ExportSettings object
|
||||
* @param withBackground
|
||||
* @param withTheme
|
||||
* @returns
|
||||
*/
|
||||
getExportSettings(withBackground: boolean, withTheme: boolean): ExportSettings;
|
||||
/**
|
||||
* get bounding box of elements
|
||||
* bounding box is the box encapsulating all of the elements completely
|
||||
* @param elements
|
||||
* @returns
|
||||
*/
|
||||
getBoundingBox(elements: ExcalidrawElement[]): {
|
||||
topX: number;
|
||||
topY: number;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
/**
|
||||
* elements grouped by the highest level groups
|
||||
* @param elements
|
||||
* @returns
|
||||
*/
|
||||
getMaximumGroups(elements: ExcalidrawElement[]): ExcalidrawElement[][];
|
||||
/**
|
||||
* gets the largest element from a group. useful when a text element is grouped with a box, and you want to connect an arrow to the box
|
||||
* @param elements
|
||||
* @returns
|
||||
*/
|
||||
getLargestElement(elements: ExcalidrawElement[]): ExcalidrawElement;
|
||||
/**
|
||||
* @param element
|
||||
* @param a
|
||||
* @param b
|
||||
* @param gap
|
||||
* @returns 2 or 0 intersection points between line going through `a` and `b`
|
||||
* and the `element`, in ascending order of distance from `a`.
|
||||
*/
|
||||
intersectElementWithLine(element: ExcalidrawBindableElement, a: readonly [number, number], b: readonly [number, number], gap?: number): Point[];
|
||||
/**
|
||||
* Gets the groupId for the group that contains all the elements, or null if such a group does not exist
|
||||
* @param elements
|
||||
* @returns null or the groupId
|
||||
*/
|
||||
getCommonGroupForElements(elements: ExcalidrawElement[]): string;
|
||||
/**
|
||||
* Gets all the elements from elements[] that share one or more groupIds with element.
|
||||
* @param element
|
||||
* @param elements - typically all the non-deleted elements in the scene
|
||||
* @returns
|
||||
*/
|
||||
getElementsInTheSameGroupWithElement(element: ExcalidrawElement, elements: ExcalidrawElement[]): ExcalidrawElement[];
|
||||
/**
|
||||
* Gets all the elements from elements[] that are contained in the frame.
|
||||
* @param element
|
||||
* @param elements - typically all the non-deleted elements in the scene
|
||||
* @returns
|
||||
*/
|
||||
getElementsInFrame(frameElement: ExcalidrawElement, elements: ExcalidrawElement[]): ExcalidrawElement[];
|
||||
/**
|
||||
* See OCR plugin for example on how to use scriptSettings
|
||||
* Set by the ScriptEngine
|
||||
*/
|
||||
activeScript: string;
|
||||
/**
|
||||
*
|
||||
* @returns script settings. Saves settings in plugin settings, under the activeScript key
|
||||
*/
|
||||
getScriptSettings(): {};
|
||||
/**
|
||||
* sets script settings.
|
||||
* @param settings
|
||||
* @returns
|
||||
*/
|
||||
setScriptSettings(settings: any): Promise<void>;
|
||||
/**
|
||||
* Open a file in a new workspaceleaf or reuse an existing adjacent leaf depending on Excalidraw Plugin Settings
|
||||
* @param file
|
||||
* @param openState - if not provided {active: true} will be used
|
||||
* @returns
|
||||
*/
|
||||
openFileInNewOrAdjacentLeaf(file: TFile, openState?: OpenViewState): WorkspaceLeaf;
|
||||
/**
|
||||
* measure text size based on current style settings
|
||||
* @param text
|
||||
* @returns
|
||||
*/
|
||||
measureText(text: string): {
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
/**
|
||||
* Returns the size of the image element at 100% (i.e. the original size)
|
||||
* @param imageElement an image element from the active scene on targetView
|
||||
*/
|
||||
getOriginalImageSize(imageElement: ExcalidrawImageElement): Promise<{
|
||||
width: number;
|
||||
height: number;
|
||||
}>;
|
||||
/**
|
||||
* verifyMinimumPluginVersion returns true if plugin version is >= than required
|
||||
* recommended use:
|
||||
* if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.5.20")) {new Notice("message");return;}
|
||||
* @param requiredVersion
|
||||
* @returns
|
||||
*/
|
||||
verifyMinimumPluginVersion(requiredVersion: string): boolean;
|
||||
/**
|
||||
* Check if view is instance of ExcalidrawView
|
||||
* @param view
|
||||
* @returns
|
||||
*/
|
||||
isExcalidrawView(view: any): boolean;
|
||||
/**
|
||||
* sets selection in view
|
||||
* @param elements
|
||||
* @returns
|
||||
*/
|
||||
selectElementsInView(elements: ExcalidrawElement[] | string[]): void;
|
||||
/**
|
||||
* @returns an 8 character long random id
|
||||
*/
|
||||
generateElementId(): string;
|
||||
/**
|
||||
* @param element
|
||||
* @returns a clone of the element with a new id
|
||||
*/
|
||||
cloneElement(element: ExcalidrawElement): ExcalidrawElement;
|
||||
/**
|
||||
* Moves the element to a specific position in the z-index
|
||||
*/
|
||||
moveViewElementToZIndex(elementId: number, newZIndex: number): void;
|
||||
/**
|
||||
* Deprecated. Use getCM / ColorMaster instead
|
||||
* @param color
|
||||
* @returns
|
||||
*/
|
||||
hexStringToRgb(color: string): number[];
|
||||
/**
|
||||
* Deprecated. Use getCM / ColorMaster instead
|
||||
* @param color
|
||||
* @returns
|
||||
*/
|
||||
rgbToHexString(color: number[]): string;
|
||||
/**
|
||||
* Deprecated. Use getCM / ColorMaster instead
|
||||
* @param color
|
||||
* @returns
|
||||
*/
|
||||
hslToRgb(color: number[]): number[];
|
||||
/**
|
||||
* Deprecated. Use getCM / ColorMaster instead
|
||||
* @param color
|
||||
* @returns
|
||||
*/
|
||||
rgbToHsl(color: number[]): number[];
|
||||
/**
|
||||
*
|
||||
* @param color
|
||||
* @returns
|
||||
*/
|
||||
colorNameToHex(color: string): string;
|
||||
/**
|
||||
* https://github.com/lbragile/ColorMaster
|
||||
* @param color
|
||||
* @returns
|
||||
*/
|
||||
getCM(color: TInput): ColorMaster;
|
||||
importSVG(svgString: string): boolean;
|
||||
}
|
||||
export declare function initExcalidrawAutomate(plugin: ExcalidrawPlugin): Promise<ExcalidrawAutomate>;
|
||||
export declare function destroyExcalidrawAutomate(): void;
|
||||
export declare function _measureText(newText: string, fontSize: number, fontFamily: number, lineHeight: number): {
|
||||
w: number;
|
||||
h: number;
|
||||
baseline: number;
|
||||
};
|
||||
export declare const generatePlaceholderDataURL: (width: number, height: number) => DataURL;
|
||||
export declare function createPNG(templatePath: string, scale: number, exportSettings: ExportSettings, loader: EmbeddedFilesLoader, forceTheme: string, canvasTheme: string, canvasBackgroundColor: string, automateElements: ExcalidrawElement[], plugin: ExcalidrawPlugin, depth: number, padding?: number, imagesDict?: any): Promise<Blob>;
|
||||
export declare function createSVG(templatePath: string, embedFont: boolean, exportSettings: ExportSettings, loader: EmbeddedFilesLoader, forceTheme: string, canvasTheme: string, canvasBackgroundColor: string, automateElements: ExcalidrawElement[], plugin: ExcalidrawPlugin, depth: number, padding?: number, imagesDict?: any, convertMarkdownLinksToObsidianURLs?: boolean): Promise<SVGSVGElement>;
|
||||
export declare function estimateBounds(elements: ExcalidrawElement[]): [number, number, number, number];
|
||||
export declare function repositionElementsToCursor(elements: ExcalidrawElement[], newPosition: {
|
||||
x: number;
|
||||
y: number;
|
||||
}, center: boolean, api: ExcalidrawImperativeAPI): ExcalidrawElement[];
|
||||
export declare const insertLaTeXToView: (view: ExcalidrawView) => void;
|
||||
export declare const search: (view: ExcalidrawView) => Promise<void>;
|
||||
/**
|
||||
*
|
||||
* @param elements
|
||||
* @param query
|
||||
* @param exactMatch - when searching for section header exactMatch should be set to true
|
||||
* @returns the elements matching the query
|
||||
*/
|
||||
export declare const getTextElementsMatchingQuery: (elements: ExcalidrawElement[], query: string[], exactMatch?: boolean) => ExcalidrawElement[];
|
||||
/**
|
||||
*
|
||||
* @param elements
|
||||
* @param query
|
||||
* @param exactMatch - when searching for section header exactMatch should be set to true
|
||||
* @returns the elements matching the query
|
||||
*/
|
||||
export declare const getFrameElementsMatchingQuery: (elements: ExcalidrawElement[], query: string[], exactMatch?: boolean) => ExcalidrawElement[];
|
||||
export declare const cloneElement: (el: ExcalidrawElement) => any;
|
||||
export declare const verifyMinimumPluginVersion: (requiredVersion: string) => boolean;
|
||||
```
|
||||
19
docs/zh-cn/docs/API/canvas_style.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# [◀ Excalidraw 自动化指南](../readme.md)
|
||||
|
||||
## 画布样式设置
|
||||
设置画布的属性。
|
||||
|
||||
### theme, setTheme()
|
||||
字符串。有效值为 "light"(明亮)和 "dark"(黑暗)。
|
||||
|
||||
`setTheme()` 接受一个数字参数:
|
||||
- 0:"light"(明亮)
|
||||
- 其他任何数字:"dark"(黑暗)
|
||||
|
||||
### viewBackgroundColor
|
||||
字符串。这是对象的填充颜色。[CSS 合法颜色值](https://www.w3schools.com/cssref/css_colors_legal.asp)
|
||||
|
||||
允许的值包括 [HTML 颜色名称](https://www.w3schools.com/colors/colors_names.asp)、十六进制 RGB 字符串(例如红色使用 `#FF0000`)或 `transparent`(透明)。
|
||||
|
||||
### gridSize
|
||||
数字。网格的大小。如果设置为零,则不显示网格。
|
||||
110
docs/zh-cn/docs/API/element_style.md
Normal file
@@ -0,0 +1,110 @@
|
||||
# [◀ Excalidraw 自动化指南](../readme.md)
|
||||
|
||||
## 元素样式设置
|
||||
|
||||
你会注意到,一些样式有setter函数。这是为了帮助你设置属性的允许值。但是你不必使用setter函数,也可以直接设置值。
|
||||
|
||||
### strokeColor
|
||||
|
||||
字符串类型。线条的颜色。[CSS合法颜色值](https://www.w3schools.com/cssref/css_colors_legal.asp)
|
||||
|
||||
允许的值包括[HTML颜色名称](https://www.w3schools.com/colors/colors_names.asp)、十六进制RGB字符串,例如红色为`#FF0000`。
|
||||
|
||||
### backgroundColor
|
||||
|
||||
字符串类型。这是对象的填充颜色。[CSS合法颜色值](https://www.w3schools.com/cssref/css_colors_legal.asp)
|
||||
|
||||
允许的值包括[HTML颜色名称](https://www.w3schools.com/colors/colors_names.asp)、十六进制RGB字符串,例如红色为`#FF0000`,或者`transparent`(透明)。
|
||||
|
||||
### angle
|
||||
|
||||
数字类型。以弧度为单位的旋转角度。90度等于`Math.PI/2`。
|
||||
|
||||
### fillStyle, setFillStyle()
|
||||
|
||||
```typescript
|
||||
type FillStyle = "hachure" | "cross-hatch" | "solid";
|
||||
setFillStyle (val:number);
|
||||
```
|
||||
|
||||
fillStyle 是一个字符串。
|
||||
|
||||
`setFillStyle()` 接受一个数字参数:
|
||||
- 0: "hachure"(斜线填充)
|
||||
- 1: "cross-hatch"(交叉填充)
|
||||
- 其他任意数字: "solid"(实心填充)
|
||||
|
||||
### strokeWidth
|
||||
|
||||
数字类型。设置线条的宽度。
|
||||
|
||||
### strokeStyle, setStrokeStyle()
|
||||
|
||||
```typescript
|
||||
type StrokeStyle = "solid" | "dashed" | "dotted";
|
||||
setStrokeStyle (val:number);
|
||||
```
|
||||
|
||||
strokeStyle 是一个字符串。
|
||||
|
||||
`setStrokeStyle()` 接受一个数字参数:
|
||||
- 0: "solid"(实线)
|
||||
- 1: "dashed"(虚线)
|
||||
- 其他任意数字: "dotted"(点线)
|
||||
|
||||
### roughness
|
||||
|
||||
数字类型。在 Excalidraw 中称为随意度。接受三个值:
|
||||
- 0:建筑师风格
|
||||
- 1:艺术家风格
|
||||
- 2:卡通家风格
|
||||
|
||||
### opacity
|
||||
|
||||
数字类型,取值范围在 0~100 之间。用于设置对象的不透明度,同时影响线条和填充的透明度。
|
||||
|
||||
### strokeSharpness, setStrokeSharpness()
|
||||
|
||||
```typescript
|
||||
type StrokeSharpness = "round" | "sharp";
|
||||
setStrokeSharpness(val:number);
|
||||
```
|
||||
|
||||
strokeSharpness 是一个字符串。
|
||||
|
||||
"round"(圆滑)线条是弯曲的,"sharp"(尖锐)线条在转折点处会形成尖角。
|
||||
|
||||
`setStrokeSharpness()` 接受一个数字参数:
|
||||
- 0:"round"(圆滑)
|
||||
- 其他任意数字:"sharp"(尖锐)
|
||||
|
||||
### fontFamily, setFontFamily()
|
||||
|
||||
数字类型。有效值为 1、2 和 3。
|
||||
|
||||
`setFontFamily()` 也接受一个数字参数并返回字体名称:
|
||||
- 1: "Virgil, Segoe UI Emoji"
|
||||
- 2: "Helvetica, Segoe UI Emoji"
|
||||
- 3: "Cascadia, Segoe UI Emoji"
|
||||
|
||||
### fontSize
|
||||
|
||||
数字类型。默认值为 20px。
|
||||
|
||||
### textAlign
|
||||
|
||||
字符串类型。文本的水平对齐方式。有效值为 "left"(左对齐)、"center"(居中对齐)、"right"(右对齐)。
|
||||
|
||||
这在使用 `addText()` 函数设置固定宽度时很有用。
|
||||
|
||||
### verticalAlign
|
||||
|
||||
字符串类型。文本的垂直对齐方式。有效值为 "top"(顶部对齐)和 "middle"(居中对齐)。
|
||||
|
||||
这在使用 `addText()` 函数设置固定高度时很有用。
|
||||
|
||||
### startArrowHead, endArrowHead
|
||||
|
||||
字符串类型。有效值为 "arrow"(箭头)、"bar"(线段)、"dot"(圆点)和 "none"(无)。用于指定箭头的起始和结束样式。
|
||||
|
||||
这在使用 `addArrow()` 和 `connectObjects()` 函数时很有用。
|
||||
113
docs/zh-cn/docs/API/introduction.md
Normal file
@@ -0,0 +1,113 @@
|
||||
# [◀ Excalidraw Automate 使用指南](../readme.md)
|
||||
|
||||
## API 介绍
|
||||
|
||||
你可以通过 ExcalidrawAutomate 对象来访问 Excalidraw Automate。我建议在 Templater、DataView 和 QuickAdd 脚本中使用以下代码开始:
|
||||
|
||||
*使用 <kbd>CTRL+Shift+V</kbd> 将代码粘贴到 Obsidian 中!*
|
||||
|
||||
```javascript
|
||||
const ea = ExcalidrawAutomate;
|
||||
ea.reset();
|
||||
```
|
||||
|
||||
第一行创建了一个常量,这样你就可以避免重复写 ExcalidrawAutomate 上百次。
|
||||
|
||||
第二行将 ExcalidrawAutomate 重置为默认值。这一步很重要,因为你不会知道之前执行了哪个模板,因此也不知道 Excalidraw 处于什么状态。
|
||||
|
||||
**⚠ 注意:** 如果你正在使用 Excalidraw 插件内置的[脚本引擎](../ExcalidrawScriptsEngine.md),引擎会自动处理 `ea` 对象的初始化。
|
||||
|
||||
### Excalidraw Automate 的基本使用逻辑
|
||||
|
||||
1. 设置要绘制元素的样式
|
||||
2. 添加元素。当你添加元素时,每个新元素都会被添加到前一个元素的上层,因此在元素重叠的情况下,后添加的元素会显示在先添加元素的上方。
|
||||
3. 调用 `await ea.create();` 来实例化绘图,或使用 `ea.setView();` 后跟 `ea.addElementsToView();` 将元素添加到现有视图中,或使用 `await ea.createSVG();` 或 `await ea.createPNG();` 从你的元素创建 PNG 或 SVG 图像。
|
||||
|
||||
你可以在添加不同元素之间改变样式。我将元素样式和创建分开的逻辑基于这样一个假设:你可能会设置一个描边颜色、描边样式、描边粗糙度等,并使用这些设置来绘制大多数元素。每次添加元素时都重新设置所有这些参数是没有意义的。
|
||||
|
||||
### 在深入了解之前,这里有三个简单的 [Templater](https://github.com/SilentVoid13/Templater) 脚本示例
|
||||
|
||||
#### 使用模板在自定义文件夹中创建具有自定义名称的新绘图
|
||||
|
||||
这个简单的脚本相比 Excalidraw 插件设置提供了更大的灵活性,让你可以为绘图命名、将其放入文件夹中并应用模板。
|
||||
|
||||
*使用 <kbd>CTRL+Shift+V</kbd> 将代码粘贴到 Obsidian 中!*
|
||||
|
||||
```javascript
|
||||
<%*
|
||||
const ea = ExcalidrawAutomate;
|
||||
ea.reset();
|
||||
await ea.create({
|
||||
filename : tp.date.now("HH.mm"),
|
||||
foldername : tp.date.now("YYYY-MM-DD"),
|
||||
templatePath: "Excalidraw/Template1.excalidraw",
|
||||
onNewPane : false
|
||||
});
|
||||
%>
|
||||
```
|
||||
|
||||
#### 创建一个简单的绘图
|
||||
|
||||
*使用 <kbd>CTRL+Shift+V</kbd> 将代码粘贴到 Obsidian 中!*
|
||||
|
||||
```javascript
|
||||
<%*
|
||||
const ea = ExcalidrawAutomate;
|
||||
ea.reset();
|
||||
ea.addRect(-150,-50,450,300);
|
||||
ea.addText(-100,70,"Left to right");
|
||||
ea.addArrow([[-100,100],[100,100]]);
|
||||
|
||||
ea.style.strokeColor = "red";
|
||||
ea.addText(100,-30,"top to bottom",{width:200,textAligh:"center"});
|
||||
ea.addArrow([[200,0],[200,200]]);
|
||||
await ea.create();
|
||||
%>
|
||||
```
|
||||
|
||||
该脚本将生成以下绘图:
|
||||
|
||||

|
||||
|
||||
#### 在打开的 Excalidraw 视图中添加一个带框的文本元素
|
||||
|
||||
将新元素放置在当前选中元素的下方,并用箭头从选中的元素指向新添加的文本。
|
||||
|
||||
*使用 <kbd>CTRL+Shift+V</kbd> 将代码粘贴到 Obsidian 中!*
|
||||
|
||||
```javascript
|
||||
<%*
|
||||
const ea = ExcalidrawAutomate;
|
||||
ea.reset();
|
||||
ea.setView("first");
|
||||
selectedElement = ea.getViewSelectedElement();
|
||||
ea.setStrokeSharpness(0);
|
||||
const boxPadding = 5;
|
||||
id = ea.addText(
|
||||
selectedElement.x + boxPadding,
|
||||
selectedElement.y+selectedElement.height+100,
|
||||
"[[Next process step]]",
|
||||
{
|
||||
textAlign:"center",
|
||||
box:true,
|
||||
boxPadding:boxPadding,
|
||||
width:selectedElement.width-boxPadding*2,
|
||||
}
|
||||
);
|
||||
ea.setStrokeSharpness(1);
|
||||
ea.style.roughness= 0;
|
||||
ea.connectObjectWithViewSelectedElement(
|
||||
id,
|
||||
"top",
|
||||
"bottom",
|
||||
{
|
||||
numberOfPoints:2,
|
||||
startArrowHead:"arrow",
|
||||
endArrowHead:"dot",
|
||||
padding:5
|
||||
});
|
||||
ea.addElementsToView();
|
||||
%>
|
||||
```
|
||||
|
||||
[点击此处查看动画演示](https://user-images.githubusercontent.com/14358394/131967188-2a488e38-f742-49d9-ae98-33238a8d4712.mp4)
|
||||
94
docs/zh-cn/docs/API/objects.md
Normal file
@@ -0,0 +1,94 @@
|
||||
# [◀ Excalidraw 自动化使用指南](../readme.md)
|
||||
|
||||
## 添加对象
|
||||
|
||||
这些函数将向你的绘图中添加对象。画布是无限的,可以接受负数和正数的 X 和 Y 值。X 值从左到右递增,Y 值从上到下递增。
|
||||
|
||||

|
||||
|
||||
### addRect(), addDiamond(), addEllipse()
|
||||
|
||||
```typescript
|
||||
addRect(topX:number, topY:number, width:number, height:number):string
|
||||
addDiamond(topX:number, topY:number, width:number, height:number):string
|
||||
addEllipse(topX:number, topY:number, width:number, height:number):string
|
||||
```
|
||||
|
||||
返回对象的 `id`。当使用线条连接对象时需要用到这个 `id`,详见后文。
|
||||
|
||||
### addText()
|
||||
|
||||
```typescript
|
||||
addText(
|
||||
topX:number,
|
||||
topY:number,
|
||||
text:string,
|
||||
formatting?:{
|
||||
wrapAt?:number,
|
||||
width?:number,
|
||||
height?:number,
|
||||
textAlign?:string,
|
||||
box?: "box"|"blob"|"ellipse"|"diamond",
|
||||
boxPadding?:number
|
||||
},
|
||||
id?:string
|
||||
):string
|
||||
```
|
||||
|
||||
向绘图中添加文本。
|
||||
|
||||
格式化参数是可选的:
|
||||
- 如果未指定 `width` 和 `height`,函数将根据字体系列(fontFamily)、字体大小(fontSize)和提供的文本来计算宽度和高度。
|
||||
- 如果你想要将文本相对于绘图中的其他元素居中对齐,你可以提供固定的高度和宽度,并且可以像上面描述的那样指定 `textAlign` 和 `verticalAlign`。例如:`{width:500, textAlign:"center"}`
|
||||
- 如果你想在文本周围添加一个框,设置 `{box:"box"|"blob"|"ellipse"|"diamond"}`(分别对应矩形框、气泡框、椭圆框、菱形框)
|
||||
|
||||
返回对象的 `id`。当使用线条连接对象时需要用到这个 `id`,详见后文。如果设置了 `{box:}`,则返回包围框对象的 id。
|
||||
|
||||
### addLine()
|
||||
|
||||
```typescript
|
||||
addLine(points: [[x:number,y:number]]):string
|
||||
```
|
||||
|
||||
根据提供的点添加一条线。必须包含至少两个点 `points.length >= 2`。如果提供了超过 2 个点,中间点将被添加为断点。当 `strokeSharpness` 设置为 "sharp" 时,线条会以角度方式折断;设置为 "round" 时,线条会呈现曲线。
|
||||
|
||||
返回对象的 `id`。
|
||||
|
||||
### addArrow()
|
||||
|
||||
```typescript
|
||||
addArrow(points: [[x:number,y:number]],formatting?:{startArrowHead?:string,endArrowHead?:string,startObjectId?:string,endObjectId?:string}):string ;
|
||||
```
|
||||
|
||||
根据提供的点添加一个箭头。必须包含至少两个点 `points.length >= 2`。如果提供了超过 2 个点,中间点将被添加为断点。当元素的 `style.strokeSharpness` 设置为 "sharp" 时,线条会以角度方式折断;设置为 "round" 时,线条会呈现曲线。
|
||||
|
||||
`startArrowHead` 和 `endArrowHead` 指定要使用的箭头类型,如上所述。有效值包括 "none"(无)、"arrow"(箭头)、"dot"(圆点)和 "bar"(线条)。例如:`{startArrowHead: "dot", endArrowHead: "arrow"}`
|
||||
|
||||
`startObjectId` 和 `endObjectId` 是连接对象的 ID。如果是为了连接对象,建议使用 `connectObjects` 而不是调用 addArrow()。
|
||||
|
||||
返回对象的 `id`。
|
||||
|
||||
### connectObjects()
|
||||
|
||||
```typescript
|
||||
declare type ConnectionPoint = "top"|"bottom"|"left"|"right";
|
||||
connectObjects(objectA: string, connectionA: ConnectionPoint, objectB: string, connectionB: ConnectionPoint, formatting?:{numberOfPoints: number,startArrowHead:string,endArrowHead:string, padding: number}):void
|
||||
```
|
||||
|
||||
使用箭头连接两个对象。如果两个元素中的任何一个是 `line`(线条)、`arrow`(箭头)或 `freedraw`(自由绘制)类型,则不会执行任何操作。
|
||||
|
||||
`objectA` 和 `objectB` 是字符串类型,表示要连接的对象的 ID。这些 ID 是在创建对象时由 addRect()、addDiamond()、addEllipse() 和 addText() 函数返回的。
|
||||
|
||||
`connectionA` 和 `connectionB` 指定在对象上的连接位置。有效值包括:"top"(顶部)、"bottom"(底部)、"left"(左侧)和 "right"(右侧)。
|
||||
|
||||
`numberOfPoints` 设置线条的中间断点数量。默认值为零,表示箭头的起点和终点之间没有断点。当在绘图上移动对象时,这些断点会影响 Excalidraw 重新路由线条的方式。
|
||||
|
||||
`startArrowHead` 和 `endArrowHead` 的工作方式如上文 `addArrow()` 中所述。
|
||||
|
||||
### addToGroup()
|
||||
|
||||
```typescript
|
||||
addToGroup(objectIds:[]):string
|
||||
```
|
||||
|
||||
将 `objectIds` 中列出的对象组合成一个组。返回该组的 `id`。
|
||||
219
docs/zh-cn/docs/API/utility.md
Normal file
@@ -0,0 +1,219 @@
|
||||
# [◀ Excalidraw Automate How To](../readme.md)
|
||||
|
||||
## 实用工具函数
|
||||
|
||||
### isExcalidrawFile()
|
||||
```typescript
|
||||
isExcalidrawFile(f:TFile): boolean
|
||||
```
|
||||
如果提供的文件是有效的 Excalidraw 文件(可以是传统的 `*.excalidraw` 文件或在 front-matter 中包含 excalidraw 键的 markdown 文件),则返回 true。
|
||||
|
||||
### clear()
|
||||
`clear()` 将清除缓存中的对象,但会保留元素样式设置。
|
||||
|
||||
### reset()
|
||||
`reset()` 会先调用 `clear()`,然后将元素样式重置为默认值。
|
||||
|
||||
### toClipboard()
|
||||
```typescript
|
||||
async toClipboard(templatePath?:string)
|
||||
```
|
||||
将生成的绘图放置到剪贴板中。当你不想创建新的绘图,而是想将额外的元素粘贴到现有绘图上时,这个功能很有用。
|
||||
|
||||
### getElements()
|
||||
```typescript
|
||||
getElements():ExcalidrawElement[];
|
||||
```
|
||||
以数组形式返回 ExcalidrawAutomate 中的 ExcalidrawElement 元素。这种格式在使用 ExcalidrawRef 时特别有用。
|
||||
|
||||
### getElement()
|
||||
```typescript
|
||||
getElement(id:string):ExcalidrawElement;
|
||||
```
|
||||
返回与指定 id 匹配的元素对象。如果元素不存在,则返回 null。
|
||||
|
||||
### create()
|
||||
```typescript
|
||||
async create(params?:{filename: string, foldername:string, templatePath:string, onNewPane: boolean})
|
||||
```
|
||||
创建并打开绘图。返回创建文件的完整路径。
|
||||
|
||||
`filename` 是要创建的绘图文件名(不包含扩展名)。如果为 `null`,Excalidraw 将自动生成文件名。
|
||||
|
||||
`foldername` 是文件创建的目标文件夹。如果为 `null`,则会根据 Excalidraw 设置使用默认的新建绘图文件夹。
|
||||
|
||||
`templatePath` 是模板文件的完整路径(包含文件名和扩展名)。该模板文件将作为基础图层,所有通过 ExcalidrawAutomate 添加的对象都会显示在模板元素的上层。如果为 `null`,则不使用模板,即使用空白画布作为添加对象的基础。
|
||||
|
||||
`onNewPane` 定义新绘图的创建位置。`false` 将在当前活动页签中打开绘图。`true` 将通过垂直分割当前页签来打开绘图。
|
||||
|
||||
`frontmatterKeys` 是要应用到文档的 frontmatter 键值集合
|
||||
{
|
||||
excalidraw-plugin?: "raw"|"parsed",
|
||||
excalidraw-link-prefix?: string,
|
||||
excalidraw-link-brackets?: boolean,
|
||||
excalidraw-url-prefix?: string
|
||||
}
|
||||
|
||||
示例:
|
||||
```javascript
|
||||
create (
|
||||
{
|
||||
filename:"my drawing",
|
||||
foldername:"myfolder/subfolder/",
|
||||
templatePath: "Excalidraw/template.excalidraw",
|
||||
onNewPane: true,
|
||||
frontmatterKeys: {
|
||||
"excalidraw-plugin": "parsed",
|
||||
"excalidraw-link-prefix": "",
|
||||
"excalidraw-link-brackets": true,
|
||||
"excalidraw-url-prefix": "🌐",
|
||||
}
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### createSVG()
|
||||
```typescript
|
||||
async createSVG(templatePath?:string)
|
||||
```
|
||||
返回包含生成绘图的 HTML SVGSVGElement 元素。
|
||||
|
||||
### createPNG()
|
||||
```typescript
|
||||
async createPNG(templatePath?:string, scale:number=1)
|
||||
```
|
||||
返回包含生成绘图的 PNG 图像 blob 对象。
|
||||
|
||||
### wrapText()
|
||||
```typescript
|
||||
wrapText(text:string, lineLen:number):string
|
||||
```
|
||||
返回一个按照指定最大行长度换行的字符串。
|
||||
|
||||
### 访问打开的 Excalidraw 视图
|
||||
在使用任何视图操作函数之前,你需要先初始化 targetView。
|
||||
|
||||
#### targetView
|
||||
```typescript
|
||||
targetView: ExcalidrawView
|
||||
```
|
||||
已打开的 Excalidraw 视图,被配置为视图操作的目标。使用 `setView` 进行初始化。
|
||||
|
||||
#### setView()
|
||||
```typescript
|
||||
setView(view:ExcalidrawView|"first"|"active"):ExcalidrawView
|
||||
```
|
||||
设置将作为视图操作目标的 ExcalidrawView。有效的 `view` 输入值包括:
|
||||
- ExcalidrawView 的对象实例
|
||||
- "first":如果打开了多个 Excalidraw 视图,则选择 `app.workspace.getLeavesOfType("Excalidraw")` 返回的第一个视图
|
||||
- "active":表示当前活动的视图
|
||||
|
||||
#### getExcalidrawAPI()
|
||||
```typescript
|
||||
getExcalidrawAPI():any
|
||||
```
|
||||
返回在 `targetView` 中指定的当前活动绘图的原生 Excalidraw API(ref.current)。
|
||||
查看 Excalidraw 文档请访问:https://www.npmjs.com/package/@excalidraw/excalidraw#ref
|
||||
|
||||
#### getViewElements()
|
||||
```typescript
|
||||
getViewElements():ExcalidrawElement[]
|
||||
```
|
||||
返回视图中的所有元素。
|
||||
|
||||
#### deleteViewElements()
|
||||
```typescript
|
||||
deleteViewElements(elToDelete: ExcalidrawElement[]):boolean
|
||||
```
|
||||
从视图中删除与输入参数中提供的元素相匹配的元素。
|
||||
|
||||
示例:从视图中删除选中的元素:
|
||||
```typescript
|
||||
ea = ExcalidrawAutomate;
|
||||
ea.setView("active");
|
||||
el = ea.getViewSelectedElements();
|
||||
ea.deleteViewElements();
|
||||
```
|
||||
|
||||
#### getViewSelectedElement()
|
||||
```typescript
|
||||
getViewSelectedElement():ExcalidrawElement
|
||||
```
|
||||
首先需要调用 `setView()` 来设置视图。
|
||||
|
||||
如果在目标视图 (targetView) 中选中了一个元素,该函数将返回被选中的元素。如果选中了多个元素(通过 <kbd>SHIFT+点击</kbd> 选择多个元素,或者选择一个组),将返回第一个元素。如果你想从一个组中指定要选择的元素,请双击该组中想要的元素。
|
||||
|
||||
当你想要添加一个与绘图中现有元素相关的新元素时,这个函数会很有帮助。
|
||||
|
||||
#### getViewSelectedElements()
|
||||
```typescript
|
||||
getViewSelectedElements():ExcalidrawElement[]
|
||||
```
|
||||
首先需要调用 `setView()` 来设置视图。
|
||||
|
||||
获取场景中选中元素的数组。如果没有选中任何元素,则返回 []。
|
||||
|
||||
注意:你可以调用 `getExcalidrawAPI().getSceneElements()` 来获取场景中的所有元素。
|
||||
|
||||
#### viewToggleFullScreen()
|
||||
```typescript
|
||||
viewToggleFullScreen(forceViewMode?:boolean):void;
|
||||
```
|
||||
在目标视图 (targetView) 中切换全屏模式和普通模式。通过将 forceViewMode 设置为 `true` 可以将 Excalidraw 切换到查看模式。默认值为 `false`。
|
||||
|
||||
此功能在 Obsidian 移动端上不生效。
|
||||
|
||||
#### connectObjectWithViewSelectedElement()
|
||||
```typescript
|
||||
connectObjectWithViewSelectedElement(objectA:string,connectionA: ConnectionPoint, connectionB: ConnectionPoint, formatting?:{numberOfPoints?: number,startArrowHead?:string,endArrowHead?:string, padding?: number}):boolean
|
||||
```
|
||||
与 `connectObjects()` 功能相同,但 ObjectB 是目标 ExcalidrawView 中当前选中的元素。该函数有助于在新创建的对象和目标 ExcalidrawView 中选中的元素之间放置一个箭头。
|
||||
|
||||
#### addElementsToView()
|
||||
```typescript
|
||||
async addElementsToView(repositionToCursor:boolean=false, save:boolean=false):Promise<boolean>
|
||||
```
|
||||
将使用 ExcalidrawAutomate 创建的元素添加到目标 ExcalidrawView 中。
|
||||
|
||||
`repositionToCursor` 默认值为 false
|
||||
- true:元素将被移动,使其中心点与 ExcalidrawView 上当前指针的位置对齐。你可以使用此开关将元素指向并放置到绘图中的所需位置。
|
||||
- false:元素将按照每个元素的 x&y 坐标定义的位置进行放置。
|
||||
|
||||
`save` 默认值为 false
|
||||
- true:元素添加后绘图将被保存。
|
||||
- false:绘图将在下一个自动保存周期时保存。当连续添加多个元素时使用 false。否则,最好使用 true 以最小化数据丢失的风险。
|
||||
|
||||
### onDropHook
|
||||
```typescript
|
||||
onDropHook (data: {
|
||||
ea: ExcalidrawAutomate,
|
||||
event: React.DragEvent<HTMLDivElement>,
|
||||
draggable: any, //Obsidian draggable object
|
||||
type: "file"|"text"|"unknown",
|
||||
payload: {
|
||||
files: TFile[], //TFile[] array of dropped files
|
||||
text: string, //string
|
||||
},
|
||||
excalidrawFile: TFile, //the file receiving the drop event
|
||||
view: ExcalidrawView, //the excalidraw view receiving the drop
|
||||
pointerPosition: {x:number, y:number} //the pointer position on canvas at the time of drop
|
||||
}):boolean;
|
||||
```
|
||||
当可拖拽项被拖放到 Excalidraw 上时触发的回调函数。
|
||||
|
||||
该函数应返回一个布尔值。如果拖放由钩子函数处理且应停止进一步的原生处理,则返回 true;如果应让 Excalidraw 继续处理拖放操作,则返回 false。
|
||||
|
||||
拖放类型可以是以下之一:
|
||||
- "file":当从 Obsidian 文件浏览器中拖放文件到 Excalidraw 时。在这种情况下,payload.files 将包含被拖放文件的列表。
|
||||
- "text":当拖放链接(如 URL 或 wiki 链接)或其他文本时。在这种情况下,payload.text 将包含接收到的字符串。
|
||||
- "unknown":当 Excalidraw 插件无法识别拖放对象的类型时。在这种情况下,你可以使用 React.DragEvent 来分析拖放的对象。
|
||||
|
||||
使用 Templater 启动模板或类似方法来设置钩子函数。
|
||||
|
||||
```typescript
|
||||
ea = ExcalidrawAutomate;
|
||||
ea.onDropHook = (data) => {
|
||||
console.log(data);
|
||||
return false;
|
||||
}
|
||||
```
|
||||
28
docs/zh-cn/docs/Examples/apply_template.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# [◀ Excalidraw 自动化使用指南](../readme.md)
|
||||
|
||||
## 将 Excalidraw 模板应用到新绘图
|
||||
|
||||
这个示例与介绍中的类似,只是将图形旋转了90度,并且使用了模板,同时指定了保存绘图的文件名和文件夹,还会在新窗格中打开这个新绘图。
|
||||
|
||||
*使用 <kbd>CTRL+Shift+V</kbd> 将代码粘贴到 Obsidian 中!*
|
||||
|
||||
```javascript
|
||||
<%*
|
||||
const ea = ExcalidrawAutomate;
|
||||
ea.reset();
|
||||
ea.style.angle = Math.PI/2;
|
||||
ea.style.strokeWidth = 3.5;
|
||||
ea.addRect(-150,-50,450,300);
|
||||
ea.addText(-100,70,"Left to right");
|
||||
ea.addArrow([[-100,100],[100,100]]);
|
||||
|
||||
ea.style.strokeColor = "red";
|
||||
await ea.addText(100,-30,"top to bottom",{width:200,textAlign:"center"});
|
||||
ea.addArrow([[200,0],[200,200]]);
|
||||
await ea.create({
|
||||
filename :"My Drawing",
|
||||
foldername :"myfolder/fordemo/",
|
||||
templatePath:"Excalidraw/Template2.excalidraw",
|
||||
onNewPane :true});
|
||||
%>
|
||||
```
|
||||
21
docs/zh-cn/docs/Examples/connect_objects.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# [◀ Excalidraw Automate 使用指南](../readme.md)
|
||||
|
||||
## 连接对象
|
||||
|
||||
这个 [Templater](https://github.com/SilentVoid13/Templater) 模板演示了如何使用 ExcalidrawAutomate 连接两个对象。
|
||||
|
||||
*使用 <kbd>CTRL+Shift+V</kbd> 将代码粘贴到 Obsidian 中!*
|
||||
|
||||
```javascript
|
||||
<%*
|
||||
const ea = ExcalidrawAutomate;
|
||||
ea.reset();
|
||||
ea.addText(-130,-100,"Connecting two objects");
|
||||
const a = ea.addRect(-100,-100,100,100);
|
||||
const b = ea.addEllipse(200,200,100,100);
|
||||
ea.connectObjects(a,"bottom",b,"left",{numberOfPoints: 2}); //see how the line breaks differently when moving objects around
|
||||
ea.style.strokeColor = "red";
|
||||
ea.connectObjects(a,"right",b,"top",1);
|
||||
await ea.create();
|
||||
%>
|
||||
```
|
||||
70
docs/zh-cn/docs/Examples/dataviewjs_familytree.md
Normal file
@@ -0,0 +1,70 @@
|
||||
# [◀ Excalidraw Automate 使用指南](../readme.md)
|
||||
|
||||
## 使用 dataviewjs 生成家谱树
|
||||
|
||||
这个示例与使用 dataviewjs 生成思维导图的脚本类似,但输出结果是垂直呈现的。
|
||||
|
||||
### 输出效果
|
||||
|
||||

|
||||
|
||||
### 输入文件
|
||||
|
||||
任务列表格式如下:
|
||||
|
||||
```markdown
|
||||
- [ ] OBSIDIAN
|
||||
- [ ] Silver
|
||||
- [ ] PawPaw Silv
|
||||
- [ ] MawMaw Silv
|
||||
- [ ] Licat
|
||||
- [ ] PeePaw Li
|
||||
- [ ] MeeMaw Li
|
||||
```
|
||||
|
||||
### dataviewjs 脚本
|
||||
|
||||
渲染 Excalidraw 图形的代码如下:
|
||||
|
||||
```javascript
|
||||
function crawl(subtasks) {
|
||||
let size = subtasks.length > 0 ? 0 : 1; //if no children then a leaf with size 1
|
||||
for (let task of subtasks) {
|
||||
task["size"] = crawl(task.subtasks);
|
||||
size += task.size;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
const tasks = dv.page("FamilyTree.md").file.tasks[0];
|
||||
tasks["size"] = crawl(tasks.subtasks);
|
||||
|
||||
const width = 300;
|
||||
const height = 150;
|
||||
const ea = ExcalidrawAutomate;
|
||||
ea.reset();
|
||||
|
||||
function buildMindmap(subtasks, depth, offset, parentObjectID) {
|
||||
if (subtasks.length == 0) return;
|
||||
let task;
|
||||
|
||||
for (let i = 0; i < subtasks.length; i++) {
|
||||
task = subtasks[i]
|
||||
if (depth == 1) ea.style.strokeColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16).padStart(6,"0");
|
||||
task["objectID"] = ea.addText((task.size/2+offset)*width,depth*height,task.text,{box:true})
|
||||
ea.connectObjects(parentObjectID,"top",task.objectID,"bottom",{startArrowHead: 'arrow', endArrowHead: 'dot'});
|
||||
if (i >= 1) {
|
||||
ea.connectObjects(subtasks[i-1]['objectID'],"right",task.objectID,"left", {endArrowHead: 'none'});
|
||||
}
|
||||
|
||||
buildMindmap(task.subtasks, depth-1,offset,task.objectID);
|
||||
offset += task.size/1.5;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
tasks["objectID"] = ea.addText(width*1.5,height*(tasks.size-1),tasks.text,{box:true, textAlign:"center"});
|
||||
buildMindmap(tasks.subtasks, 2, 0, tasks.objectID);
|
||||
|
||||
ea.createSVG().then((svg)=>dv.span(svg.outerHTML));
|
||||
```
|
||||
64
docs/zh-cn/docs/Examples/dataviewjs_mindmap.md
Normal file
@@ -0,0 +1,64 @@
|
||||
# [◀ Excalidraw Automate 使用指南](../readme.md)
|
||||
|
||||
## 使用 dataviewjs 从任务列表生成思维导图
|
||||
|
||||
这个方法与使用 templater 生成思维导图的脚本类似,但由于 dataview 已经以树形结构返回任务,所以实现起来稍微简单一些
|
||||
|
||||
### 输出效果
|
||||
|
||||

|
||||
|
||||
### 输入文件
|
||||
|
||||
输入文件是 `Demo.md`,其内容如下:
|
||||
|
||||
```markdown
|
||||
- [ ] Root task
|
||||
- [ ] task 1.1
|
||||
- [ ] task 1.2
|
||||
- [ ] task 1.2.1
|
||||
- [ ] task 1.2.2
|
||||
- [ ] task 1.3
|
||||
- [ ] task 1.3.1
|
||||
```
|
||||
|
||||
### dataviewjs 脚本
|
||||
|
||||
`dataviewjs` 脚本如下所示:
|
||||
|
||||
*使用 <kbd>CTRL+Shift+V</kbd> 将代码粘贴到 Obsidian 中!*
|
||||
|
||||
```javascript
|
||||
function crawl(subtasks) {
|
||||
let size = subtasks.length > 0 ? 0 : 1; //if no children then a leaf with size 1
|
||||
for (let task of subtasks) {
|
||||
task["size"] = crawl(task.subtasks);
|
||||
size += task.size;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
const tasks = dv.page("Demo.md").file.tasks[0];
|
||||
tasks["size"] = crawl(tasks.subtasks);
|
||||
|
||||
const width = 300;
|
||||
const height = 100;
|
||||
const ea = ExcalidrawAutomate;
|
||||
ea.reset();
|
||||
|
||||
function buildMindmap(subtasks, depth, offset, parentObjectID) {
|
||||
if (subtasks.length == 0) return;
|
||||
for (let task of subtasks) {
|
||||
if (depth == 1) ea.style.strokeColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16).padStart(6,"0");
|
||||
task["objectID"] = ea.addText(depth*width,(task.size/2+offset)*height,task.text,{box:true})
|
||||
ea.connectObjects(parentObjectID,"right",task.objectID,"left",{startArrowHead: 'dot'});
|
||||
buildMindmap(task.subtasks, depth+1,offset,task.objectID);
|
||||
offset += task.size;
|
||||
}
|
||||
}
|
||||
|
||||
tasks["objectID"] = ea.addText(0,(tasks.size/2)*height,tasks.text,{box:true});
|
||||
buildMindmap(tasks.subtasks, 1, 0, tasks.objectID);
|
||||
|
||||
ea.createSVG().then((svg)=>dv.span(svg.outerHTML));
|
||||
```
|
||||
26
docs/zh-cn/docs/Examples/insert_new_drawing.md
Normal file
@@ -0,0 +1,26 @@
|
||||
# [◀ Excalidraw 自动化使用指南](../readme.md)
|
||||
|
||||
## 在当前编辑的文档中插入新绘图
|
||||
|
||||
这个 [Templater](https://github.com/SilentVoid13/Templater) 模板会提示你输入绘图的标题。它将使用提供的标题创建一个新的绘图,并将其保存在你正在编辑的文档所在的文件夹中。然后,它会在光标位置嵌入新绘图,并通过拆分当前页面的方式在新的工作区中打开这个绘图。
|
||||
|
||||
*使用 <kbd>CTRL+Shift+V</kbd> 将代码粘贴到 Obsidian 中!*
|
||||
|
||||
```javascript
|
||||
<%*
|
||||
const defaultTitle = tp.date.now("HHmm")+' '+tp.file.title;
|
||||
const title = await tp.system.prompt("Title of the drawing?", defaultTitle);
|
||||
const folder = tp.file.folder(true);
|
||||
const transcludePath = (folder== '/' ? '' : folder + '/') + title + '.excalidraw';
|
||||
tR = '![['+transcludePath+']]';
|
||||
const ea = ExcalidrawAutomate;
|
||||
ea.reset();
|
||||
ea.setTheme(1); //set Theme to dark
|
||||
await ea.create({
|
||||
filename : title,
|
||||
foldername : folder,
|
||||
//templatePath: 'Excalidraw/Template.excalidraw', //uncomment if you want to use a template
|
||||
onNewPane : true
|
||||
});
|
||||
%>
|
||||
```
|
||||
103
docs/zh-cn/docs/Examples/templater_mindmap.md
Normal file
@@ -0,0 +1,103 @@
|
||||
# [◀ Excalidraw Automate 使用指南](../readme.md)
|
||||
|
||||
## 从文本大纲生成简单思维导图
|
||||
|
||||
这是一个稍微复杂一点的示例。它将从制表符缩进的大纲生成思维导图。
|
||||
|
||||
### 输出效果
|
||||
|
||||

|
||||
|
||||
### 输入文件
|
||||
|
||||
示例输入:
|
||||
```
|
||||
- Test 1
|
||||
- Test 1.1
|
||||
- Test 2
|
||||
- Test 2.1
|
||||
- Test 2.2
|
||||
- Test 2.2.1
|
||||
- Test 2.2.2
|
||||
- Test 2.2.3
|
||||
- Test 2.2.3.1
|
||||
- Test 3
|
||||
- Test 3.1
|
||||
```
|
||||
|
||||
### Templater 脚本
|
||||
|
||||
*使用 <kbd>CTRL+Shift+V</kbd> 将代码粘贴到 Obsidian 中!*
|
||||
|
||||
```javascript
|
||||
<%*
|
||||
const IDX = Object.freeze({"depth":0, "text":1, "parent":2, "size":3, "children": 4, "objectId":5});
|
||||
|
||||
//check if an editor is the active view
|
||||
const editor = this.app.workspace.activeLeaf?.view?.editor;
|
||||
if(!editor) return;
|
||||
|
||||
//initialize the tree with the title of the document as the first element
|
||||
let tree = [[0,this.app.workspace.activeLeaf?.view?.getDisplayText(),-1,0,[],0]];
|
||||
const linecount = editor.lineCount();
|
||||
|
||||
//helper function, use regex to calculate indentation depth, and to get line text
|
||||
function getLineProps (i) {
|
||||
props = editor.getLine(i).match(/^(\t*)-\s+(.*)/);
|
||||
return [props[1].length+1, props[2]];
|
||||
}
|
||||
|
||||
//a vector that will hold last valid parent for each depth
|
||||
let parents = [0];
|
||||
|
||||
//load outline into tree
|
||||
for(i=0;i<linecount;i++) {
|
||||
[depth,text] = getLineProps(i);
|
||||
if(depth>parents.length) parents.push(i+1);
|
||||
else parents[depth] = i+1;
|
||||
tree.push([depth,text,parents[depth-1],1,[]]);
|
||||
tree[parents[depth-1]][IDX.children].push(i+1);
|
||||
}
|
||||
|
||||
//recursive function to crawl the tree and identify height aka. size of each node
|
||||
function crawlTree(i) {
|
||||
if(i>linecount) return 0;
|
||||
size = 0;
|
||||
if((i+1<=linecount && tree[i+1][IDX.depth] <= tree[i][IDX.depth])|| i == linecount) { //I am a leaf
|
||||
tree[i][IDX.size] = 1;
|
||||
return 1;
|
||||
}
|
||||
tree[i][IDX.children].forEach((node)=>{
|
||||
size += crawlTree(node);
|
||||
});
|
||||
tree[i][IDX.size] = size;
|
||||
return size;
|
||||
}
|
||||
|
||||
crawlTree(0);
|
||||
|
||||
//Build the mindmap in Excalidraw
|
||||
const width = 300;
|
||||
const height = 100;
|
||||
const ea = ExcalidrawAutomate;
|
||||
ea.reset();
|
||||
|
||||
//stores position offset of branch/leaf in height units
|
||||
offsets = [0];
|
||||
|
||||
for(i=0;i<=linecount;i++) {
|
||||
depth = tree[i][IDX.depth];
|
||||
if (depth == 1) ea.style.strokeColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16).padStart(6,"0");
|
||||
tree[i][IDX.objectId] = ea.addText(depth*width,((tree[i][IDX.size]/2)+offsets[depth])*height,tree[i][IDX.text],{box:true});
|
||||
//set child offset equal to parent offset
|
||||
if((depth+1)>offsets.length) offsets.push(offsets[depth]);
|
||||
else offsets[depth+1] = offsets[depth];
|
||||
offsets[depth] += tree[i][IDX.size];
|
||||
if(tree[i][IDX.parent]!=-1) {
|
||||
ea.connectObjects(tree[tree[i][IDX.parent]][IDX.objectId],"right",tree[i][IDX.objectId],"left",{startArrowHead: 'dot'});
|
||||
}
|
||||
}
|
||||
|
||||
await ea.create({onNewPane: true});
|
||||
%>
|
||||
```
|
||||
410
docs/zh-cn/docs/ExcalidrawScriptsEngine.md
Normal file
@@ -0,0 +1,410 @@
|
||||
# [◀ Excalidraw 自动化使用指南](./readme.md)
|
||||
|
||||
> 此说明当前更新至 `768aebf`。
|
||||
|
||||
【[English](../../ExcalidrawScriptsEngine.md) | 简体中文】
|
||||
|
||||
[](https://youtu.be/hePJcObHIso)
|
||||
|
||||
## 简介
|
||||
|
||||
请将你的 ExcalidrawAutomate 脚本放入 Excalidraw 设置中定义的文件夹中。脚本文件夹不能是你的 Vault 根目录。
|
||||
|
||||

|
||||
|
||||
EA 脚本可以是 markdown 文件、纯文本文件或 .js 文件。唯一的要求是它们必须包含有效的 JavaScript 代码。
|
||||
|
||||

|
||||
|
||||
你可以通过 Obsidian 命令面板从 Excalidraw 访问你的脚本。
|
||||
|
||||

|
||||
|
||||
这样你就可以像设置其他 Obsidian 命令一样,为你喜欢的脚本分配快捷键。
|
||||
|
||||

|
||||
|
||||
## 脚本开发
|
||||
|
||||
Excalidraw 脚本会自动接收两个对象:
|
||||
|
||||
- `ea`:脚本引擎会初始化 `ea` 对象,包括设置调用脚本时的活动视图为当前视图。
|
||||
- `utils`:我从 [QuickAdd](https://github.com/chhoumann/quickadd/blob/master/docs/QuickAddAPI.md) 借用了一些实用函数,但目前并非所有 QuickAdd 实用函数都在 Excalidraw 中实现。目前可用的函数如下。详见下方示例。
|
||||
- `inputPrompt: (header: string, placeholder?: string, value?: string, buttons?: [{caption:string, action:Function}])`
|
||||
- 打开一个提示框请求输入。返回输入的字符串。
|
||||
- 你需要使用 await 等待 inputPrompt 的结果。
|
||||
- `buttons.action(input: string) => string`。按钮动作将接收当前输入字符串。如果动作返回 null,输入将保持不变。如果动作返回字符串,inputPrompt 将解析为该值。
|
||||
```typescript
|
||||
let fileType = "";
|
||||
const filename = await utils.inputPrompt (
|
||||
"Filename for new document",
|
||||
"Placeholder",
|
||||
"DefaultFilename.md",
|
||||
[
|
||||
{
|
||||
caption: "Markdown",
|
||||
action: ()=>{fileType="md";return;}
|
||||
},
|
||||
{
|
||||
caption: "Excalidraw",
|
||||
action: ()=>{fileType="ex";return;}
|
||||
}
|
||||
]
|
||||
);
|
||||
|
||||
```
|
||||
- `suggester: (displayItems: string[], items: any[], hint?: string, instructions?:Instruction[])`
|
||||
- 打开一个建议器。显示 displayItems 并返回 items[] 中对应的项。
|
||||
- 你需要使用 await 等待 suggester 的结果。
|
||||
- 如果用户取消(按ESC键),suggester 将返回 `undefined`
|
||||
- Hint(提示)和 instructions(说明)参数是可选的。
|
||||
```typescript
|
||||
interface Instruction {
|
||||
command: string;
|
||||
purpose: string;
|
||||
}
|
||||
```
|
||||
- 脚本可以有设置。这些设置作为插件设置的一部分存储,用户也可以通过 Obsidian 插件设置窗口更改。
|
||||
- 你可以使用 `ea.getScriptSettings()` 访问当前脚本的设置,并使用 `ea.setScriptSettings(settings:any)` 存储设置值
|
||||
- 在插件设置中显示脚本设置的规则如下:
|
||||
- 如果设置是简单的字面量(布尔值、数字、字符串),这些将按原样显示在设置中。设置的名称将作为值的键。
|
||||
```javascript
|
||||
ea.setScriptSettings({
|
||||
"value 1": true,
|
||||
"value 2": 1,
|
||||
"value 3": "my string"
|
||||
})
|
||||
```
|
||||

|
||||
- 如果设置是一个对象并遵循以下结构,则可以添加描述和值集。也可以使用 `hidden` 键从用户界面中隐藏值。
|
||||
```javascript
|
||||
ea.setScriptSettings({
|
||||
"value 1": {
|
||||
"value": true,
|
||||
"description": "This is the description for my boolean value"
|
||||
},
|
||||
"value 2": {
|
||||
"value": 1,
|
||||
"description": "This is the description for my numeric value"
|
||||
},
|
||||
"value 3": {
|
||||
"value": "my string",
|
||||
"description": "This is the description for my string value",
|
||||
"valueset": ["allowed 1","allowed 2","allowed 3"]
|
||||
},
|
||||
"value 4": {
|
||||
"value": "my value",
|
||||
"hidden": true
|
||||
}
|
||||
});
|
||||
```
|
||||

|
||||
|
||||
---------
|
||||
|
||||
## Excalidraw 自动化脚本示例
|
||||
|
||||
这些脚本可以在 GitHub [这个](https://github.com/zsviczian/obsidian-excalidraw-plugin/tree/master/ea-scripts)文件夹 📂 中下载为 `.md` 文件。
|
||||
|
||||
### 为选中元素添加边框
|
||||
|
||||

|
||||
|
||||
此脚本将在 Excalidraw 中当前选中的元素周围添加一个包围框
|
||||
|
||||
```javascript
|
||||
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.5.21")) {
|
||||
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
|
||||
return;
|
||||
}
|
||||
|
||||
settings = ea.getScriptSettings();
|
||||
//check if settings exist. If not, set default values on first run
|
||||
if(!settings["Default padding"]) {
|
||||
settings = {
|
||||
"Prompt for padding?": true,
|
||||
"Default padding" : {
|
||||
value: 10,
|
||||
description: "Padding between the bounding box of the selected elements, and the box the script creates"
|
||||
}
|
||||
};
|
||||
ea.setScriptSettings(settings);
|
||||
}
|
||||
|
||||
let padding = settings["Default padding"].value;
|
||||
|
||||
if(settings["Prompt for padding?"]) {
|
||||
padding = parseInt (await utils.inputPrompt("padding?","number",padding.toString()));
|
||||
}
|
||||
|
||||
if(isNaN(padding)) {
|
||||
new Notice("The padding value provided is not a number");
|
||||
return;
|
||||
}
|
||||
elements = ea.getViewSelectedElements();
|
||||
const box = ea.getBoundingBox(elements);
|
||||
color = ea
|
||||
.getExcalidrawAPI()
|
||||
.getAppState()
|
||||
.currentItemStrokeColor;
|
||||
//uncomment for random color:
|
||||
//color = '#'+(Math.random()*0xFFFFFF<<0).toString(16).padStart(6,"0");
|
||||
ea.style.strokeColor = color;
|
||||
id = ea.addRect(
|
||||
box.topX - padding,
|
||||
box.topY - padding,
|
||||
box.width + 2*padding,
|
||||
box.height + 2*padding
|
||||
);
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
ea.addToGroup([id].concat(elements.map((el)=>el.id)));
|
||||
ea.addElementsToView(false);
|
||||
```
|
||||
|
||||
----
|
||||
|
||||
### 用箭头连接选中的元素
|
||||
|
||||

|
||||
|
||||
此脚本将用箭头连接两个对象。如果任一对象是一组分组元素(例如,一个文本元素与一个包围它的矩形分组),脚本会识别这些组,并将箭头连接到组中最大的对象(假设你想将箭头连接到文本元素周围的框)。
|
||||
```javascript
|
||||
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.5.21")) {
|
||||
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
|
||||
return;
|
||||
}
|
||||
|
||||
settings = ea.getScriptSettings();
|
||||
//set default values on first run
|
||||
if(!settings["Starting arrowhead"]) {
|
||||
settings = {
|
||||
"Starting arrowhead" : {
|
||||
value: "none",
|
||||
valueset: ["none","arrow","triangle","bar","dot"]
|
||||
},
|
||||
"Ending arrowhead" : {
|
||||
value: "triangle",
|
||||
valueset: ["none","arrow","triangle","bar","dot"]
|
||||
},
|
||||
"Line points" : {
|
||||
value: 1,
|
||||
description: "Number of line points between start and end"
|
||||
}
|
||||
};
|
||||
ea.setScriptSettings(settings);
|
||||
}
|
||||
|
||||
const arrowStart = settings["Starting arrowhead"].value === "none" ? null : settings["Starting arrowhead"].value;
|
||||
const arrowEnd = settings["Ending arrowhead"].value === "none" ? null : settings["Ending arrowhead"].value;
|
||||
const linePoints = Math.floor(settings["Line points"].value);
|
||||
|
||||
const elements = ea.getViewSelectedElements();
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
groups = ea.getMaximumGroups(elements);
|
||||
|
||||
if(groups.length !== 2) {
|
||||
//unfortunately getMaxGroups returns duplicated resultset for sticky notes
|
||||
//needs additional filtering
|
||||
cleanGroups=[];
|
||||
idList = [];
|
||||
for (group of groups) {
|
||||
keep = true;
|
||||
for(item of group) if(idList.contains(item.id)) keep = false;
|
||||
if(keep) {
|
||||
cleanGroups.push(group);
|
||||
idList = idList.concat(group.map(el=>el.id))
|
||||
}
|
||||
}
|
||||
if(cleanGroups.length !== 2) return;
|
||||
groups = cleanGroups;
|
||||
}
|
||||
|
||||
els = [
|
||||
ea.getLargestElement(groups[0]),
|
||||
ea.getLargestElement(groups[1])
|
||||
];
|
||||
|
||||
ea.style.strokeColor = els[0].strokeColor;
|
||||
ea.style.strokeWidth = els[0].strokeWidth;
|
||||
ea.style.strokeStyle = els[0].strokeStyle;
|
||||
ea.style.strokeSharpness = els[0].strokeSharpness;
|
||||
|
||||
ea.connectObjects(
|
||||
els[0].id,
|
||||
null,
|
||||
els[1].id,
|
||||
null,
|
||||
{
|
||||
endArrowHead: arrowEnd,
|
||||
startArrowHead: arrowStart,
|
||||
numberOfPoints: linePoints
|
||||
}
|
||||
);
|
||||
ea.addElementsToView();
|
||||
```
|
||||
|
||||
----
|
||||
### 反转选中的箭头
|
||||
|
||||

|
||||
|
||||
反转选中元素范围内**箭头**的方向。
|
||||
|
||||
```javascript
|
||||
elements = ea.getViewSelectedElements().filter((el)=>el.type==="arrow");
|
||||
if(!elements || elements.length===0) return;
|
||||
elements.forEach((el)=>{
|
||||
const start = el.startArrowhead;
|
||||
el.startArrowhead = el.endArrowhead;
|
||||
el.endArrowhead = start;
|
||||
});
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
ea.addElementsToView();
|
||||
```
|
||||
|
||||
----
|
||||
|
||||
### 设置选中元素的线条宽度
|
||||
|
||||

|
||||
|
||||
当你缩放自由绘制的草图并想要减小或增加它们的线条宽度时,这个脚本会很有帮助。
|
||||
```javascript
|
||||
let width = (ea.getViewSelectedElement().strokeWidth??1).toString();
|
||||
width = await utils.inputPrompt("Width?","number",width);
|
||||
const elements=ea.getViewSelectedElements();
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
ea.getElements().forEach((el)=>el.strokeWidth=width);
|
||||
ea.addElementsToView();
|
||||
```
|
||||
|
||||
----
|
||||
|
||||
### 设置网格大小
|
||||
|
||||

|
||||
|
||||
Excalidraw 中默认的网格大小是 20。目前通过用户界面无法更改网格大小。
|
||||
```javascript
|
||||
const grid = parseInt(await utils.inputPrompt("Grid size?",null,"20"));
|
||||
const api = ea.getExcalidrawAPI();
|
||||
let appState = api.getAppState();
|
||||
appState.gridSize = grid;
|
||||
api.updateScene({
|
||||
appState,
|
||||
commitToHistory:false
|
||||
});
|
||||
```
|
||||
|
||||
----
|
||||
|
||||
### 设置元素尺寸和位置
|
||||
|
||||

|
||||
|
||||
目前在 Excalidraw 中还没有办法指定对象的精确位置和大小。你可以使用以下简单脚本来解决这个问题。
|
||||
```javascript
|
||||
const elements = ea.getViewSelectedElements();
|
||||
if(elements.length === 0) return;
|
||||
const el = ea.getLargestElement(elements);
|
||||
const sizeIn = [el.x,el.y,el.width,el.height].join(",");
|
||||
let res = await utils.inputPrompt("x,y,width,height?",null,sizeIn);
|
||||
res = res.split(",");
|
||||
if(res.length !== 4) return;
|
||||
let size = [];
|
||||
for (v of res) {
|
||||
const i = parseInt(v);
|
||||
if(isNaN(i)) return;
|
||||
size.push(i);
|
||||
}
|
||||
el.x = size[0];
|
||||
el.y = size[1];
|
||||
el.width = size[2];
|
||||
el.height = size[3];
|
||||
ea.copyViewElementsToEAforEditing([el]);
|
||||
ea.addElementsToView();
|
||||
```
|
||||
|
||||
----
|
||||
|
||||
### 项目符号
|
||||
|
||||

|
||||
|
||||
此脚本会在选中的每个文本元素的左上角添加一个小圆圈,并将文本和"项目符号"组合成一个组。
|
||||
```javascript
|
||||
elements = ea.getViewSelectedElements().filter((el)=>el.type==="text");
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
const padding = 10;
|
||||
elements.forEach((el)=>{
|
||||
ea.style.strokeColor = el.strokeColor;
|
||||
const size = el.fontSize/2;
|
||||
const ellipseId = ea.addEllipse(
|
||||
el.x-padding-size,
|
||||
el.y+size/2,
|
||||
size,
|
||||
size
|
||||
);
|
||||
ea.addToGroup([el.id,ellipseId]);
|
||||
});
|
||||
ea.addElementsToView();
|
||||
```
|
||||
|
||||
----
|
||||
|
||||
### 按行分割文本
|
||||
|
||||
**!!!需要 Excalidraw 1.5.1 或更高版本**
|
||||
|
||||

|
||||
|
||||
将文本块按行分割成单独的文本元素,以便更容易重新组织
|
||||
```javascript
|
||||
elements = ea.getViewSelectedElements().filter((el)=>el.type==="text");
|
||||
elements.forEach((el)=>{
|
||||
ea.style.strokeColor = el.strokeColor;
|
||||
ea.style.fontFamily = el.fontFamily;
|
||||
ea.style.fontSize = el.fontSize;
|
||||
const text = el.text.split("\n");
|
||||
for(i=0;i<text.length;i++) {
|
||||
ea.addText(el.x,el.y+i*el.height/text.length,text[i]);
|
||||
}
|
||||
});
|
||||
ea.addElementsToView();
|
||||
ea.deleteViewElements(elements);
|
||||
```
|
||||
|
||||
----
|
||||
|
||||
### 设置文本对齐方式
|
||||
|
||||

|
||||
|
||||
设置文本块的对齐方式(居中、右对齐、左对齐)。如果你想为选择文本对齐方式设置键盘快捷键,这个脚本会很有用。
|
||||
```javascript
|
||||
elements = ea.getViewSelectedElements().filter((el)=>el.type==="text");
|
||||
if(elements.length===0) return;
|
||||
let align = ["left","right","center"];
|
||||
align = await utils.suggester(align,align);
|
||||
elements.forEach((el)=>el.textAlign = align);
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
ea.addElementsToView();
|
||||
```
|
||||
|
||||
----
|
||||
|
||||
### 设置字体
|
||||
|
||||

|
||||
|
||||
设置文本块的字体(Virgil、Helvetica、Cascadia)。如果你想为选择字体设置键盘快捷键,这个功能会很有用。
|
||||
```javascript
|
||||
elements = ea.getViewSelectedElements().filter((el)=>el.type==="text");
|
||||
if(elements.length===0) return;
|
||||
let font = ["Virgil","Helvetica","Cascadia"];
|
||||
font = parseInt(await utils.suggester(font,["1","2","3"]));
|
||||
if (isNaN(font)) return;
|
||||
elements.forEach((el)=>el.fontFamily = font);
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
ea.addElementsToView();
|
||||
```
|
||||
5804
docs/zh-cn/docs/Release-notes.md
Normal file
57
docs/zh-cn/docs/readme.md
Normal file
@@ -0,0 +1,57 @@
|
||||
# Excalidraw 自动化使用指南
|
||||
|
||||
> 此说明当前更新至 `e793526`。
|
||||
|
||||
【[English](../../readme.md) | 简体中文】
|
||||
|
||||
使用 ExcalidrawAutomate 可以通过 [ExcalidrawAutomate 脚本引擎](ExcalidrawScriptsEngine.md)、[Templater](https://silentvoid13.github.io/Templater/docs/) 或 [QuickAdd](https://github.com/chhoumann/quickadd) 插件来创建或操作 Excalidraw 绘图,并使用 [DataviewJS](https://blacksmithgu.github.io/obsidian-dataview/docs/api/intro/) 生成嵌入式的 SVG 和 PNG 图像。
|
||||
|
||||
通过一些简单的配置,使用 ExcalidrawAutomate 你可以:
|
||||
- 生成简单的思维导图
|
||||
- 构建家谱
|
||||
- 填写 SVG 表单
|
||||
- 创建自定义图表
|
||||
- 在 Excalidraw 中自动化简单任务(即创建宏)
|
||||
|
||||

|
||||
|
||||
## API 文档
|
||||
|
||||
- **从这里开始** [API 介绍](API/introduction.md)
|
||||
- [属性和函数概览](API/attributes_functions_overview.md)
|
||||
- [元素样式](API/element_style.md)
|
||||
- [画布样式](API/canvas_style.md)
|
||||
- [添加对象](API/objects.md)
|
||||
- [实用函数](API/utility.md)
|
||||
|
||||
## ExcalidrawAutomate 脚本引擎
|
||||
|
||||
当你想要自动化一些简单的步骤时,比如在文本元素周围添加一个框、用箭头连接两个对象、或者设置自定义的线宽或网格值等类似"宏"的自动化操作,我建议使用脚本引擎。
|
||||
- [ExcalidrawAutomate 脚本引擎](ExcalidrawScriptsEngine.md)
|
||||
|
||||
## 示例
|
||||
- **Templater**
|
||||
- [在当前编辑的文档中插入新绘图](Examples/insert_new_drawing.md)
|
||||
- [连接对象](Examples/connect_objects.md)
|
||||
- [应用 Excalidraw 模板](Examples/apply_template.md)
|
||||
- [使用 Templater 创建思维导图](Examples/templater_mindmap.md)
|
||||
|
||||
- **Dataview**
|
||||
- [使用 Dataview 创建思维导图](Examples/dataviewjs_mindmap.md)
|
||||
- [使用 Dataview 创建家谱](Examples/dataviewjs_familytree.md)
|
||||
|
||||
## 支持与反馈
|
||||
|
||||
### 支持原作者
|
||||
|
||||
如果你喜欢这个插件,请通过以下方式支持:
|
||||
- 在社交媒体上分享这个插件
|
||||
- 在 Twitter 上关注作者 [@zsviczian](https://twitter.com/zsviczian)
|
||||
- 访问作者的博客 [zsolt.blog](https://zsolt.blog)
|
||||
- [赞助作者](https://ko-fi.com/zsolt)
|
||||
|
||||
[<img src="https://user-images.githubusercontent.com/14358394/115450238-f39e8100-a21b-11eb-89d0-fa4b82cdbce8.png" width="150" alt="赞助按钮">](https://ko-fi.com/zsolt)
|
||||
|
||||
### 支持中文翻译
|
||||
|
||||
如果这些中文翻译对你有帮助,欢迎通过 [爱发电](https://afdian.com/a/daomishu) 支持译者。
|
||||
91
docs/zh-cn/ea-scripts/README.md
Normal file
@@ -0,0 +1,91 @@
|
||||
# Excalidraw 脚本引擎脚本库
|
||||
|
||||
> 此说明当前更新至 `768aebf`。
|
||||
|
||||
【[English](../../../ea-scripts/README.md) | 简体中文】
|
||||
|
||||
点击观看介绍视频:
|
||||
|
||||
[](https://youtu.be/hePJcObHIso)
|
||||
|
||||
> **警告**
|
||||
> 相比视频中展示的方法,现在有更简单的方式来安装/管理脚本
|
||||
|
||||
查看 [Excalidraw 脚本引擎](../../ExcalidrawScriptsEngine.md) 文档了解更多详情。
|
||||
|
||||
## 如何在 Obsidian 仓库中安装脚本
|
||||
|
||||
安装内置脚本的步骤:
|
||||
|
||||
- 在 Obsidian 中打开一个 Excalidraw 绘图
|
||||
- 在面板下拉菜单中选择"安装或更新 Excalidraw 脚本"
|
||||
- 点击其中一个可用脚本
|
||||
- 点击"安装此脚本"(注意如果脚本已经安装,你会看到更新选项)
|
||||
- 重启 Obsidian 使脚本生效
|
||||
|
||||
注意:默认情况下,脚本会被安装到你仓库中的 `Excalidraw/Scripts/Downloaded` 文件夹
|
||||
|
||||
<details><summary>手动安装脚本</summary>
|
||||
|
||||
打开你感兴趣的脚本,将其保存到你的 Obsidian 仓库中(包括第一行的 `/*`),或者在"Raw"模式下打开并将全部内容复制到 Obsidian 中。
|
||||
|
||||

|
||||
|
||||
</details>
|
||||
|
||||
## 可用脚本列表
|
||||
|
||||
|标题|描述|图标|贡献者|
|
||||
|----|----|----|----|
|
||||
|[添加连接点](../../../ea-scripts/Add%20Connector%20Point.md)|此脚本将在选中文本元素的左上角添加一个小圆圈,并将文本和"圆点"组合成一组。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[添加现有文件链接并打开](../../../ea-scripts/Add%20Link%20to%20Existing%20File%20and%20Open.md)|提示从保险库(Vault)中选择文件。为选中的元素添加指向所选文件的链接。你可以在设置中控制是在当前活动面板还是相邻面板中打开文件。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[添加新页面链接并打开](../../../ea-scripts/Add%20Link%20and%20Open%20Page.md)|提示输入文件名。提供创建和打开新的 Markdown 或 Excalidraw 文档的选项。为绘图中选中的对象添加指向新文件的链接。你可以在设置中控制是在当前活动面板或是相邻面板中打开文件。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[添加流程下一步](../../../ea-scripts/Add%20Link%20to%20New%20Page%20and%20Open.md)|此脚本将提示你输入流程步骤的标题,然后创建带有该文本的便签。如果选中了某个元素,脚本将用箭头将这个新步骤与上一步骤(选中的元素)连接起来。如果没有选中元素,脚本会假定这是流程的第一步,只会输出带有输入文本的便签。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[分割椭圆](../../../ea-scripts/Boolean%20Operations.md)|使用此脚本可以对形状进行布尔运算。||[@GColoy](https://github.com/GColoy)|
|
||||
|[为每个选中的组添加边框](../../../ea-scripts/Box%20Each%20Selected%20Groups.md)|此脚本将为 Excalidraw 中当前选中的每个组添加封装框。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[为选中元素添加边框](../../../ea-scripts/Box%20Selected%20Elements.md)|此脚本将为 Excalidraw 中当前选中的元素添加一个封装框。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[更改选中元素的形状](../../../ea-scripts/Change%20shape%20of%20selected%20elements.md)|此脚本允许你更改选中的矩形、菱形和椭圆的形状||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[连接元素](../../../ea-scripts/Connect%20elements.md)|此脚本将用箭头连接两个对象。如果任一对象是一组分组的元素(例如,与封装矩形分组的文本元素),脚本将识别这些组,并将箭头连接到组中最大的对象(假设你想将箭头连接到文本元素周围的框)。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[将自由绘制转换为线条](../../../ea-scripts/Convert%20freedraw%20to%20line.md)|将选中的自由绘制对象转换为可编辑的线条。这样你就可以通过拖动线条点来调整绘图,如果是封闭线条还可以选择形状填充。你可以在设置中调整转换点的密度||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[将选中的文本元素转换为便签](../../../ea-scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.md)|将选中的纯文本元素转换为具有透明背景和透明描边颜色的便签。本质上是将文本元素转换为可换行的格式。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[将文本转换为带文件夹和别名的链接](../../../ea-scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.md)|将文本元素转换为指向所选文件夹中文件的链接,并将原始文本设置为别名。脚本会提示用户从保险库(Vault)中选择一个现有文件夹。|`原始文本` => `[[选定文件夹/原始文本\|原始文本]]`|[@zsviczian](https://github.com/zsviczian)|
|
||||
|[将选中元素样式复制到全局](../../../ea-scripts/Copy%20Selected%20Element%20Styles%20to%20Global)|此脚本会将任何选中元素的样式复制到 Excalidraw 的全局样式中。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[创建新的 Markdown 文件并嵌入到当前绘图中](../../../ea-scripts/Create%20new%20markdown%20file%20and%20embed%20into%20active%20drawing.md)|此脚本会提示你输入文件名,然后创建一个具有该文件名的新 Markdown 文档,在相邻面板中打开新的 Markdown 文档,并将该 Markdown 文档嵌入到当前的 Excalidraw 绘图中。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[加深背景颜色](../../../ea-scripts/Darken%20background%20color.md)|此脚本每次将选中元素的背景颜色加深 2%。你可以多次使用此脚本直到满意为止。建议为此脚本设置快捷键,这样你就可以快速尝试加深和减淡颜色效果。与"修改背景颜色不透明度"脚本相比,其优点是元素的背景颜色不受画布颜色影响,并且颜色值不会以奇怪的 rgba() 形式出现。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[肘形连接器](../../../ea-scripts/Elbow%20connectors.md)|此脚本将选中的连接器转换为肘形。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[水平扩展矩形并保持文本居中](../../../ea-scripts/Expand%20rectangles%20horizontally%20keep%20text20%centered.md)|此脚本会扩展选中矩形的宽度,直到它们都具有相同的宽度,并保持文本居中。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[水平扩展矩形](../../../ea-scripts/Expand%20rectangles%20horizontally.md)|此脚本会扩展选中矩形的宽度,直到它们都具有相同的宽度。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[垂直扩展矩形并保持文本居中](../../../ea-scripts/Expand%20rectangles%20vertically%20keep%20text%20centered.md)|此脚本会扩展选中矩形的高度,直到它们都具有相同的高度,并保持文本居中。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[垂直扩展矩形](../../../ea-scripts/Expand%20rectangles%20vertically.md)|此脚本会扩展选中矩形的高度,直到它们都具有相同的高度。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[固定中心点水平距离](../../../ea-scripts/Fixed%20horizontal%20distance%20between%20centers.md)|此脚本会以固定的中心点间距水平排列选中的元素。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[固定内部距离](../../../ea-scripts/Fixed%20inner%20distance.md)|此脚本会以固定的内部距离排列选中的元素和组。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[固定间距](../../../ea-scripts/Fixed%20spacing.md)|此脚本会以固定的间距水平排列选中的元素。当我们创建架构图或思维导图时,经常需要以固定间距排列大量元素。"固定间距"和"固定垂直距离"脚本可以为我们节省大量时间。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[固定中心点垂直距离](../../../ea-scripts/Fixed%20vertical%20distance%20between%20centers.md)|此脚本会以固定的中心点间距垂直排列选中的元素。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[固定垂直距离](../../../ea-scripts/Fixed%20vertical%20distance.md)|此脚本会以固定间距垂直排列选中的元素。当我们创建架构图或思维导图时,经常需要以固定间距排列大量元素。`固定间距`和`固定垂直距离`脚本可以为我们节省大量时间。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[减淡背景颜色](../../../ea-scripts/Lighten%20background%20color.md)|此脚本每次将选中元素的背景颜色减淡 2%。你可以多次使用此脚本直到满意为止。建议为此脚本设置快捷键,这样你就可以快速尝试加深和减淡颜色效果。与"修改背景颜色不透明度"脚本相比,其优点是元素的背景颜色不受画布颜色影响,并且颜色值不会以奇怪的 rgba() 形式出现。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[思维导图连接器](../../../ea-scripts/Mindmap%20connector.md)|此脚本为选中的元素创建类似思维导图的连线(目前仅支持右侧和向下方向)。连线的起点将根据元素的创建时间确定。因此你应该先创建标题元素。||[@xllowl](https://github.com/xllowl)|
|
||||
|[修改背景颜色不透明度](../../../ea-scripts/Modify%20background%20color%20opacity.md)|此脚本会更改选中框的背景颜色不透明度。Excalidraw 中的默认背景颜色太深,导致文字难以阅读。你可以通过设置透明度来使颜色变浅。你可以反复调整透明度直到满意为止。虽然 Excalidraw 在其原生属性设置中有不透明度选项,但它也会改变边框的透明度。使用此脚本可以只更改背景颜色的不透明度而不影响边框。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[标准化选中箭头](../../../ea-scripts/Normalize%20Selected%20Arrows.md)|此脚本将重置选中箭头的起点和终点位置。箭头将指向连接框的中心,并与框保持 8px 的间距。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[OCR - 光学字符识别](../../../ea-scripts/OCR%20-%20Optical%20Character%20Recognition.md)|此脚本将 1) 把选中的图片文件发送到 [taskbone.com](https://taskbone.com) 提取图片中的文字,并 2) 将文字作为文本元素添加到你的绘图中。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[有机线条](../../../ea-scripts/Organic%20Line.md)|将选中的自由绘制线条转换为从开始到结束笔压逐渐减小的线条。转换后的线条会被放置在图层的最底层,位于所有其他元素之下。在绘制有机思维导图时很有帮助。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[重复元素](../../../ea-scripts/Repeat%20Elements.md)|此脚本会检测两个选中元素之间的差异,包括位置、大小、角度、描边和背景颜色,并根据用户输入的重复次数创建多个具有相同差异的元素。||[@1-2-3](https://github.com/1-2-3)|
|
||||
|[重置 LaTeX 大小](../../../ea-scripts/Reset%20LaTeX%20Size.md)|将嵌入的 LaTeX 公式大小重置为默认大小或默认大小的倍数。||[@firai](https://github.com/firai)|
|
||||
|[反转箭头](../../../ea-scripts/Reverse%20arrows.md)|反转选中元素范围内的**箭头**方向。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[手写助手](../../../ea-scripts/Scribble%20Helper.md)|iOS 手写助手,用于改善文本元素的手写体验。如果没有选中元素,则会在指针位置创建一个文本元素,你可以使用编辑框通过手写来修改文本。如果选中了文本元素,则会打开输入提示框,你可以在其中通过手写修改文本。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[选择特定类型元素](../../../ea-scripts/Select%20Elements%20of%20Type.md)|显示当前图像中不同元素类型的列表供选择。只有选定类型的元素会在画布上被选中。如果运行脚本时没有选中任何元素,则脚本会处理画布上的所有元素。如果执行脚本时已选中某些元素,则脚本只会处理这些选中的元素。<br>此脚本在以下情况下很有用,例如,当你想要将所有箭头置于顶层,或想要更改所有文本元素的颜色等。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[通过添加阴影克隆为未闭合线条对象设置背景颜色](../../../ea-scripts/Set%20background%20color%20of%20unclosed%20line%20object%20by%20adding%20a%20shadow%20clone.md)|使用此脚本为未闭合(即开放)线条对象设置背景颜色,方法是创建对象的克隆。脚本会将克隆的描边颜色设置为透明,并添加一条直线来闭合对象。使用设置来定义默认背景颜色、填充样式和克隆的描边宽度。默认情况下,克隆会与原始对象组合在一起,你也可以在设置中禁用此功能。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[设置尺寸](../../../ea-scripts/Set%20Dimensions.md)|目前在 Excalidraw 中无法指定对象的确切位置和大小。你可以使用这个简单的脚本来弥补这个不足。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[设置字体](../../../ea-scripts/Set%20Font%20Family.md)|设置文本块的字体(Virgil、Helvetica、Cascadia)。如果你想为选择字体设置键盘快捷键,这个脚本很有用。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[设置网格](../../../ea-scripts/Set%20Grid.md)|Excalidraw 中的默认网格大小是 20。目前无法通过用户界面更改网格大小。这个脚本提供了一种方法来弥补这个不足。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[设置链接别名](../../../ea-scripts/Set20%Link20%Alias.md)|遍历选中文本元素中的所有链接,并提示用户为每个找到的链接设置或修改别名。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[设置选中元素的描边宽度](../../../ea-scripts/Set%20Stroke%20Width%20of%20Selected%20Elements.md)|此脚本将设置选中元素的描边宽度。这在缩放自由绘制草图并想要减小或增加其线条宽度时很有用。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[按行分割文本](../../../ea-scripts/Split%20text%20by%20lines.md)|将文本行分割成单独的文本元素,以便更容易重新组织||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[设置文本对齐方式](../../../ea-scripts/Set%20Text%20Alignment.md)|设置文本块的对齐方式(居中、右对齐、左对齐)。如果你想为选择文本对齐方式设置键盘快捷键,这个脚本很有用。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[分割椭圆](../../../ea-scripts/Split%20Ellipse.md)|此脚本会在线条与椭圆相交的任何点处分割椭圆。||[@GColoy](https://github.com/GColoy)|
|
||||
|[TheBrain导航](../../../ea-scripts/TheBrain-navigation.md)|基于Excalidraw的保险库(Vault)图形用户界面。需要[Dataview插件](https://github.com/blacksmithgu/obsidian-dataview)。生成类似于[TheBrain](https://TheBrain.com)的图形视图。在[YouTube](https://youtu.be/plYobK-VufM)上观看此脚本的介绍。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[移动端切换全屏](../../../ea-scripts/Toggle%20Fullscreen%20on%20Mobile.md)|隐藏Obsidian工作区叶片填充和标题(基于设置中的选项,默认"隐藏标题"=false),这将使Excalidraw全屏显示。⚠ 注意,如果标题不可见,将很难调用命令面板来结束全屏。只有在你有键盘或已经练习过打开命令面板的情况下才隐藏标题!||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[切换网格](../../../ea-scripts/Toggle%20Grid.md)|切换网格的显示与隐藏。||[@GColoy](https://github.com/GColoy)|
|
||||
|[将文本元素转移到Excalidraw markdown元数据](../../../ea-scripts/Transfer%20TextElements%20to%20Excalidraw%20markdown%20metadata.md)|此脚本将从画布中删除选中的文本元素,并将这些文本元素中的文本复制到Excalidraw markdown文件的元数据中。这意味着,文本将不再在绘图中可见,但你可以在Obsidian中搜索文本并找到包含此图像的绘图。||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[缩放以适应选中元素](../../../ea-scripts/Zoom%20to%20Fit%20Selected%20Elements.md)|类似于Excalidraw标准的<kbd>SHIFT+2</kbd>功能:缩放以适应选中元素,但可以缩放到1000%。灵感来源:[#272](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/272)||[@zsviczian](https://github.com/zsviczian)|
|
||||
|[硬件橡皮擦支持](../../../ea-scripts/Hardware%20Eraser%20Support.md)|允许在支持的笔上使用笔反转/硬件橡皮擦。|[@threethan](https://github.com/threethan)|
|
||||
|[笔的自动绘制](../../../ea-scripts/Auto%20Draw%20for%20Pen.md)|当悬停笔时自动从选择工具切换到绘制工具,然后再切换回来。|[@threethan](https://github.com/threethan)|
|
||||
@@ -23,8 +23,8 @@ const elements = ea.getViewSelectedElements().filter(
|
||||
el.groupIds.some(id => id.startsWith(ShadowGroupMarker)) ||
|
||||
(["line", "arrow"].includes(el.type) && el.roundness === null)
|
||||
);
|
||||
if(elements.length === 0) {
|
||||
new Notice ("Select ellipses, rectangles or diamonds");
|
||||
if(elements.length < 2) {
|
||||
new Notice ("Select ellipses, rectangles, diamonds; or lines and arrows with sharp edges");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -69,10 +69,15 @@ const result = polyboolAction({
|
||||
const polygonHierachy = subordinateInnerPolygons(result.regions);
|
||||
drawPolygonHierachy(polygonHierachy);
|
||||
ea.deleteViewElements(elements);
|
||||
setPolygonTrue();
|
||||
ea.addElementsToView(false,false,true);
|
||||
return;
|
||||
|
||||
|
||||
function setPolygonTrue() {
|
||||
ea.getElements().filter(el=>el.type==="line").forEach(el => {
|
||||
el.polygon = true;
|
||||
});
|
||||
}
|
||||
|
||||
function traceElement(element) {
|
||||
const diamondPath = (diamond) => [
|
||||
|
||||
660
ea-scripts/Printable Layout Wizard.md
Normal file
@@ -0,0 +1,660 @@
|
||||
/*
|
||||
|
||||
Export Excalidraw to PDF Pages: Define printable page areas using frames, then export each frame as a separate page in a multi-page PDF. Perfect for turning your Excalidraw drawings into printable notes, handouts, or booklets. Supports standard and custom page sizes, margins, and easy frame arrangement.
|
||||
|
||||

|
||||
|
||||

|
||||
|
||||
```js
|
||||
*/
|
||||
|
||||
|
||||
async function run() {
|
||||
// Help text for the script
|
||||
const HELP_TEXT = `
|
||||
**Easily split your Excalidraw drawing into printable pages!**
|
||||
|
||||
If you find this script helpful, consider [buying me a coffee](https://ko-fi.com/zsolt). Thank you.
|
||||
|
||||
---
|
||||
|
||||
### How it works
|
||||
|
||||
- **Define Pages:** Use frames to mark out each page area in your drawing. You can create the first frame with this script (choose a standard size or orientation), or draw your own frame for a custom page size.
|
||||
- **Add More Pages:** Select a frame, then use the arrow buttons to add new frames next to it. All new frames will match the size of the selected one.
|
||||
- **Rename Frames:** You can rename frames as you like. When exporting to PDF, pages will be ordered alphabetically by frame name.
|
||||
|
||||
---
|
||||
|
||||
### Important Notes
|
||||
|
||||
- **Same Size & Orientation:** All frames must have the same size and orientation (e.g., all A4 Portrait) to export to PDF. Excalidraw currently does not support PDFs with different-sized pages.
|
||||
- **Custom Sizes:** If you draw your own frame, the PDF will use that exact size—great for custom page layouts!
|
||||
- **Margins:** If you set a margin, the page size stays the same, but your content will shrink to fit inside the printable area.
|
||||
- **No Frame Borders/Titles in Print:** Frame borders and frame titles will *not* appear in the PDF.
|
||||
- **No Frame Clipping:** The script disables frame clipping for this drawing.
|
||||
- **Templates:** You can save a template document with prearranged frames (even locked ones) for reuse.
|
||||
- **Lock Frames:** Frames only define print areas—they don't "contain" elements. Locking frames is recommended to prevent accidental movement.
|
||||
- **Outside Content:** Anything outside the frames will *not* appear in the PDF.
|
||||
|
||||
---
|
||||
|
||||
### Printing
|
||||
|
||||
- **Export to PDF:** Click the printer button to export each frame as a separate page in a PDF.
|
||||
- **Order:** Pages are exported in alphabetical order of frame names.
|
||||
|
||||
---
|
||||
|
||||
### Settings
|
||||
|
||||
You can also access script settings at the bottom of Excalidraw Plugin settings. The script stores your preferences for:
|
||||
- Locking new frames after creation
|
||||
- Zooming to new frames
|
||||
- Closing the dialog after adding a frame
|
||||
- Default page size and orientation
|
||||
- Print margin
|
||||
|
||||
---
|
||||
|
||||
**Tip:** For more on templates, see [Mastering Excalidraw Templates](https://youtu.be/jgUpYznHP9A). For referencing pages in markdown, see [Image Fragments](https://youtu.be/sjZfdqpxqsg) and [Image Block References](https://youtu.be/yZQoJg2RCKI).
|
||||
`;
|
||||
|
||||
// Enable frame rendering
|
||||
const st = ea.getExcalidrawAPI().getAppState();
|
||||
const {enabled, clip, name, outline} = st.frameRendering;
|
||||
if(!enabled || clip || !name || !outline) {
|
||||
ea.viewUpdateScene({
|
||||
appState: {
|
||||
frameRendering: {
|
||||
enabled: true,
|
||||
clip: false,
|
||||
name: true,
|
||||
outline: true
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Page size options (using standard sizes from ExcalidrawAutomate)
|
||||
const PAGE_SIZES = [
|
||||
"A0", "A1", "A2", "A3", "A4", "A5", "A6",
|
||||
"Letter", "Legal", "Tabloid", "Ledger"
|
||||
];
|
||||
|
||||
const PAGE_ORIENTATIONS = ["portrait", "landscape"];
|
||||
|
||||
// Margin sizes in points
|
||||
const MARGINS = {
|
||||
"none": 0,
|
||||
"tiny": 10,
|
||||
"normal": 60,
|
||||
};
|
||||
|
||||
// Initialize settings
|
||||
let settings = ea.getScriptSettings();
|
||||
let dirty = false;
|
||||
|
||||
// Define setting keys
|
||||
const PAGE_SIZE = "Page size";
|
||||
const ORIENTATION = "Page orientation";
|
||||
const MARGIN = "Print-margin";
|
||||
const LOCK_FRAME = "Lock frame after it is created";
|
||||
const SHOULD_ZOOM = "Should zoom after adding page";
|
||||
const SHOULD_CLOSE = "Should close after adding page";
|
||||
|
||||
// Set default values on first run
|
||||
if (!settings[PAGE_SIZE]) {
|
||||
settings = {};
|
||||
settings[PAGE_SIZE] = { value: "A4", valueSet: PAGE_SIZES };
|
||||
settings[ORIENTATION] = { value: "portrait", valueSet: PAGE_ORIENTATIONS };
|
||||
settings[MARGIN] = { value: "none", valueSet: Object.keys(MARGINS)};
|
||||
settings[SHOULD_ZOOM] = { value: false };
|
||||
settings[SHOULD_CLOSE] = { value: false };
|
||||
settings[LOCK_FRAME] = { value: true };
|
||||
await ea.setScriptSettings(settings);
|
||||
}
|
||||
|
||||
const getSortedFrames = () => ea.getViewElements()
|
||||
.filter(el => el.type === "frame")
|
||||
.sort((a, b) => {
|
||||
const nameA = a.name || "";
|
||||
const nameB = b.name || "";
|
||||
return nameA.localeCompare(nameB);
|
||||
});
|
||||
|
||||
// Find existing page frames and determine next page number
|
||||
const findExistingPages = (selectLastFrame = false) => {
|
||||
const frameElements = getSortedFrames();
|
||||
|
||||
// Extract page numbers from frame names
|
||||
const pageNumbers = frameElements
|
||||
.map(frame => {
|
||||
const match = frame.name?.match(/Page\s+(\d+)/i);
|
||||
return match ? parseInt(match[1]) : 0;
|
||||
})
|
||||
.filter(num => !isNaN(num));
|
||||
|
||||
// Find the highest page number
|
||||
const nextPageNumber = pageNumbers.length > 0
|
||||
? Math.max(...pageNumbers) + 1
|
||||
: 1;
|
||||
|
||||
if(selectLastFrame && frameElements.length > 0) {
|
||||
ea.selectElementsInView([frameElements[frameElements.length-1]]);
|
||||
}
|
||||
|
||||
return {
|
||||
frames: frameElements,
|
||||
nextPageNumber: nextPageNumber
|
||||
};
|
||||
};
|
||||
|
||||
// Check if there are frames in the scene and if a frame is selected
|
||||
let existingFrames = ea.getViewElements().filter(el => el.type === "frame");
|
||||
let selectedFrame = ea.getViewSelectedElements().find(el => el.type === "frame");
|
||||
const hasFrames = existingFrames.length > 0;
|
||||
if(hasFrames && !selectedFrame) {
|
||||
if(st.activeLockedId && existingFrames.find(f=>f.id === st.activeLockedId)) {
|
||||
selectedFrame = existingFrames.find(f=>f.id === st.activeLockedId);
|
||||
ea.viewUpdateScene({ appState: { activeLockedId: null }});
|
||||
ea.selectElementsInView([selectedFrame]);
|
||||
} else {
|
||||
findExistingPages(true);
|
||||
selectedFrame = ea.getViewSelectedElements().find(el => el.type === "frame");
|
||||
}
|
||||
}
|
||||
const hasSelectedFrame = !!selectedFrame;
|
||||
const modal = new ea.FloatingModal(ea.plugin.app);
|
||||
let lockFrame = !!settings[LOCK_FRAME]?.value;
|
||||
let shouldClose = settings[SHOULD_CLOSE].value;
|
||||
let shouldZoom = settings[SHOULD_ZOOM].value;
|
||||
|
||||
// Show notice if there are frames but none selected
|
||||
if (hasFrames && !hasSelectedFrame) {
|
||||
new Notice("Select a frame before running the script", 7000);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create the first frame
|
||||
const createFirstFrame = async (pageSize, orientation) => {
|
||||
// Use ExcalidrawAutomate's built-in function to get page dimensions
|
||||
const dimensions = ea.getPagePDFDimensions(pageSize, orientation);
|
||||
|
||||
if (!dimensions) {
|
||||
new Notice("Invalid page size selected");
|
||||
return;
|
||||
}
|
||||
|
||||
// Save settings when creating first frame
|
||||
if (settings[PAGE_SIZE].value !== pageSize) {
|
||||
settings[PAGE_SIZE].value = pageSize;
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
if (settings[ORIENTATION].value !== orientation) {
|
||||
settings[ORIENTATION].value = orientation;
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
// Format page number with leading zero
|
||||
const pageName = "Page 01";
|
||||
|
||||
// Calculate position to center the frame
|
||||
const appState = ea.getExcalidrawAPI().getAppState();
|
||||
const x = (appState.width - dimensions.width) / 2;
|
||||
const y = (appState.height - dimensions.height) / 2;
|
||||
|
||||
return await addFrameElement(x, y, dimensions.width, dimensions.height, pageName, true);
|
||||
};
|
||||
|
||||
// Add new page frame
|
||||
const addPage = async (direction, pageSize, orientation) => {
|
||||
selectedFrame = ea.getViewSelectedElements().find(el => el.type === "frame");
|
||||
if (!selectedFrame) return;
|
||||
|
||||
const { frames, nextPageNumber } = findExistingPages();
|
||||
|
||||
// Get dimensions from selected frame
|
||||
const dimensions = {
|
||||
width: selectedFrame.width,
|
||||
height: selectedFrame.height
|
||||
};
|
||||
|
||||
// Format page number with leading zero
|
||||
const pageName = `Page ${nextPageNumber.toString().padStart(2, '0')}`;
|
||||
|
||||
// Calculate position based on direction and selected frame
|
||||
let x = 0;
|
||||
let y = 0;
|
||||
|
||||
switch (direction) {
|
||||
case "right":
|
||||
x = selectedFrame.x + selectedFrame.width;
|
||||
y = selectedFrame.y;
|
||||
break;
|
||||
case "left":
|
||||
x = selectedFrame.x - dimensions.width;
|
||||
y = selectedFrame.y;
|
||||
break;
|
||||
case "down":
|
||||
x = selectedFrame.x;
|
||||
y = selectedFrame.y + selectedFrame.height;
|
||||
break;
|
||||
case "up":
|
||||
x = selectedFrame.x;
|
||||
y = selectedFrame.y - dimensions.height;
|
||||
break;
|
||||
}
|
||||
|
||||
return await addFrameElement(x, y, dimensions.width, dimensions.height, pageName);
|
||||
};
|
||||
|
||||
addFrameElement = async (x, y, width, height, pageName, repositionToCursor = false) => {
|
||||
const frameId = ea.addFrame(x, y, width, height, pageName);
|
||||
if(lockFrame) {
|
||||
ea.getElement(frameId).locked = true;
|
||||
}
|
||||
await ea.addElementsToView(repositionToCursor);
|
||||
const addedFrame = ea.getViewElements().find(el => el.id === frameId);
|
||||
if(shouldZoom) {
|
||||
ea.viewZoomToElements(true, [addedFrame]);
|
||||
} else {
|
||||
ea.selectElementsInView([addedFrame]);
|
||||
}
|
||||
|
||||
//ready for the next frame
|
||||
ea.clear();
|
||||
selectedFrame = addedFrame;
|
||||
if(shouldClose) {
|
||||
modal.close();
|
||||
}
|
||||
return addedFrame;
|
||||
}
|
||||
|
||||
const translateToZero = ({ top, left, bottom, right }, padding=0) => {
|
||||
const {topX, topY, width, height} = ea.getBoundingBox(ea.getViewElements());
|
||||
const newTop = top - (topY - padding);
|
||||
const newLeft = left - (topX - padding);
|
||||
const newBottom = bottom - (topY - padding);
|
||||
const newRight = right - (topX - padding);
|
||||
|
||||
return {
|
||||
top: newTop,
|
||||
left: newLeft,
|
||||
bottom: newBottom,
|
||||
right: newRight,
|
||||
};
|
||||
}
|
||||
|
||||
// Check if all frames have the same size
|
||||
const checkFrameSizes = (frames) => {
|
||||
if (frames.length <= 1) return true;
|
||||
|
||||
const referenceWidth = frames[0].width;
|
||||
const referenceHeight = frames[0].height;
|
||||
|
||||
return frames.every(frame =>
|
||||
Math.abs(frame.width - referenceWidth) < 1 &&
|
||||
Math.abs(frame.height - referenceHeight) < 1
|
||||
);
|
||||
};
|
||||
|
||||
// Print frames to PDF
|
||||
const printToPDF = async (marginSize) => {
|
||||
const margin = MARGINS[marginSize] || 0;
|
||||
|
||||
// Save margin setting
|
||||
if (settings[MARGIN].value !== marginSize) {
|
||||
settings[MARGIN].value = marginSize;
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
// Get all frame elements and sort by name
|
||||
const frames = getSortedFrames();
|
||||
|
||||
if (frames.length === 0) {
|
||||
new Notice("No frames found to print");
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if all frames have the same size
|
||||
if (!checkFrameSizes(frames)) {
|
||||
new Notice("Only same sized pages are supported currently", 7000);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create a notice during processing
|
||||
const notice = new Notice("Preparing PDF, please wait...", 0);
|
||||
|
||||
// Create SVGs for each frame
|
||||
const svgPages = [];
|
||||
|
||||
const svgScene = await ea.createViewSVG({
|
||||
withBackground: true,
|
||||
theme: st.theme,
|
||||
frameRendering: { enabled: false, name: false, outline: false, clip: false },
|
||||
padding: 0,
|
||||
selectedOnly: false,
|
||||
skipInliningFonts: false,
|
||||
embedScene: false,
|
||||
});
|
||||
|
||||
for (const frame of frames) {
|
||||
const { top, left, bottom, right } = translateToZero({
|
||||
top: frame.y,
|
||||
left: frame.x,
|
||||
bottom: frame.y + frame.height,
|
||||
right: frame.x + frame.width,
|
||||
});
|
||||
|
||||
//always create the new SVG in the main Obsidian workspace (not the popout window, if present)
|
||||
const host = window.createDiv();
|
||||
host.innerHTML = svgScene.outerHTML;
|
||||
const clonedSVG = host.firstElementChild;
|
||||
const width = Math.abs(left-right);
|
||||
const height = Math.abs(top-bottom);
|
||||
clonedSVG.setAttribute("viewBox", `${left} ${top} ${width} ${height}`);
|
||||
clonedSVG.setAttribute("width", `${width}`);
|
||||
clonedSVG.setAttribute("height", `${height}`);
|
||||
svgPages.push(clonedSVG);
|
||||
}
|
||||
|
||||
// Use dimensions from the first frame
|
||||
const width = frames[0].width;
|
||||
const height = frames[0].height;
|
||||
|
||||
// Create PDF
|
||||
await ea.createPDF({
|
||||
SVG: svgPages,
|
||||
scale: { fitToPage: true },
|
||||
pageProps: {
|
||||
dimensions: { width, height },
|
||||
backgroundColor: "#ffffff",
|
||||
margin: {
|
||||
left: margin,
|
||||
right: margin,
|
||||
top: margin,
|
||||
bottom: margin
|
||||
},
|
||||
alignment: "center"
|
||||
},
|
||||
filename: ea.targetView.file.basename + "-pages.pdf"
|
||||
});
|
||||
notice.hide();
|
||||
};
|
||||
|
||||
// -----------------------
|
||||
// Create a floating modal
|
||||
// -----------------------
|
||||
|
||||
modal.titleEl.setText("Page Management");
|
||||
modal.titleEl.style.textAlign = "center";
|
||||
|
||||
// Handle save settings on modal close
|
||||
modal.onClose = () => {
|
||||
if (dirty) {
|
||||
ea.setScriptSettings(settings);
|
||||
}
|
||||
};
|
||||
|
||||
// Create modal content
|
||||
modal.contentEl.createDiv({ cls: "excalidraw-page-manager" }, div => {
|
||||
const container = div.createDiv({
|
||||
attr: {
|
||||
style: "display: flex; flex-direction: column; gap: 15px; padding: 10px;"
|
||||
}
|
||||
});
|
||||
|
||||
// Add help section at the top
|
||||
const helpDiv = container.createDiv({
|
||||
attr: {
|
||||
style: "margin-bottom: 10px;"
|
||||
}
|
||||
});
|
||||
|
||||
helpDiv.createEl("details", {}, (details) => {
|
||||
details.createEl("summary", {
|
||||
text: "Help & Information",
|
||||
attr: {
|
||||
style: "cursor: pointer; font-weight: bold; margin-bottom: 10px;"
|
||||
}
|
||||
});
|
||||
|
||||
details.createEl("div", {
|
||||
attr: {
|
||||
style: "padding: 10px; border: 1px solid var(--background-modifier-border); border-radius: 4px; margin-top: 8px; font-size: 0.9em; max-height: 300px; overflow-y: auto;"
|
||||
}
|
||||
}, div => {
|
||||
ea.obsidian.MarkdownRenderer.render(ea.plugin.app, HELP_TEXT, div, "", ea.plugin)
|
||||
});
|
||||
});
|
||||
|
||||
let pageSizeDropdown, orientationDropdown, marginDropdown;
|
||||
|
||||
// Settings section - only show for first frame creation
|
||||
if (!hasFrames) {
|
||||
const settingsContainer = container.createDiv({
|
||||
attr: {
|
||||
style: "display: grid; grid-template-columns: auto 1fr; gap: 10px; align-items: center;"
|
||||
}
|
||||
});
|
||||
|
||||
// Page size dropdown
|
||||
settingsContainer.createEl("label", { text: "Page Size:" });
|
||||
pageSizeDropdown = settingsContainer.createEl("select", {
|
||||
cls: "dropdown",
|
||||
attr: { style: "width: 100%;" }
|
||||
});
|
||||
|
||||
PAGE_SIZES.forEach(size => {
|
||||
pageSizeDropdown.createEl("option", { text: size, value: size });
|
||||
});
|
||||
pageSizeDropdown.value = settings[PAGE_SIZE].value;
|
||||
|
||||
// Orientation dropdown
|
||||
settingsContainer.createEl("label", { text: "Orientation:" });
|
||||
orientationDropdown = settingsContainer.createEl("select", {
|
||||
cls: "dropdown",
|
||||
attr: { style: "width: 100%;" }
|
||||
});
|
||||
|
||||
PAGE_ORIENTATIONS.forEach(orientation => {
|
||||
orientationDropdown.createEl("option", { text: orientation, value: orientation });
|
||||
});
|
||||
orientationDropdown.value = settings[ORIENTATION].value;
|
||||
}
|
||||
|
||||
// Show margin settings only if frames exist
|
||||
if (hasFrames) {
|
||||
const marginContainer = container.createDiv({
|
||||
attr: {
|
||||
style: "display: grid; grid-template-columns: auto 1fr; gap: 10px; align-items: center;"
|
||||
}
|
||||
});
|
||||
|
||||
// Margin dropdown (for printing)
|
||||
marginContainer.createEl("label", { text: "Print Margin:" });
|
||||
marginDropdown = marginContainer.createEl("select", {
|
||||
cls: "dropdown",
|
||||
attr: { style: "width: 100%;" }
|
||||
});
|
||||
|
||||
Object.keys(MARGINS).forEach(margin => {
|
||||
marginDropdown.createEl("option", { text: margin, value: margin });
|
||||
});
|
||||
marginDropdown.value = settings[MARGIN].value;
|
||||
}
|
||||
|
||||
// Add checkboxes for zoom and modal behavior only when frames exist
|
||||
const optionsContainer = container.createDiv({
|
||||
attr: {
|
||||
style: "margin-top: 10px;"
|
||||
}
|
||||
});
|
||||
|
||||
new ea.obsidian.Setting(optionsContainer)
|
||||
.setName("Lock")
|
||||
.setDesc("Lock the new frame element after it is created.")
|
||||
.addToggle(toggle => {
|
||||
toggle.setValue(lockFrame)
|
||||
.onChange(value => {
|
||||
lockFrame = value;
|
||||
if (settings[LOCK_FRAME].value !== value) {
|
||||
settings[LOCK_FRAME].value = value;
|
||||
dirty = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Zoom to added frame checkbox
|
||||
new ea.obsidian.Setting(optionsContainer)
|
||||
.setName("Zoom to new frame")
|
||||
.setDesc("Automatically zoom to the newly created frame")
|
||||
.addToggle(toggle => {
|
||||
toggle.setValue(shouldZoom)
|
||||
.onChange(value => {
|
||||
shouldZoom = value;
|
||||
if (settings[SHOULD_ZOOM].value !== value) {
|
||||
settings[SHOULD_ZOOM].value = value;
|
||||
dirty = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Close after adding checkbox
|
||||
new ea.obsidian.Setting(optionsContainer)
|
||||
.setName("Close after adding")
|
||||
.setDesc("Close this dialog after adding a new frame")
|
||||
.addToggle(toggle => {
|
||||
toggle.setValue(shouldClose)
|
||||
.onChange(value => {
|
||||
shouldClose = value;
|
||||
if (settings[SHOULD_CLOSE].value !== value) {
|
||||
settings[SHOULD_CLOSE].value = value;
|
||||
dirty = true;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Buttons section
|
||||
const buttonContainer = container.createDiv({
|
||||
attr: {
|
||||
style: "display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-top: 10px;"
|
||||
}
|
||||
});
|
||||
|
||||
if (!hasFrames) {
|
||||
// First frame creation button (centered)
|
||||
const createFirstBtn = buttonContainer.createEl("button", {
|
||||
cls: "page-btn",
|
||||
attr: {
|
||||
style: "grid-column: 1 / span 3; height: 40px; background-color: var(--interactive-accent); color: var(--text-on-accent);"
|
||||
}
|
||||
});
|
||||
createFirstBtn.textContent = "Create First Frame";
|
||||
createFirstBtn.addEventListener("click", async () => {
|
||||
const tmpShouldClose = shouldClose;
|
||||
shouldClose = true;
|
||||
await createFirstFrame(pageSizeDropdown.value, orientationDropdown.value);
|
||||
shouldClose = tmpShouldClose;
|
||||
if(!shouldClose) run();
|
||||
});
|
||||
} else if (hasSelectedFrame) {
|
||||
// Only show navigation buttons and print when a frame is selected
|
||||
|
||||
// Up button (in middle of top row)
|
||||
const upBtn = buttonContainer.createEl("button", {
|
||||
cls: "page-btn",
|
||||
attr: {
|
||||
style: "grid-column: 2; grid-row: 1; height: 40px;"
|
||||
}
|
||||
});
|
||||
upBtn.innerHTML = ea.obsidian.getIcon("arrow-big-up").outerHTML;
|
||||
upBtn.addEventListener("click", async () => {
|
||||
await addPage("up");
|
||||
});
|
||||
|
||||
// Add empty space
|
||||
buttonContainer.createDiv({
|
||||
attr: { style: "grid-column: 3; grid-row: 1;" }
|
||||
});
|
||||
|
||||
// Left button
|
||||
const leftBtn = buttonContainer.createEl("button", {
|
||||
cls: "page-btn",
|
||||
attr: { style: "grid-column: 1; grid-row: 2; height: 40px;" }
|
||||
});
|
||||
leftBtn.innerHTML = ea.obsidian.getIcon("arrow-big-left").outerHTML;
|
||||
leftBtn.addEventListener("click", async () => {
|
||||
await addPage("left");
|
||||
});
|
||||
|
||||
// Print button (center)
|
||||
const printBtn = buttonContainer.createEl("button", {
|
||||
cls: "page-btn",
|
||||
attr: {
|
||||
style: "grid-column: 2; grid-row: 2; height: 40px; background-color: var(--interactive-accent);"
|
||||
}
|
||||
});
|
||||
printBtn.innerHTML = ea.obsidian.getIcon("printer").outerHTML;
|
||||
printBtn.addEventListener("click", async () => {
|
||||
await printToPDF(marginDropdown.value);
|
||||
});
|
||||
|
||||
// Right button
|
||||
const rightBtn = buttonContainer.createEl("button", {
|
||||
cls: "page-btn",
|
||||
attr: { style: "grid-column: 3; grid-row: 2; height: 40px;" }
|
||||
});
|
||||
rightBtn.innerHTML = ea.obsidian.getIcon("arrow-big-right").outerHTML;
|
||||
rightBtn.addEventListener("click", async () => {
|
||||
await addPage("right");
|
||||
});
|
||||
|
||||
// Down button (in middle of bottom row)
|
||||
const downBtn = buttonContainer.createEl("button", {
|
||||
cls: "page-btn",
|
||||
attr: { style: "grid-column: 2; grid-row: 3; height: 40px;" }
|
||||
});
|
||||
downBtn.innerHTML = ea.obsidian.getIcon("arrow-big-down").outerHTML;
|
||||
downBtn.addEventListener("click", async () => {
|
||||
await addPage("down");
|
||||
});
|
||||
|
||||
// Add empty space
|
||||
buttonContainer.createDiv({
|
||||
attr: { style: "grid-column: 1; grid-row: 3;" }
|
||||
});
|
||||
}
|
||||
|
||||
// Add CSS
|
||||
div.createEl("style", {
|
||||
text: `
|
||||
.page-btn {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.page-btn:hover {
|
||||
background-color: var(--interactive-hover);
|
||||
}
|
||||
.dropdown {
|
||||
height: 30px;
|
||||
background-color: var(--background-secondary);
|
||||
color: var(--text-normal);
|
||||
border-radius: 4px;
|
||||
border: 1px solid var(--background-modifier-border);
|
||||
padding: 0 10px;
|
||||
}
|
||||
`
|
||||
});
|
||||
});
|
||||
|
||||
modal.open();
|
||||
}
|
||||
|
||||
run();
|
||||
1
ea-scripts/Printable Layout Wizard.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg class="skip" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"/><path d="M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6"/><rect x="6" y="14" width="12" height="8" rx="1"/></svg>
|
||||
|
After Width: | Height: | Size: 386 B |
@@ -1,4 +1,7 @@
|
||||
# Excalidraw Script Engine scripts library
|
||||
|
||||
【English | [简体中文](../docs/zh-cn/ea-scripts/README.md)】
|
||||
|
||||
Click to watch the intro video:
|
||||
|
||||
[](https://youtu.be/hePJcObHIso)
|
||||
|
||||
@@ -7,21 +7,27 @@ Scribble Helper can improve handwriting and add links. It lets you create and ed
|
||||
|
||||
```javascript
|
||||
*/
|
||||
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("1.8.25")) {
|
||||
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.11.0")) {
|
||||
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
|
||||
return;
|
||||
}
|
||||
|
||||
// ------------------------------
|
||||
// Constants and initialization
|
||||
// ------------------------------
|
||||
const helpLINK = "https://youtu.be/BvYkOaly-QM";
|
||||
const DBLCLICKTIMEOUT = 300;
|
||||
const maxWidth = 600;
|
||||
const padding = 6;
|
||||
const api = ea.getExcalidrawAPI();
|
||||
const win = ea.targetView.ownerWindow;
|
||||
|
||||
// Initialize global variables
|
||||
if(!win.ExcalidrawScribbleHelper) win.ExcalidrawScribbleHelper = {};
|
||||
if(typeof win.ExcalidrawScribbleHelper.penOnly === "undefined") {
|
||||
win.ExcalidrawScribbleHelper.penOnly = false;
|
||||
}
|
||||
|
||||
let windowOpen = false; //to prevent the modal window to open again while writing with scribble
|
||||
let prevZoomValue = api.getAppState().zoom.value; //used to avoid trigger on pinch zoom
|
||||
|
||||
@@ -49,8 +55,10 @@ if(typeof win.ExcalidrawScribbleHelper.action === "undefined") {
|
||||
}
|
||||
|
||||
//---------------------------------------
|
||||
// Color Palette for stroke color setting
|
||||
// Helper Functions
|
||||
//---------------------------------------
|
||||
|
||||
// Color Palette for stroke color setting
|
||||
// https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.6.8
|
||||
const defaultStrokeColors = [
|
||||
"#000000", "#343a40", "#495057", "#c92a2a", "#a61e4d",
|
||||
@@ -58,7 +66,7 @@ const defaultStrokeColors = [
|
||||
"#087f5b", "#2b8a3e", "#5c940d", "#e67700", "#d9480f"
|
||||
];
|
||||
|
||||
const loadColorPalette = () => {
|
||||
function loadColorPalette() {
|
||||
const st = api.getAppState();
|
||||
const strokeColors = new Set();
|
||||
let strokeColorPalette = st.colorPalette?.elementStroke ?? defaultStrokeColors;
|
||||
@@ -79,18 +87,8 @@ const loadColorPalette = () => {
|
||||
return strokeColors;
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
// Define variables to cache element location on first click
|
||||
//----------------------------------------------------------
|
||||
// if a single element is selected when the action is started, update that existing text
|
||||
let containerElements = ea.getViewSelectedElements()
|
||||
.filter(el=>["arrow","rectangle","ellipse","line","diamond"].contains(el.type));
|
||||
let selectedTextElements = ea.getViewSelectedElements().filter(el=>el.type==="text");
|
||||
|
||||
//-------------------------------------------
|
||||
// Functions to add and remove event listners
|
||||
//-------------------------------------------
|
||||
const addEventHandler = (handler) => {
|
||||
// Event handler management
|
||||
function addEventHandler(handler) {
|
||||
if(win.ExcalidrawScribbleHelper.eventHandler) {
|
||||
win.removeEventListner("pointerdown", handler);
|
||||
}
|
||||
@@ -99,40 +97,53 @@ const addEventHandler = (handler) => {
|
||||
win.ExcalidrawScribbleHelper.window = win;
|
||||
}
|
||||
|
||||
const removeEventHandler = (handler) => {
|
||||
function removeEventHandler(handler) {
|
||||
win.removeEventListener("pointerdown",handler);
|
||||
delete win.ExcalidrawScribbleHelper.eventHandler;
|
||||
delete win.ExcalidrawScribbleHelper.window;
|
||||
}
|
||||
|
||||
//Stop the script if scribble helper is clicked and no eligable element is selected
|
||||
let silent = false;
|
||||
if (win.ExcalidrawScribbleHelper?.eventHandler) {
|
||||
removeEventHandler(win.ExcalidrawScribbleHelper.eventHandler);
|
||||
delete win.ExcalidrawScribbleHelper.eventHandler;
|
||||
delete win.ExcalidrawScribbleHelper.window;
|
||||
if(!(containerElements.length === 1 || selectedTextElements.length === 1)) {
|
||||
new Notice ("Scribble Helper was stopped",1000);
|
||||
return;
|
||||
// Edit existing text element function
|
||||
async function editExistingTextElement(elements) {
|
||||
windowOpen = true;
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
const el = ea.getElements()[0];
|
||||
ea.style.strokeColor = el.strokeColor;
|
||||
const text = await utils.inputPrompt({
|
||||
header: "Edit text",
|
||||
placeholder: "",
|
||||
value: elements[0].rawText,
|
||||
//buttons: undefined,
|
||||
lines: 5,
|
||||
displayEditorButtons: true,
|
||||
customComponents: customControls,
|
||||
blockPointerInputOutsideModal: true,
|
||||
controlsOnTop: true
|
||||
});
|
||||
|
||||
windowOpen = false;
|
||||
if(!text) return;
|
||||
|
||||
el.strokeColor = ea.style.strokeColor;
|
||||
el.originalText = text;
|
||||
el.text = text;
|
||||
el.rawText = text;
|
||||
if(el.autoResize) {
|
||||
ea.refreshTextElementSize(el.id);
|
||||
}
|
||||
await ea.addElementsToView(false,false);
|
||||
if(el.containerId) {
|
||||
const containers = ea.getViewElements().filter(e=>e.id === el.containerId);
|
||||
api.updateContainerSize(containers);
|
||||
ea.selectElementsInView(containers);
|
||||
}
|
||||
silent = true;
|
||||
}
|
||||
|
||||
// ----------------------
|
||||
// Custom dialog controls
|
||||
// ----------------------
|
||||
if (typeof win.ExcalidrawScribbleHelper.penOnly === "undefined") {
|
||||
win.ExcalidrawScribbleHelper.penOnly = undefined;
|
||||
}
|
||||
if (typeof win.ExcalidrawScribbleHelper.penDetected === "undefined") {
|
||||
win.ExcalidrawScribbleHelper.penDetected = false;
|
||||
}
|
||||
let timer = Date.now();
|
||||
let eventHandler = () => {};
|
||||
|
||||
const customControls = (container) => {
|
||||
// Custom dialog UI components
|
||||
function customControls (container) {
|
||||
const helpDIV = container.createDiv();
|
||||
helpDIV.innerHTML = `<a href="${helpLINK}" target="_blank">Click here for help</a>`;
|
||||
helpDIV.style.paddingBottom = "0.25em";
|
||||
const viewBackground = api.getAppState().viewBackgroundColor;
|
||||
const el1 = new ea.obsidian.Setting(container)
|
||||
.setName(`Text color`)
|
||||
@@ -152,9 +163,10 @@ const customControls = (container) => {
|
||||
el1.nameEl.style.color = ea.style.strokeColor;
|
||||
el1.nameEl.style.background = viewBackground;
|
||||
el1.nameEl.style.fontWeight = "bold";
|
||||
|
||||
el1.settingEl.style.padding = "0.25em 0";
|
||||
|
||||
const el2 = new ea.obsidian.Setting(container)
|
||||
.setName(`Trigger editor by pen double tap only`)
|
||||
.setDesc(`Trigger editor by pen double tap only`)
|
||||
.addToggle((toggle) => toggle
|
||||
.setValue(win.ExcalidrawScribbleHelper.penOnly)
|
||||
.onChange(value => {
|
||||
@@ -162,13 +174,23 @@ const customControls = (container) => {
|
||||
})
|
||||
)
|
||||
el2.settingEl.style.border = "none";
|
||||
el2.settingEl.style.padding = "0.25em 0";
|
||||
el2.settingEl.style.display = win.ExcalidrawScribbleHelper.penDetected ? "" : "none";
|
||||
}
|
||||
|
||||
//----------------------------------------------------------
|
||||
// Cache element location on first click
|
||||
//----------------------------------------------------------
|
||||
// if a single element is selected when the action is started, update that existing text
|
||||
let containerElements = ea.getViewSelectedElements()
|
||||
.filter(el=>["arrow","rectangle","ellipse","line","diamond"].contains(el.type));
|
||||
let selectedTextElements = ea.getViewSelectedElements().filter(el=>el.type==="text");
|
||||
|
||||
// -------------------------------
|
||||
// Click / dbl click event handler
|
||||
// Main Click / dbl click event handler
|
||||
// -------------------------------
|
||||
eventHandler = async (evt) => {
|
||||
let timer = Date.now();
|
||||
async function eventHandler(evt) {
|
||||
if(windowOpen) return;
|
||||
if(ea.targetView !== app.workspace.activeLeaf.view) removeEventHandler(eventHandler);
|
||||
if(evt && evt.target && !evt.target.hasClass("excalidraw__canvas")) return;
|
||||
@@ -252,7 +274,7 @@ eventHandler = async (evt) => {
|
||||
},
|
||||
{
|
||||
caption: "☱",
|
||||
tooltip: "Add as Wrapped Text (rectangle with transparent border and background)",
|
||||
tooltip: "Add as Wrapped Text",
|
||||
action: () => {
|
||||
win.ExcalidrawScribbleHelper.action="Wrap";
|
||||
if(settings["Default action"].value!=="Wrap") {
|
||||
@@ -266,6 +288,7 @@ eventHandler = async (evt) => {
|
||||
if(win.ExcalidrawScribbleHelper.action !== "Text") actionButtons.push(actionButtons.shift());
|
||||
if(win.ExcalidrawScribbleHelper.action === "Wrap") actionButtons.push(actionButtons.shift());
|
||||
|
||||
// Apply styles from current app state
|
||||
ea.style.strokeColor = st.currentItemStrokeColor ?? ea.style.strokeColor;
|
||||
ea.style.roughness = st.currentItemRoughness ?? ea.style.roughness;
|
||||
ea.setStrokeSharpness(st.currentItemRoundness === "round" ? 0 : st.currentItemRoundness)
|
||||
@@ -281,9 +304,18 @@ eventHandler = async (evt) => {
|
||||
ea.style.verticalAlign = "middle";
|
||||
|
||||
windowOpen = true;
|
||||
const text = await utils.inputPrompt (
|
||||
"Edit text", "", "", containerID?undefined:actionButtons, 5, true, customControls, true
|
||||
);
|
||||
|
||||
const text = await utils.inputPrompt ({
|
||||
header: "Edit text",
|
||||
placeholder: "",
|
||||
value: "",
|
||||
buttons: containerID?undefined:actionButtons,
|
||||
lines: 5,
|
||||
displayEditorButtons: true,
|
||||
customComponents: customControls,
|
||||
blockPointerInputOutsideModal: true,
|
||||
controlsOnTop: true
|
||||
});
|
||||
windowOpen = false;
|
||||
|
||||
if(!text || text.trim() === "") return;
|
||||
@@ -297,8 +329,11 @@ eventHandler = async (evt) => {
|
||||
const textEl = ea.getElement(textId);
|
||||
|
||||
if(!container && (win.ExcalidrawScribbleHelper.action === "Wrap")) {
|
||||
ea.style.backgroundColor = "transparent";
|
||||
ea.style.strokeColor = "transparent";
|
||||
textEl.autoResize = false;
|
||||
textEl.width = Math.min(textEl.width, maxWidth);
|
||||
ea.addElementsToView(false, false, true);
|
||||
addEventHandler(eventHandler);
|
||||
return;
|
||||
}
|
||||
|
||||
if(!container && (win.ExcalidrawScribbleHelper.action === "Sticky")) {
|
||||
@@ -342,36 +377,22 @@ eventHandler = async (evt) => {
|
||||
ea.selectElementsInView(containers);
|
||||
};
|
||||
|
||||
// ---------------------
|
||||
// Edit Existing Element
|
||||
// ---------------------
|
||||
const editExistingTextElement = async (elements) => {
|
||||
windowOpen = true;
|
||||
ea.copyViewElementsToEAforEditing(elements);
|
||||
const el = ea.getElements()[0];
|
||||
ea.style.strokeColor = el.strokeColor;
|
||||
const text = await utils.inputPrompt(
|
||||
"Edit text","",elements[0].rawText,undefined,5,true,customControls,true
|
||||
);
|
||||
windowOpen = false;
|
||||
if(!text) return;
|
||||
|
||||
el.strokeColor = ea.style.strokeColor;
|
||||
el.originalText = text;
|
||||
el.text = text;
|
||||
el.rawText = text;
|
||||
ea.refreshTextElementSize(el.id);
|
||||
await ea.addElementsToView(false,false);
|
||||
if(el.containerId) {
|
||||
const containers = ea.getViewElements().filter(e=>e.id === el.containerId);
|
||||
api.updateContainerSize(containers);
|
||||
ea.selectElementsInView(containers);
|
||||
//---------------------
|
||||
// Script entry point
|
||||
//---------------------
|
||||
//Stop the script if scribble helper is clicked and no eligable element is selected
|
||||
let silent = false;
|
||||
if (win.ExcalidrawScribbleHelper?.eventHandler) {
|
||||
removeEventHandler(win.ExcalidrawScribbleHelper.eventHandler);
|
||||
delete win.ExcalidrawScribbleHelper.eventHandler;
|
||||
delete win.ExcalidrawScribbleHelper.window;
|
||||
if(!(containerElements.length === 1 || selectedTextElements.length === 1)) {
|
||||
new Notice ("Scribble Helper was stopped",1000);
|
||||
return;
|
||||
}
|
||||
silent = true;
|
||||
}
|
||||
|
||||
//--------------
|
||||
// Start actions
|
||||
//--------------
|
||||
if(!win.ExcalidrawScribbleHelper?.eventHandler) {
|
||||
if(!silent) new Notice(
|
||||
"To create a new text element,\ndouble-tap the screen.\n\n" +
|
||||
|
||||
@@ -7,28 +7,23 @@ This script modifies the color lightness/hue/saturation/transparency of selected
|
||||
- The color of SVG elements and nested Excalidraw drawings will only be mapped. When mapping colors, the original image remains unchanged, only a mapping table is created and the image is recolored during rendering of your Excalidraw screen. In case you want to make manual changes you can also edit the mapping in Markdown View Mode under `## Embedded Files`
|
||||
|
||||
If you select only a single SVG or nested Excalidraw element, then the script offers an additional feature. You can map colors one by one in the image.
|
||||
```js*/
|
||||
```js
|
||||
*/
|
||||
|
||||
const HELP_TEXT = `
|
||||
<ul>
|
||||
<li dir="auto">Select SVG images, nested Excalidraw drawings and/or regular Excalidraw elements</li>
|
||||
<li dir="auto">For a single selected image, you can map colors individually in the color mapping section</li>
|
||||
<li dir="auto">For Excalidraw elements: stroke and background colors are modified permanently</li>
|
||||
<li dir="auto">For SVG/nested drawings: original files stay unchanged, color mapping is stored under <code>## Embedded Files</code></li>
|
||||
<li dir="auto">Using color maps helps maintain links between drawings while allowing different color themes</li>
|
||||
<li dir="auto">Sliders work on relative scale - the amount of change is applied to current values</li>
|
||||
<li dir="auto">Unlike Excalidraw's opacity setting which affects the whole element:
|
||||
<ul>
|
||||
<li dir="auto">Shade Master can set different opacity for stroke vs background</li>
|
||||
<li dir="auto">Note: SVG/nested drawing colors are mapped at color name level, thus "black" is different from "#000000"</li>
|
||||
<li dir="auto">Additionally if the same color is used as fill and stroke the color can only be mapped once</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li dir="auto">This is an experimental script - contributions welcome on GitHub via PRs</li>
|
||||
</ul>
|
||||
<div class="excalidraw-videoWrapper"><div>
|
||||
<iframe src="https://www.youtube.com/embed/ISuORbVKyhQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
|
||||
</div></div>
|
||||
- Select SVG images, nested Excalidraw drawings and/or regular Excalidraw elements
|
||||
- For a single selected image, you can map colors individually in the color mapping section
|
||||
- For Excalidraw elements: stroke and background colors are modified permanently
|
||||
- For SVG/nested drawings: original files stay unchanged, color mapping is stored under \`## Embedded Files\`
|
||||
- Using color maps helps maintain links between drawings while allowing different color themes
|
||||
- Sliders work on relative scale - the amount of change is applied to current values
|
||||
- Unlike Excalidraw's opacity setting which affects the whole element:
|
||||
- Shade Master can set different opacity for stroke vs background
|
||||
- **Note:** SVG/nested drawing colors are mapped at color name level, thus "black" is different from "#000000"
|
||||
- Additionally if the same color is used as fill and stroke the color can only be mapped once
|
||||
- This is an experimental script - contributions welcome on GitHub via PRs
|
||||
|
||||

|
||||
`;
|
||||
|
||||
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.7.2")) {
|
||||
@@ -343,7 +338,8 @@ function showModal() {
|
||||
const helpDetailsDiv = helpDiv.createEl("div", {
|
||||
attr: { style: "margin-top: 0em; " }
|
||||
});
|
||||
helpDetailsDiv.innerHTML = HELP_TEXT;
|
||||
//helpDetailsDiv.innerHTML = HELP_TEXT;
|
||||
await ea.obsidian.MarkdownRenderer.render(ea.plugin.app, HELP_TEXT, helpDetailsDiv, "", ea.plugin);
|
||||
|
||||
const component = new ea.obsidian.Setting(contentEl)
|
||||
.setName(FORMAT)
|
||||
|
||||
@@ -21,7 +21,7 @@ The script will convert your drawing into a slideshow presentation.
|
||||
|
||||
```javascript
|
||||
*/
|
||||
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.1.7")) {
|
||||
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.8.0")) {
|
||||
new Notice("This script requires a newer version of Excalidraw. Please install the latest version.");
|
||||
return;
|
||||
}
|
||||
@@ -46,6 +46,8 @@ const TRANSITION_DELAY = 1000; //maximum time for transition between slides in m
|
||||
const FRAME_SLEEP = 1; //milliseconds
|
||||
const EDIT_ZOOMOUT = 0.7; //70% of original slide zoom, set to a value between 1 and 0
|
||||
const FADE_LEVEL = 0.1; //opacity of the slideshow controls after fade delay (value between 0 and 1)
|
||||
const PRINT_SLIDE_WIDTH = 1920;
|
||||
const PRINT_SLIDE_HEIGHT = 1080;
|
||||
//using outerHTML because the SVG object returned by Obsidin is in the main workspace window
|
||||
//but excalidraw might be open in a popout window which has a different document object
|
||||
const SVG_COG = ea.obsidian.getIcon("lucide-settings").outerHTML;
|
||||
@@ -57,6 +59,7 @@ const SVG_MAXIMIZE = ea.obsidian.getIcon("lucide-maximize").outerHTML;
|
||||
const SVG_MINIMIZE = ea.obsidian.getIcon("lucide-minimize").outerHTML;
|
||||
const SVG_LASER_ON = ea.obsidian.getIcon("lucide-hand").outerHTML;
|
||||
const SVG_LASER_OFF = ea.obsidian.getIcon("lucide-wand").outerHTML;
|
||||
const SVG_PRINTER = ea.obsidian.getIcon("lucide-printer").outerHTML;
|
||||
|
||||
//-------------------------------
|
||||
//utility & convenience functions
|
||||
@@ -202,7 +205,7 @@ const gotoFullscreen = async () => {
|
||||
}
|
||||
await waitForExcalidrawResize();
|
||||
const layerUIWrapper = contentEl.querySelector(".layer-ui__wrapper");
|
||||
if(!layerUIWrapper.hasClass("excalidraw-hidden")) layerUIWrapper.addClass("excalidraw-hidden");
|
||||
if(!layerUIWrapper?.hasClass("excalidraw-hidden")) layerUIWrapper.addClass("excalidraw-hidden");
|
||||
if(toggleFullscreenButton) toggleFullscreenButton.innerHTML = SVG_MINIMIZE;
|
||||
resetControlPanelElPosition();
|
||||
isFullscreen = true;
|
||||
@@ -271,8 +274,8 @@ if(presentationPathType==="line") {
|
||||
//-----------------------------
|
||||
// scroll-to-location functions
|
||||
//-----------------------------
|
||||
const getNavigationRect = ({ x1, y1, x2, y2 }) => {
|
||||
const { width, height } = excalidrawAPI.getAppState();
|
||||
const getNavigationRect = ({ x1, y1, x2, y2, printDimensions }) => {
|
||||
const { width, height } = printDimensions ? printDimensions : excalidrawAPI.getAppState();
|
||||
const ratioX = width / Math.abs(x1 - x2);
|
||||
const ratioY = height / Math.abs(y1 - y2);
|
||||
let ratio = Math.min(Math.max(ratioX, ratioY), 30);
|
||||
@@ -534,6 +537,20 @@ const createPresentationNavigationPanel = () => {
|
||||
}
|
||||
});
|
||||
}
|
||||
if(ea.DEVICE.isDesktop) {
|
||||
el.createEl("button",{
|
||||
attr: {
|
||||
style: `
|
||||
margin-right: calc(var(--default-button-size)*0.25);`,
|
||||
title: `Print to PDF\nClick to print slides at ${PRINT_SLIDE_WIDTH}x${
|
||||
PRINT_SLIDE_HEIGHT}\nHold SHIFT to print the presentation as displayed`
|
||||
//${!presentationPathLineEl ? "\nHold ALT/OPT to clip frames":""}`
|
||||
}
|
||||
}, button => {
|
||||
button.innerHTML = SVG_PRINTER;
|
||||
button.onclick = (e) => printToPDF(e);
|
||||
});
|
||||
}
|
||||
el.createEl("button",{
|
||||
attr: {
|
||||
style: `
|
||||
@@ -542,7 +559,7 @@ const createPresentationNavigationPanel = () => {
|
||||
}
|
||||
}, button => {
|
||||
button.innerHTML = SVG_FINISH;
|
||||
button.onclick = () => exitPresentation()
|
||||
button.onclick = () => exitPresentation();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -741,6 +758,96 @@ const exitPresentation = async (openForEdit = false) => {
|
||||
}
|
||||
}
|
||||
|
||||
//--------------------------
|
||||
// Print to PDF
|
||||
//--------------------------
|
||||
let notice;
|
||||
let noticeEl;
|
||||
function setSingleNotice(message) {
|
||||
if(noticeEl?.parentElement) {
|
||||
notice.setMessage(message);
|
||||
return;
|
||||
}
|
||||
notice = new Notice(message, 0);
|
||||
noticeEl = notice.containerEl ?? notice.noticeEl;
|
||||
}
|
||||
|
||||
function hideSingleNotice() {
|
||||
if(noticeEl?.parentElement) {
|
||||
notice.hide();
|
||||
}
|
||||
}
|
||||
|
||||
const translateToZero = ({ top, left, bottom, right }, padding) => {
|
||||
const {topX, topY, width, height} = ea.getBoundingBox(ea.getViewElements());
|
||||
const newTop = top - (topY - padding);
|
||||
const newLeft = left - (topX - padding);
|
||||
const newBottom = bottom - (topY - padding);
|
||||
const newRight = right - (topX - padding);
|
||||
|
||||
return {
|
||||
top: newTop,
|
||||
left: newLeft,
|
||||
bottom: newBottom,
|
||||
right: newRight,
|
||||
};
|
||||
}
|
||||
|
||||
const printToPDF = async (e) => {
|
||||
const slideWidth = e.shiftKey ? excalidrawAPI.getAppState().width : PRINT_SLIDE_WIDTH;
|
||||
const slideHeight = e.shiftKey ? excalidrawAPI.getAppState().height : PRINT_SLIDE_HEIGHT;
|
||||
//const shouldClipFrames = !presentationPathLineEl && e.altKey;
|
||||
const shouldClipFrames = false;
|
||||
//huge padding to ensure the HD window always fits the width
|
||||
//no padding if frames are clipped
|
||||
const padding = shouldClipFrames ? 0 : Math.round(Math.max(slideWidth,slideHeight)/2)+10;
|
||||
const st = ea.getExcalidrawAPI().getAppState();
|
||||
setSingleNotice("Generating image. This can take a longer time depending on the size of the image and speed of your device");
|
||||
const svg = await ea.createViewSVG({
|
||||
withBackground: true,
|
||||
theme: st.theme,
|
||||
frameRendering: { enabled: shouldClipFrames, name: false, outline: false, clip: shouldClipFrames },
|
||||
padding,
|
||||
selectedOnly: false,
|
||||
skipInliningFonts: false,
|
||||
embedScene: false,
|
||||
});
|
||||
const pages = [];
|
||||
for(i=0;i<slides.length;i++) {
|
||||
setSingleNotice(`Generating slide ${i+1}`);
|
||||
const s = slides[i];
|
||||
const { top, left, bottom, right } = translateToZero(
|
||||
getNavigationRect({
|
||||
...s,
|
||||
printDimensions: {width: slideWidth, height: slideHeight}
|
||||
}), padding
|
||||
);
|
||||
//always create the new SVG in the main Obsidian workspace (not the popout window, if present)
|
||||
const host = window.createDiv();
|
||||
host.innerHTML = svg.outerHTML;
|
||||
const clonedSVG = host.firstElementChild;
|
||||
const width = Math.abs(left-right);
|
||||
const height = Math.abs(top-bottom);
|
||||
clonedSVG.setAttribute("viewBox", `${left} ${top} ${width} ${height}`);
|
||||
clonedSVG.setAttribute("width", `${width}`);
|
||||
clonedSVG.setAttribute("height", `${height}`);
|
||||
pages.push(clonedSVG);
|
||||
}
|
||||
const bgColor = ea.getExcalidrawAPI().getAppState().viewBackgroundColor;
|
||||
setSingleNotice("Creating PDF Document");
|
||||
ea.createPDF({
|
||||
SVG: pages,
|
||||
scale: { fitToPage: true },
|
||||
pageProps: {
|
||||
dimensions: { width: slideWidth, height: slideHeight },
|
||||
backgroundColor: bgColor,
|
||||
margin: { left: 0, right: 0, top: 0, bottom: 0 },
|
||||
alignment: "center"
|
||||
},
|
||||
filename: ea.targetView.file.basename + ".pdf",
|
||||
}).then(()=>hideSingleNotice());
|
||||
}
|
||||
|
||||
//--------------------------
|
||||
// Start presentation or open presentation settings on double click
|
||||
//--------------------------
|
||||
@@ -768,7 +875,11 @@ const start = async () => {
|
||||
}
|
||||
|
||||
const timestamp = Date.now();
|
||||
if(window.ExcalidrawSlideshow && (window.ExcalidrawSlideshow.script === utils.scriptFile.path) && (timestamp - window.ExcalidrawSlideshow.timestamp <400) ) {
|
||||
if(
|
||||
window.ExcalidrawSlideshow &&
|
||||
(window.ExcalidrawSlideshow.script === utils.scriptFile.path) &&
|
||||
(timestamp - window.ExcalidrawSlideshow.timestamp <400)
|
||||
) {
|
||||
if(window.ExcalidrawSlideshowStartTimer) {
|
||||
window.clearTimeout(window.ExcalidrawSlideshowStartTimer);
|
||||
delete window.ExcalidrawSlideshowStartTimer;
|
||||
@@ -789,4 +900,4 @@ if(window.ExcalidrawSlideshow && (window.ExcalidrawSlideshow.script === utils.sc
|
||||
window.ExcalidrawSlideshow.slide[ea.targetView.file.path] = 0;
|
||||
|
||||
window.ExcalidrawSlideshowStartTimer = window.setTimeout(start,500);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
This script splits an ellipse at any point where a line intersects it. If no lines are selected, it will use every line that intersects the ellipse. Otherwise, it will only use the selected lines. If there is no intersecting line, the ellipse will be converted into a line object.
|
||||
There is also the option to close the object along the cut, which will close the cut in the shape of the line.
|
||||

|
||||

|
||||

|
||||

|
||||
Tip: To use an ellipse as the cutting object, you first have to use this script on it, since it will convert the ellipse into a line.
|
||||
|
||||
|
||||
@@ -54,6 +54,7 @@ angles.forEach((angle, key) => {
|
||||
|
||||
const lineId = ea.addLine(points);
|
||||
const line = ea.getElement(lineId);
|
||||
if (closeObject && cuttingLine) line.polygon = true;
|
||||
line.frameId = ellipse.frameId;
|
||||
line.groupIds = ellipse.groupIds;
|
||||
});
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
/*
|
||||

|
||||
|
||||
Fit a text to the arch of a circle. The script will prompt you for the radius of the circle and then split your text to individual letters and place each letter to the arch defined by the radius. Setting a lower radius value will increase the arching of the text. Note that the arched-text will no longer be editable as a text element and it will no longer function as a markdown link. Emojis are currently not supported.
|
||||
|
||||
```javascript
|
||||
*/
|
||||
el = ea.getViewSelectedElement();
|
||||
if(!el || el.type!=="text") {
|
||||
new Notice("Please select a text element");
|
||||
return;
|
||||
}
|
||||
|
||||
ea.style.fontSize = el.fontSize;
|
||||
ea.style.fontFamily = el.fontFamily;
|
||||
ea.style.strokeColor = el.strokeColor;
|
||||
ea.style.opacity = el.opacity;
|
||||
|
||||
const r = parseInt (await utils.inputPrompt("The radius of the arch you'd like to fit the text to","number","150"));
|
||||
const archAbove = await utils.suggester(["Arch above","Arch below"],[true,false]);
|
||||
|
||||
if(isNaN(r)) {
|
||||
new Notice("The radius is not a number");
|
||||
return;
|
||||
}
|
||||
|
||||
circlePoint = (angle) => archAbove
|
||||
? [
|
||||
r * Math.sin(angle),
|
||||
-r * Math.cos(angle)
|
||||
]
|
||||
: [
|
||||
-r * Math.sin(angle),
|
||||
r * Math.cos(angle)
|
||||
];
|
||||
|
||||
let rot = (archAbove ? -0.5 : 0.5) * ea.measureText(el.text).width/r;
|
||||
|
||||
let objectIDs = [];
|
||||
for(i=0;i<el.text.length;i++) {
|
||||
const character = el.text.substring(i,i+1);
|
||||
const width = ea.measureText(character).width;
|
||||
ea.style.angle = rot;
|
||||
const [x,y] = circlePoint(rot);
|
||||
rot += (archAbove ? 1 : -1) *width / r;
|
||||
objectIDs.push(ea.addText(x,y,character));
|
||||
}
|
||||
ea.addToGroup(objectIDs);
|
||||
ea.addElementsToView(true, false, true);
|
||||
1078
ea-scripts/Text to Path.md
Normal file
|
Before Width: | Height: | Size: 327 B After Width: | Height: | Size: 327 B |
476
ea-scripts/To Line.md
Normal file
@@ -0,0 +1,476 @@
|
||||
/**
|
||||
* Converts an ellipse element to a line element
|
||||
* @param {Object} ellipse - The ellipse element to convert
|
||||
* @param {number} pointDensity - Optional number of points to generate (defaults to 64)
|
||||
* @returns {string} The ID of the created line element
|
||||
```js*/
|
||||
function ellipseToLine(ellipse, pointDensity = 64) {
|
||||
if (!ellipse || ellipse.type !== "ellipse") {
|
||||
throw new Error("Input must be an ellipse element");
|
||||
}
|
||||
|
||||
// Calculate points along the ellipse perimeter
|
||||
const stepSize = (Math.PI * 2) / pointDensity;
|
||||
const points = drawEllipse(
|
||||
ellipse.x,
|
||||
ellipse.y,
|
||||
ellipse.width,
|
||||
ellipse.height,
|
||||
ellipse.angle,
|
||||
0,
|
||||
Math.PI * 2,
|
||||
stepSize
|
||||
);
|
||||
|
||||
// Save original styling to apply to the new line
|
||||
const originalStyling = {
|
||||
strokeColor: ellipse.strokeColor,
|
||||
strokeWidth: ellipse.strokeWidth,
|
||||
backgroundColor: ellipse.backgroundColor,
|
||||
fillStyle: ellipse.fillStyle,
|
||||
roughness: ellipse.roughness,
|
||||
strokeSharpness: ellipse.strokeSharpness,
|
||||
frameId: ellipse.frameId,
|
||||
groupIds: [...ellipse.groupIds],
|
||||
opacity: ellipse.opacity
|
||||
};
|
||||
|
||||
// Use current style
|
||||
const prevStyle = {...ea.style};
|
||||
|
||||
// Apply ellipse styling to the line
|
||||
ea.style.strokeColor = originalStyling.strokeColor;
|
||||
ea.style.strokeWidth = originalStyling.strokeWidth;
|
||||
ea.style.backgroundColor = originalStyling.backgroundColor;
|
||||
ea.style.fillStyle = originalStyling.fillStyle;
|
||||
ea.style.roughness = originalStyling.roughness;
|
||||
ea.style.strokeSharpness = originalStyling.strokeSharpness;
|
||||
ea.style.opacity = originalStyling.opacity;
|
||||
|
||||
// Create the line and close it
|
||||
const lineId = ea.addLine(points);
|
||||
const line = ea.getElement(lineId);
|
||||
|
||||
// Make it a polygon to close the path
|
||||
line.polygon = true;
|
||||
|
||||
// Transfer grouping and frame information
|
||||
line.frameId = originalStyling.frameId;
|
||||
line.groupIds = originalStyling.groupIds;
|
||||
|
||||
// Restore previous style
|
||||
ea.style = prevStyle;
|
||||
|
||||
return lineId;
|
||||
|
||||
// Helper function from the Split Ellipse script
|
||||
function drawEllipse(x, y, width, height, angle = 0, start = 0, end = Math.PI*2, step = Math.PI/32) {
|
||||
const ellipse = (t) => {
|
||||
const spanningVector = rotateVector([width/2*Math.cos(t), height/2*Math.sin(t)], angle);
|
||||
const baseVector = [x+width/2, y+height/2];
|
||||
return addVectors([baseVector, spanningVector]);
|
||||
}
|
||||
|
||||
if(end <= start) end = end + Math.PI*2;
|
||||
|
||||
let points = [];
|
||||
const almostEnd = end - step/2;
|
||||
for (let t = start; t < almostEnd; t = t + step) {
|
||||
points.push(ellipse(t));
|
||||
}
|
||||
points.push(ellipse(end));
|
||||
return points;
|
||||
}
|
||||
|
||||
function rotateVector(vec, ang) {
|
||||
var cos = Math.cos(ang);
|
||||
var sin = Math.sin(ang);
|
||||
return [vec[0] * cos - vec[1] * sin, vec[0] * sin + vec[1] * cos];
|
||||
}
|
||||
|
||||
function addVectors(vectors) {
|
||||
return vectors.reduce((acc, vec) => [acc[0] + vec[0], acc[1] + vec[1]], [0, 0]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a rectangle element to a line element
|
||||
* @param {Object} rectangle - The rectangle element to convert
|
||||
* @param {number} pointDensity - Optional number of points to generate for curved segments (defaults to 16)
|
||||
* @returns {string} The ID of the created line element
|
||||
*/
|
||||
function rectangleToLine(rectangle, pointDensity = 16) {
|
||||
if (!rectangle || rectangle.type !== "rectangle") {
|
||||
throw new Error("Input must be a rectangle element");
|
||||
}
|
||||
|
||||
// Save original styling to apply to the new line
|
||||
const originalStyling = {
|
||||
strokeColor: rectangle.strokeColor,
|
||||
strokeWidth: rectangle.strokeWidth,
|
||||
backgroundColor: rectangle.backgroundColor,
|
||||
fillStyle: rectangle.fillStyle,
|
||||
roughness: rectangle.roughness,
|
||||
strokeSharpness: rectangle.strokeSharpness,
|
||||
frameId: rectangle.frameId,
|
||||
groupIds: [...rectangle.groupIds],
|
||||
opacity: rectangle.opacity
|
||||
};
|
||||
|
||||
// Use current style
|
||||
const prevStyle = {...ea.style};
|
||||
|
||||
// Apply rectangle styling to the line
|
||||
ea.style.strokeColor = originalStyling.strokeColor;
|
||||
ea.style.strokeWidth = originalStyling.strokeWidth;
|
||||
ea.style.backgroundColor = originalStyling.backgroundColor;
|
||||
ea.style.fillStyle = originalStyling.fillStyle;
|
||||
ea.style.roughness = originalStyling.roughness;
|
||||
ea.style.strokeSharpness = originalStyling.strokeSharpness;
|
||||
ea.style.opacity = originalStyling.opacity;
|
||||
|
||||
// Calculate points for the rectangle perimeter
|
||||
const points = generateRectanglePoints(rectangle, pointDensity);
|
||||
|
||||
// Create the line and close it
|
||||
const lineId = ea.addLine(points);
|
||||
const line = ea.getElement(lineId);
|
||||
|
||||
// Make it a polygon to close the path
|
||||
line.polygon = true;
|
||||
|
||||
// Transfer grouping and frame information
|
||||
line.frameId = originalStyling.frameId;
|
||||
line.groupIds = originalStyling.groupIds;
|
||||
|
||||
// Restore previous style
|
||||
ea.style = prevStyle;
|
||||
|
||||
return lineId;
|
||||
|
||||
// Helper function to generate rectangle points with optional rounded corners
|
||||
function generateRectanglePoints(rectangle, pointDensity) {
|
||||
const { x, y, width, height, angle = 0 } = rectangle;
|
||||
const centerX = x + width / 2;
|
||||
const centerY = y + height / 2;
|
||||
|
||||
// If no roundness, create a simple rectangle
|
||||
if (!rectangle.roundness) {
|
||||
const corners = [
|
||||
[x, y], // top-left
|
||||
[x + width, y], // top-right
|
||||
[x + width, y + height], // bottom-right
|
||||
[x, y + height], // bottom-left
|
||||
[x,y] //origo
|
||||
];
|
||||
|
||||
// Apply rotation if needed
|
||||
if (angle !== 0) {
|
||||
return corners.map(point => rotatePoint(point, [centerX, centerY], angle));
|
||||
}
|
||||
return corners;
|
||||
}
|
||||
|
||||
// Handle rounded corners
|
||||
const points = [];
|
||||
|
||||
// Calculate corner radius using Excalidraw's algorithm
|
||||
const cornerRadius = getCornerRadius(Math.min(width, height), rectangle);
|
||||
const clampedRadius = Math.min(cornerRadius, width / 2, height / 2);
|
||||
|
||||
// Corner positions
|
||||
const topLeft = [x + clampedRadius, y + clampedRadius];
|
||||
const topRight = [x + width - clampedRadius, y + clampedRadius];
|
||||
const bottomRight = [x + width - clampedRadius, y + height - clampedRadius];
|
||||
const bottomLeft = [x + clampedRadius, y + height - clampedRadius];
|
||||
|
||||
// Add top-left corner arc
|
||||
points.push(...createArc(
|
||||
topLeft[0], topLeft[1], clampedRadius, Math.PI, Math.PI * 1.5, pointDensity));
|
||||
|
||||
// Add top edge
|
||||
points.push([x + clampedRadius, y], [x + width - clampedRadius, y]);
|
||||
|
||||
// Add top-right corner arc
|
||||
points.push(...createArc(
|
||||
topRight[0], topRight[1], clampedRadius, Math.PI * 1.5, Math.PI * 2, pointDensity));
|
||||
|
||||
// Add right edge
|
||||
points.push([x + width, y + clampedRadius], [x + width, y + height - clampedRadius]);
|
||||
|
||||
// Add bottom-right corner arc
|
||||
points.push(...createArc(
|
||||
bottomRight[0], bottomRight[1], clampedRadius, 0, Math.PI * 0.5, pointDensity));
|
||||
|
||||
// Add bottom edge
|
||||
points.push([x + width - clampedRadius, y + height], [x + clampedRadius, y + height]);
|
||||
|
||||
// Add bottom-left corner arc
|
||||
points.push(...createArc(
|
||||
bottomLeft[0], bottomLeft[1], clampedRadius, Math.PI * 0.5, Math.PI, pointDensity));
|
||||
|
||||
// Add left edge
|
||||
points.push([x, y + height - clampedRadius], [x, y + clampedRadius]);
|
||||
|
||||
// Apply rotation if needed
|
||||
if (angle !== 0) {
|
||||
return points.map(point => rotatePoint(point, [centerX, centerY], angle));
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
|
||||
// Helper function to create an arc of points
|
||||
function createArc(centerX, centerY, radius, startAngle, endAngle, pointDensity) {
|
||||
const points = [];
|
||||
const angleStep = (endAngle - startAngle) / pointDensity;
|
||||
|
||||
for (let i = 0; i <= pointDensity; i++) {
|
||||
const angle = startAngle + i * angleStep;
|
||||
const x = centerX + radius * Math.cos(angle);
|
||||
const y = centerY + radius * Math.sin(angle);
|
||||
points.push([x, y]);
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
|
||||
// Helper function to rotate a point around a center
|
||||
function rotatePoint(point, center, angle) {
|
||||
const sin = Math.sin(angle);
|
||||
const cos = Math.cos(angle);
|
||||
|
||||
// Translate point to origin
|
||||
const x = point[0] - center[0];
|
||||
const y = point[1] - center[1];
|
||||
|
||||
// Rotate point
|
||||
const xNew = x * cos - y * sin;
|
||||
const yNew = x * sin + y * cos;
|
||||
|
||||
// Translate point back
|
||||
return [xNew + center[0], yNew + center[1]];
|
||||
}
|
||||
}
|
||||
|
||||
function getCornerRadius(x, element) {
|
||||
const fixedRadiusSize = element.roundness?.value ?? 32;
|
||||
const CUTOFF_SIZE = fixedRadiusSize / 0.25;
|
||||
if (x <= CUTOFF_SIZE) {
|
||||
return x * 0.25;
|
||||
}
|
||||
return fixedRadiusSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a diamond element to a line element
|
||||
* @param {Object} diamond - The diamond element to convert
|
||||
* @param {number} pointDensity - Optional number of points to generate for curved segments (defaults to 16)
|
||||
* @returns {string} The ID of the created line element
|
||||
*/
|
||||
function diamondToLine(diamond, pointDensity = 16) {
|
||||
if (!diamond || diamond.type !== "diamond") {
|
||||
throw new Error("Input must be a diamond element");
|
||||
}
|
||||
|
||||
// Save original styling to apply to the new line
|
||||
const originalStyling = {
|
||||
strokeColor: diamond.strokeColor,
|
||||
strokeWidth: diamond.strokeWidth,
|
||||
backgroundColor: diamond.backgroundColor,
|
||||
fillStyle: diamond.fillStyle,
|
||||
roughness: diamond.roughness,
|
||||
strokeSharpness: diamond.strokeSharpness,
|
||||
frameId: diamond.frameId,
|
||||
groupIds: [...diamond.groupIds],
|
||||
opacity: diamond.opacity
|
||||
};
|
||||
|
||||
// Use current style
|
||||
const prevStyle = {...ea.style};
|
||||
|
||||
// Apply diamond styling to the line
|
||||
ea.style.strokeColor = originalStyling.strokeColor;
|
||||
ea.style.strokeWidth = originalStyling.strokeWidth;
|
||||
ea.style.backgroundColor = originalStyling.backgroundColor;
|
||||
ea.style.fillStyle = originalStyling.fillStyle;
|
||||
ea.style.roughness = originalStyling.roughness;
|
||||
ea.style.strokeSharpness = originalStyling.strokeSharpness;
|
||||
ea.style.opacity = originalStyling.opacity;
|
||||
|
||||
// Calculate points for the diamond perimeter
|
||||
const points = generateDiamondPoints(diamond, pointDensity);
|
||||
|
||||
// Create the line and close it
|
||||
const lineId = ea.addLine(points);
|
||||
const line = ea.getElement(lineId);
|
||||
|
||||
// Make it a polygon to close the path
|
||||
line.polygon = true;
|
||||
|
||||
// Transfer grouping and frame information
|
||||
line.frameId = originalStyling.frameId;
|
||||
line.groupIds = originalStyling.groupIds;
|
||||
|
||||
// Restore previous style
|
||||
ea.style = prevStyle;
|
||||
|
||||
return lineId;
|
||||
|
||||
function generateDiamondPoints(diamond, pointDensity) {
|
||||
const { x, y, width, height, angle = 0 } = diamond;
|
||||
const cx = x + width / 2;
|
||||
const cy = y + height / 2;
|
||||
|
||||
// Diamond corners
|
||||
const top = [cx, y];
|
||||
const right = [x + width, cy];
|
||||
const bottom = [cx, y + height];
|
||||
const left = [x, cy];
|
||||
|
||||
if (!diamond.roundness) {
|
||||
const corners = [top, right, bottom, left, top];
|
||||
if (angle !== 0) {
|
||||
return corners.map(pt => rotatePoint(pt, [cx, cy], angle));
|
||||
}
|
||||
return corners;
|
||||
}
|
||||
|
||||
// Clamp radius
|
||||
const r = Math.min(
|
||||
getCornerRadius(Math.min(width, height) / 2, diamond),
|
||||
width / 2,
|
||||
height / 2
|
||||
);
|
||||
|
||||
// For a diamond, the rounded corner is a *bezier* between the two adjacent edge points, not a circular arc.
|
||||
// Excalidraw uses a quadratic bezier for each corner, with the control point at the corner itself.
|
||||
|
||||
// Calculate edge directions
|
||||
function sub(a, b) { return [a[0] - b[0], a[1] - b[1]]; }
|
||||
function add(a, b) { return [a[0] + b[0], a[1] + b[1]]; }
|
||||
function norm([x, y]) {
|
||||
const len = Math.hypot(x, y);
|
||||
return [x / len, y / len];
|
||||
}
|
||||
function scale([x, y], s) { return [x * s, y * s]; }
|
||||
|
||||
// For each corner, move along both adjacent edges by r to get arc endpoints
|
||||
// Order: top, right, bottom, left
|
||||
const corners = [top, right, bottom, left];
|
||||
const next = [right, bottom, left, top];
|
||||
const prev = [left, top, right, bottom];
|
||||
|
||||
// For each corner, calculate the two points where the straight segments meet the arc
|
||||
const arcPoints = [];
|
||||
for (let i = 0; i < 4; ++i) {
|
||||
const c = corners[i];
|
||||
const n = next[i];
|
||||
const p = prev[i];
|
||||
const toNext = norm(sub(n, c));
|
||||
const toPrev = norm(sub(p, c));
|
||||
arcPoints.push([
|
||||
add(c, scale(toPrev, r)), // start of arc (from previous edge)
|
||||
add(c, scale(toNext, r)), // end of arc (to next edge)
|
||||
c // control point for bezier
|
||||
]);
|
||||
}
|
||||
|
||||
// Helper: quadratic bezier between p0 and p2 with control p1
|
||||
function bezier(p0, p1, p2, density) {
|
||||
const pts = [];
|
||||
for (let i = 0; i <= density; ++i) {
|
||||
const t = i / density;
|
||||
const mt = 1 - t;
|
||||
pts.push([
|
||||
mt*mt*p0[0] + 2*mt*t*p1[0] + t*t*p2[0],
|
||||
mt*mt*p0[1] + 2*mt*t*p1[1] + t*t*p2[1]
|
||||
]);
|
||||
}
|
||||
return pts;
|
||||
}
|
||||
|
||||
// Build path: for each corner, straight line to arc start, then bezier to arc end using corner as control
|
||||
let pts = [];
|
||||
for (let i = 0; i < 4; ++i) {
|
||||
const prevArc = arcPoints[(i + 3) % 4];
|
||||
const arc = arcPoints[i];
|
||||
if (i === 0) {
|
||||
pts.push(arc[0]);
|
||||
} else {
|
||||
pts.push(arc[0]);
|
||||
}
|
||||
// Quadratic bezier from arc[0] to arc[1] with control at arc[2] (the corner)
|
||||
pts.push(...bezier(arc[0], arc[2], arc[1], pointDensity));
|
||||
}
|
||||
pts.push(arcPoints[0][0]); // close
|
||||
|
||||
if (angle !== 0) {
|
||||
return pts.map(pt => rotatePoint(pt, [cx, cy], angle));
|
||||
}
|
||||
return pts;
|
||||
}
|
||||
|
||||
// Helper function to create an arc between two points
|
||||
function createArcBetweenPoints(startPoint, endPoint, centerX, centerY, pointDensity) {
|
||||
const startAngle = Math.atan2(startPoint[1] - centerY, startPoint[0] - centerX);
|
||||
const endAngle = Math.atan2(endPoint[1] - centerY, endPoint[0] - centerX);
|
||||
|
||||
// Ensure angles are in correct order for arc drawing
|
||||
let adjustedEndAngle = endAngle;
|
||||
if (endAngle < startAngle) {
|
||||
adjustedEndAngle += 2 * Math.PI;
|
||||
}
|
||||
|
||||
const points = [];
|
||||
const angleStep = (adjustedEndAngle - startAngle) / pointDensity;
|
||||
|
||||
// Start with the straight line to arc start
|
||||
points.push(startPoint);
|
||||
|
||||
// Create arc points
|
||||
for (let i = 1; i < pointDensity; i++) {
|
||||
const angle = startAngle + i * angleStep;
|
||||
const distance = Math.hypot(startPoint[0] - centerX, startPoint[1] - centerY);
|
||||
const x = centerX + distance * Math.cos(angle);
|
||||
const y = centerY + distance * Math.sin(angle);
|
||||
points.push([x, y]);
|
||||
}
|
||||
|
||||
// Add the end point of the arc
|
||||
points.push(endPoint);
|
||||
|
||||
return points;
|
||||
}
|
||||
|
||||
// Helper function to rotate a point around a center
|
||||
function rotatePoint(point, center, angle) {
|
||||
const sin = Math.sin(angle);
|
||||
const cos = Math.cos(angle);
|
||||
|
||||
// Translate point to origin
|
||||
const x = point[0] - center[0];
|
||||
const y = point[1] - center[1];
|
||||
|
||||
// Rotate point
|
||||
const xNew = x * cos - y * sin;
|
||||
const yNew = x * sin + y * cos;
|
||||
|
||||
// Translate point back
|
||||
return [xNew + center[0], yNew + center[1]];
|
||||
}
|
||||
}
|
||||
|
||||
const el = ea.getViewSelectedElement();
|
||||
switch (el.type) {
|
||||
case "rectangle":
|
||||
rectangleToLine(el);
|
||||
break;
|
||||
case "ellipse":
|
||||
ellipseToLine(el);
|
||||
break;
|
||||
case "diamond":
|
||||
diamondToLine(el);
|
||||
break;
|
||||
}
|
||||
ea.addElementsToView();
|
||||
@@ -47,6 +47,7 @@ I would love to include your contribution in the script library. If you have a s
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Golden%20Ratio.svg"/></div>|[[#Golden Ratio]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Grid%20Selected%20Images.svg"/></div>|[[#Grid selected images]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20format.svg"/></div>|[[#Mindmap format]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Printable%20Layout%20Wizard.svg"/></div>|[[#Printable Layout Wizard]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Zoom%20to%20Fit%20Selected%20Elements.svg"/></div>|[[#Zoom to Fit Selected Elements]]|
|
||||
|
||||
## Connectors and Arrows
|
||||
@@ -73,8 +74,8 @@ I would love to include your contribution in the script library. If you have a s
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Font%20Family.svg"/></div>|[[#Set Font Family]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Set%20Text%20Alignment.svg"/></div>|[[#Set Text Alignment]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Split%20text%20by%20lines.svg"/></div>|[[#Split text by lines]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20Arch.svg"/></div>|[[#Text Arch]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20Aura.svg"/></div>|[[#Text Aura]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20to%20Path.svg"/></div>|[[#Text to Path]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20to%20Sticky%20Notes.svg"/></div>|[[#Text to Sticky Notes]]|
|
||||
|
||||
## Styling and Appearance
|
||||
@@ -596,18 +597,24 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Split%20text%20by%20lines.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Split lines of text into separate text elements for easier reorganization<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-split-lines.jpg'></td></tr></table>
|
||||
|
||||
## Text Arch
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20Arch.md
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Text%20Arch.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Fit a text to the arch of a circle. The script will prompt you for the radius of the circle and then split your text to individual letters and place each letter to the arch defined by the radius. Setting a lower radius value will increase the arching of the text. Note that the arched-text will no longer be editable as a text element and it will no longer function as a markdown link. Emojis are currently not supported.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/text-arch.jpg'></td></tr></table>
|
||||
|
||||
## Text Aura
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20Aura.md
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Text%20Aura.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Select a single text element, or a text element in a container. The container must have a transparent background.<br>The script will add an aura to the text by adding 4 copies of the text each with the inverted stroke color of the original text element and with a very small X and Y offset. The resulting 4 + 1 (original) text elements or containers will be grouped.<br>If you copy a color string on the clipboard before running the script, the script will use that color instead of the inverted color.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-aura.jpg'></td></tr></table>
|
||||
|
||||
## Text to Path
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Text%20to%20Path.md
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Text%20to%20Path.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script allows you to fit a text element along a selected path: line, arrow, freedraw, ellipse, rectangle, or diamond. You can select either a path or a text element, or both:<br><br>
|
||||
- If only a path is selected, you will be prompted to provide the text.<br>
|
||||
- If only a text element is selected and it was previously fitted to a path, the script will use the original path if it is still present in the scene.<br>
|
||||
- If both a text and a path are selected, the script will fit the text to the selected path.<br><br>
|
||||
If the path is a perfect circle, you will be prompted to choose whether to fit the text above or below the circle.<br><br>
|
||||
After fitting, the text will no longer be editable as a standard text element or function as a markdown link. Emojis are not supported.<br>
|
||||
<img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-text-to-path.jpg'></td></tr></table>
|
||||
|
||||
## Toggle Grid
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Toggle%20Grid.md
|
||||
@@ -626,6 +633,12 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Uniform%20size.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data"><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-uniform-size.jpg"><br>The script will standardize the sizes of rectangles, diamonds and ellipses adjusting all the elements to match the largest width and height within the group.</td></tr></table>
|
||||
|
||||
# Printable Layout Wizard
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Printable%20Layout%20Wizard.md
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Printable%20Layout%20Wizard.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Export Excalidraw to PDF Pages: Define printable page areas using frames, then export each frame as a separate page in a multi-page PDF. Perfect for turning your Excalidraw drawings into printable notes, handouts, or booklets. Supports standard and custom page sizes, margins, and easy frame arrangement.<br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-01.png" style="max-width: 400px;"><br><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-layout-wizard-02.png" style="max-width: 400px;"></td></tr></table>
|
||||
|
||||
## Zoom to Fit Selected Elements
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Zoom%20to%20Fit%20Selected%20Elements.md
|
||||
|
||||
BIN
images/scripts-layout-wizard-01.png
Normal file
|
After Width: | Height: | Size: 101 KiB |
BIN
images/scripts-layout-wizard-02.png
Normal file
|
After Width: | Height: | Size: 97 KiB |
BIN
images/scripts-text-to-path.jpg
Normal file
|
After Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 95 KiB |
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.7.6-beta-1",
|
||||
"minAppVersion": "1.1.6",
|
||||
"version": "2.14.1-beta-2",
|
||||
"minAppVersion": "1.5.7",
|
||||
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
|
||||
"author": "Zsolt Viczian",
|
||||
"authorUrl": "https://zsolt.blog",
|
||||
"authorUrl": "https://excalidraw-obsidian.online",
|
||||
"isDesktopOnly": false
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.7.5",
|
||||
"minAppVersion": "1.1.6",
|
||||
"version": "2.14.0",
|
||||
"minAppVersion": "1.5.7",
|
||||
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
|
||||
"author": "Zsolt Viczian",
|
||||
"authorUrl": "https://www.zsolt.blog",
|
||||
"authorUrl": "https://excalidraw-obsidian.online",
|
||||
"fundingUrl": "https://ko-fi.com/zsolt",
|
||||
"helpUrl": "https://github.com/zsviczian/obsidian-excalidraw-plugin#readme",
|
||||
"isDesktopOnly": false
|
||||
}
|
||||
}
|
||||
4926
package-lock.json
generated
20
package.json
@@ -16,21 +16,20 @@
|
||||
"build:mathjax": "cd MathjaxToSVG && npm run build",
|
||||
"build:all": "npm run build:mathjax && npm run build",
|
||||
"dev:mathjax": "cd MathjaxToSVG && npm run dev",
|
||||
"dev:all": "npm run dev:mathjax && npm run dev",
|
||||
"build:lang": "node ./scripts/compressLanguages.js"
|
||||
"dev:all": "npm run dev:mathjax && npm run dev"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@zsviczian/excalidraw": "0.17.6-26",
|
||||
"chroma-js": "^2.4.2",
|
||||
"@zsviczian/excalidraw": "0.18.0-27",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"gl-matrix": "^3.4.3",
|
||||
"js-yaml": "^4.1.0",
|
||||
"lucide-react": "^0.263.1",
|
||||
"lucide-react": "^0.479.0",
|
||||
"mathjax-full": "^3.2.2",
|
||||
"monkey-around": "^2.3.0",
|
||||
"nanoid": "^4.0.2",
|
||||
@@ -40,8 +39,7 @@
|
||||
"react-dom": "^18.2.0",
|
||||
"roughjs": "^4.5.2",
|
||||
"woff2sfnt-sfnt2woff": "^1.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
"@cantoo/pdf-lib": "^2.2.4"
|
||||
"es6-promise-pool": "2.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"jsesc": "^3.0.2",
|
||||
@@ -61,7 +59,7 @@
|
||||
"@rollup/plugin-replace": "^5.0.2",
|
||||
"@rollup/plugin-typescript": "^12.1.2",
|
||||
"@rollup/plugin-json": "^6.1.0",
|
||||
"@types/chroma-js": "^2.4.0",
|
||||
"@types/chroma-js": "^3.1.1",
|
||||
"@types/js-beautify": "^1.14.0",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "^20.10.5",
|
||||
@@ -91,5 +89,9 @@
|
||||
"resolutions": {
|
||||
"@typescript-eslint/typescript-estree": "5.3.0"
|
||||
},
|
||||
"prettier": "@excalidraw/prettier-config"
|
||||
"prettier": "@excalidraw/prettier-config",
|
||||
"engines": {
|
||||
"node": ">=20.0.0",
|
||||
"npm": ">=10.0.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,9 +24,32 @@ const isProd = (process.env.NODE_ENV === "production");
|
||||
const isLib = (process.env.NODE_ENV === "lib");
|
||||
console.log(`Running: ${process.env.NODE_ENV}; isProd: ${isProd}; isLib: ${isLib}`);
|
||||
|
||||
|
||||
// Excalidraw React 19 compatiblity shim
|
||||
// Create JSX runtime compatibility layer
|
||||
const jsxRuntimeShim = `
|
||||
const jsx = (type, props, key) => {
|
||||
return React.createElement(type, props);
|
||||
};
|
||||
const jsxs = (type, props, key) => {
|
||||
return React.createElement(type, props);
|
||||
};
|
||||
const Fragment = React.Fragment;
|
||||
React.jsx = jsx;
|
||||
React.jsxs = jsxs;
|
||||
React.Fragment = Fragment;
|
||||
React.jsxRuntime = { jsx, jsxs, Fragment };
|
||||
window.__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ = { jsx, jsxs, Fragment };
|
||||
window.__WEBPACK_EXTERNAL_MODULE_react_jsx_dev_runtime__ = { jsx, jsxs, Fragment, jsxDEV: jsx };
|
||||
window['react/jsx-runtime'] = { jsx, jsxs, Fragment };
|
||||
window['react/jsx-dev-runtime'] = { jsx, jsxs, Fragment, jsxDEV: jsx };
|
||||
`;
|
||||
|
||||
|
||||
|
||||
const mathjaxtosvg_pkg = isLib ? "" : fs.readFileSync("./MathjaxToSVG/dist/index.js", "utf8");
|
||||
|
||||
const LANGUAGES = ['ru', 'zh-cn']; //english is not compressed as it is always loaded by default
|
||||
const LANGUAGES = ['ru', 'zh-cn', 'zh-tw', 'es']; //english is not compressed as it is always loaded by default
|
||||
|
||||
function trimLastSemicolon(input) {
|
||||
if (input.endsWith(";")) {
|
||||
@@ -99,7 +122,7 @@ const packageString = isLib
|
||||
? ""
|
||||
: ';const INITIAL_TIMESTAMP=Date.now();' + lzstring_pkg +
|
||||
'\nlet REACT_PACKAGES = `' +
|
||||
jsesc(react_pkg + reactdom_pkg, { quotes: 'backtick' }) +
|
||||
jsesc(react_pkg + reactdom_pkg + jsxRuntimeShim, { quotes: 'backtick' }) +
|
||||
'`;\n' +
|
||||
'const unpackExcalidraw = () => LZString.decompressFromBase64("' + LZString.compressToBase64(excalidraw_pkg) + '");\n' +
|
||||
'let {react, reactDOM } = new Function(`${REACT_PACKAGES}; return {react: React, reactDOM: ReactDOM};`)();\n' +
|
||||
@@ -147,6 +170,7 @@ const BUILD_CONFIG = {
|
||||
entryFileNames: 'main.js',
|
||||
format: 'cjs',
|
||||
exports: 'default',
|
||||
inlineDynamicImports: true, // Add this line only
|
||||
},
|
||||
plugins: getRollupPlugins(
|
||||
{
|
||||
|
||||
@@ -105,6 +105,169 @@
|
||||
*/
|
||||
//ea.onFileCreateHook = (data) => {};
|
||||
|
||||
/**
|
||||
* If set, this callback is triggered when a image is being saved in Excalidraw.
|
||||
* You can use this callback to customize the naming and path of pasted images to avoid
|
||||
* default names like "Pasted image 123147170.png" being saved in the attachments folder,
|
||||
* and instead use more meaningful names based on the Excalidraw file or other criteria,
|
||||
* plus save the image in a different folder.
|
||||
*
|
||||
* If the function returns null or undefined, the normal Excalidraw operation will continue
|
||||
* with the excalidraw generated name and default path.
|
||||
* If a filepath is returned, that will be used. Include the full Vault filepath and filename
|
||||
* with the file extension.
|
||||
* The currentImageName is the name of the image generated by excalidraw or provided during paste.
|
||||
*
|
||||
* @param data - An object containing the following properties:
|
||||
* @property {string} [currentImageName] - Default name for the image.
|
||||
* @property {string} drawingFilePath - The file path of the Excalidraw file where the image is being used.
|
||||
*
|
||||
* @returns {string} - The new filepath for the image including full vault path and extension.
|
||||
*
|
||||
* Example usage:
|
||||
* onImageFilePathHook: (data) => {
|
||||
* const { currentImageName, drawingFilePath } = data;
|
||||
* const ext = currentImageName.split('.').pop();
|
||||
* // Generate a new filepath based on the drawing file name and other criteria
|
||||
* return `${drawingFileName} - ${currentImageName || 'image'}.${ext}`;
|
||||
* }
|
||||
*
|
||||
* Signiture:
|
||||
* onImageFilePathHook: (data: {
|
||||
* currentImageName: string; // Excalidraw generated name of the image, or the name received from the file system.
|
||||
* drawingFilePath: string; // The full filepath of the Excalidraw file where the image is being used.
|
||||
* }) => string = null;
|
||||
*/
|
||||
// ea.onImageFilePathHook = (data) => { console.log(data); };
|
||||
|
||||
/**
|
||||
* If set, this callback is triggered when the Excalidraw image is being exported to
|
||||
* .svg, .png, or .excalidraw.
|
||||
* You can use this callback to customize the naming and path of the images. This allows
|
||||
* you to place images into an assets folder.
|
||||
*
|
||||
* If the function returns null or undefined, the normal Excalidraw operation will continue
|
||||
* with the currentImageName and in the same folder as the Excalidraw file
|
||||
* If a filepath is returned, that will be used. Include the full Vault filepath and filename
|
||||
* with the file extension.
|
||||
* !!!! If an image already exists on the path, that will be overwritten. When returning
|
||||
* your own image path, you must take care of unique filenames (if that is a requirement) !!!!
|
||||
* The current image name is the name generated by Excalidraw:
|
||||
* - my-drawing.png
|
||||
* - my-drawing.svg
|
||||
* - my-drawing.excalidraw
|
||||
* - my-drawing.dark.svg
|
||||
* - my-drawing.light.svg
|
||||
* - my-drawing.dark.png
|
||||
* - my-drawing.light.png
|
||||
*
|
||||
* @param data - An object containing the following properties:
|
||||
* @property {string} exportFilepath - Default export filepath for the image.
|
||||
* @property {string} excalidrawFile - TFile: The Excalidraw file being exported.
|
||||
* @property {string} exportExtension - The file extension of the export (e.g., .dark.svg, .png, .excalidraw).
|
||||
* @property {string} oldExcalidrawPath - If action === "move" The old path of the Excalidraw file, else undefined
|
||||
* @property {string} action - The action being performed:
|
||||
* "export" | "move" | "delete"
|
||||
* move and delete reference the change to the Excalidraw file.
|
||||
*
|
||||
* @returns {string} - The new filepath for the image including full vault path and extension.
|
||||
*
|
||||
* action === "move" || action === "delete" is only possible if "keep in sync" is enabled
|
||||
* in plugin export settings
|
||||
*
|
||||
* Example usage:
|
||||
* onImageFilePathHook: (data) => {
|
||||
* const { currentImageName, drawingFilePath, frontmatter } = data;
|
||||
* // Generate a new filepath based on the drawing file name and other criteria
|
||||
* const ext = currentImageName.split('.').pop();
|
||||
* if(frontmatter && frontmatter["my-custom-field"]) {
|
||||
* }
|
||||
* return `${drawingFileName} - ${currentImageName || 'image'}.${ext}`;
|
||||
* }
|
||||
*
|
||||
*/
|
||||
/*ea.onImageExportPathHook = (data) => {
|
||||
//debugger; //remove comment to debug using Developer Console
|
||||
|
||||
let {excalidrawFile, exportFilepath, exportExtension, oldExcalidrawPath, action} = data;
|
||||
const frontmatter = app.metadataCache.getFileCache(excalidrawFile)?.frontmatter;
|
||||
//console.log(data, frontmatter);
|
||||
|
||||
const excalidrawFilename = action === "move"
|
||||
? ea.splitFolderAndFilename(excalidrawFile.name).filename
|
||||
: excalidrawFile.name
|
||||
|
||||
if(excalidrawFilename.match(/^icon - /i)) {
|
||||
const {folderpath, filename, basename, extension} = ea.splitFolderAndFilename(exportFilepath);
|
||||
exportFilepath = "assets/icons/" + filename;
|
||||
return exportFilepath;
|
||||
}
|
||||
|
||||
if(excalidrawFilename.match(/^stickfigure - /i)) {
|
||||
const {folderpath, filename, basename, extension} = ea.splitFolderAndFilename(exportFilepath);
|
||||
exportFilepath = "assets/stickfigures/" + filename;
|
||||
return exportFilepath;
|
||||
}
|
||||
|
||||
if(excalidrawFilename.match(/^logo - /i)) {
|
||||
const {folderpath, filename, basename, extension} = ea.splitFolderAndFilename(exportFilepath);
|
||||
exportFilepath = "assets/logos/" + filename;
|
||||
return exportFilepath;
|
||||
}
|
||||
|
||||
// !!!! frontmatter will be undefined when action === "delete"
|
||||
// this means if you base your logic on frontmatter properties, then
|
||||
// plugin settings keep files in sync will break for those files when
|
||||
// deleting the Excalidraw file. The images will not be deleted, or worst
|
||||
// your logic might result in deleting other files. This hook gives you
|
||||
// powerful control, but the hook function logic requires careful testing
|
||||
// on your part.
|
||||
//if(frontmatter && frontmatter["is-asset"]) { //custom frontmatter property
|
||||
exportFilepath = ea.obsidian.normalizePath("assets/" + exportFilepath);
|
||||
return exportFilepath;
|
||||
//}
|
||||
|
||||
return exportFilepath;
|
||||
};*/
|
||||
|
||||
/**
|
||||
* Excalidraw supports auto-export of Excalidraw files to .png, .svg, and .excalidraw formats.
|
||||
*
|
||||
* Auto-export of Excalidraw files can be controlled at multiple levels.
|
||||
* 1) In plugin settings where you can set up default auto-export applicable to all your Excalidraw files.
|
||||
* 2) However, if you do not want to auto-export every file, you can also control auto-export
|
||||
* at the file level using the 'excalidraw-autoexport' frontmatter property.
|
||||
* 3) This hook gives you an additional layer of control over the auto-export process.
|
||||
*
|
||||
* This hook is triggered when an Excalidraw file is being saved.
|
||||
*
|
||||
* interface AutoexportConfig {
|
||||
* png: boolean; // Whether to auto-export to PNG
|
||||
* svg: boolean; // Whether to auto-export to SVG
|
||||
* excalidraw: boolean; // Whether to auto-export to Excalidraw format
|
||||
* theme: "light" | "dark" | "both"; // The theme to use for the export
|
||||
* }
|
||||
*
|
||||
* @param {Object} data - The data for the hook.
|
||||
* @param {AutoexportConfig} data.autoexportConfig - The current autoexport configuration.
|
||||
* @param {TFile} data.excalidrawFile - The Excalidraw file being auto-exported.
|
||||
* @returns {AutoexportConfig | null} - Return a modified AutoexportConfig to override the export behavior, or null to use the default.
|
||||
*/
|
||||
/*ea.onTriggerAutoexportHook = (data) => {
|
||||
let {autoexportConfig, excalidrawFile} = data;
|
||||
const frontmatter = app.metadataCache.getFileCache(excalidrawFile)?.frontmatter;
|
||||
//console.log(data, frontmatter);
|
||||
//logic based on filepath and frontmatter
|
||||
if(excalidrawFile.name.match(/^(?:icon|stickfigure|logo) - /i)) {
|
||||
autoexportConfig.theme = "light";
|
||||
autoexportConfig.svg = true;
|
||||
autoexportConfig.png = false;
|
||||
autoexportConfig.excalidraw = false;
|
||||
return autoexportConfig;
|
||||
}
|
||||
return autoexportConfig;
|
||||
};*/
|
||||
|
||||
/**
|
||||
* If set, this callback is triggered whenever the active canvas color changes
|
||||
* onCanvasColorChangeHook: (
|
||||
@@ -112,5 +275,5 @@
|
||||
* view: ExcalidrawView, //the excalidraw view
|
||||
* color: string,
|
||||
* ) => void = null;
|
||||
*/
|
||||
//ea.onCanvasColorChangeHook = (ea, view, color) => {};
|
||||
*/
|
||||
//ea.onCanvasColorChangeHook = (ea, view, color) => {};
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { customAlphabet } from "nanoid";
|
||||
import { ExcalidrawLib } from "../types/excalidrawLib";
|
||||
import { moment } from "obsidian";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { DeviceType } from "src/types/types";
|
||||
import { errorHandler } from "../utils/ErrorHandler";
|
||||
//This is only for backward compatibility because an early version of obsidian included an encoding to avoid fantom links from littering Obsidian graph view
|
||||
declare const PLUGIN_VERSION:string;
|
||||
export let EXCALIDRAW_PLUGIN: ExcalidrawPlugin = null;
|
||||
@@ -26,7 +26,7 @@ export const ERROR_IFRAME_CONVERSION_CANCELED = "iframe conversion canceled";
|
||||
|
||||
declare const excalidrawLib: typeof ExcalidrawLib;
|
||||
|
||||
export const LOCALE = moment.locale();
|
||||
export const LOCALE = localStorage.getItem("language")?.toLowerCase() || "en";
|
||||
export const CJK_FONTS = "CJK Fonts";
|
||||
|
||||
export const obsidianToExcalidrawMap: { [key: string]: string } = {
|
||||
@@ -79,14 +79,13 @@ export const obsidianToExcalidrawMap: { [key: string]: string } = {
|
||||
'ur': 'ur-PK', // Assuming Pakistan for Urdu
|
||||
'vi': 'vi-VN',
|
||||
'zh': 'zh-CN',
|
||||
'zh-TW': 'zh-TW',
|
||||
'zh-tw': 'zh-TW',
|
||||
};
|
||||
|
||||
|
||||
export let {
|
||||
sceneCoordsToViewportCoords,
|
||||
viewportCoordsToSceneCoords,
|
||||
determineFocusDistance,
|
||||
intersectElementWithLine,
|
||||
getCommonBoundingBox,
|
||||
getMaximumGroups,
|
||||
@@ -106,33 +105,63 @@ export let {
|
||||
getCSSFontDefinition,
|
||||
loadSceneFonts,
|
||||
loadMermaid,
|
||||
syncInvalidIndices,
|
||||
} = excalidrawLib;
|
||||
|
||||
export function updateExcalidrawLib() {
|
||||
({
|
||||
sceneCoordsToViewportCoords,
|
||||
viewportCoordsToSceneCoords,
|
||||
determineFocusDistance,
|
||||
intersectElementWithLine,
|
||||
getCommonBoundingBox,
|
||||
getMaximumGroups,
|
||||
measureText,
|
||||
getLineHeight,
|
||||
wrapText,
|
||||
getFontString,
|
||||
getBoundTextMaxWidth,
|
||||
exportToSvg,
|
||||
exportToBlob,
|
||||
mutateElement,
|
||||
restore,
|
||||
mermaidToExcalidraw,
|
||||
getFontFamilyString,
|
||||
getContainerElement,
|
||||
refreshTextDimensions,
|
||||
getCSSFontDefinition,
|
||||
loadSceneFonts,
|
||||
loadMermaid,
|
||||
} = excalidrawLib);
|
||||
try {
|
||||
// First validate that excalidrawLib exists and has the expected methods
|
||||
if (!excalidrawLib) {
|
||||
throw new Error("excalidrawLib is undefined");
|
||||
}
|
||||
|
||||
// Check that critical functions exist before assigning them
|
||||
const requiredFunctions = [
|
||||
'sceneCoordsToViewportCoords',
|
||||
'viewportCoordsToSceneCoords',
|
||||
'intersectElementWithLine',
|
||||
'getCommonBoundingBox',
|
||||
'measureText',
|
||||
'getLineHeight',
|
||||
'restore'
|
||||
];
|
||||
|
||||
for (const fnName of requiredFunctions) {
|
||||
if (!(fnName in excalidrawLib) || typeof excalidrawLib[fnName as keyof typeof excalidrawLib] !== 'function') {
|
||||
throw new Error(`Required function ${fnName} is missing from excalidrawLib`);
|
||||
}
|
||||
}
|
||||
|
||||
// If validation passes, update the exported functions
|
||||
({
|
||||
sceneCoordsToViewportCoords,
|
||||
viewportCoordsToSceneCoords,
|
||||
intersectElementWithLine,
|
||||
getCommonBoundingBox,
|
||||
getMaximumGroups,
|
||||
measureText,
|
||||
getLineHeight,
|
||||
wrapText,
|
||||
getFontString,
|
||||
getBoundTextMaxWidth,
|
||||
exportToSvg,
|
||||
exportToBlob,
|
||||
mutateElement,
|
||||
restore,
|
||||
mermaidToExcalidraw,
|
||||
getFontFamilyString,
|
||||
getContainerElement,
|
||||
refreshTextDimensions,
|
||||
getCSSFontDefinition,
|
||||
loadSceneFonts,
|
||||
loadMermaid,
|
||||
syncInvalidIndices,
|
||||
} = excalidrawLib);
|
||||
} catch (error) {
|
||||
errorHandler.handleError(error, "updateExcalidrawLib", true);
|
||||
// Don't throw here - we'll try to continue with potentially stale functions
|
||||
// but at least we won't crash
|
||||
}
|
||||
}
|
||||
|
||||
export const FONTS_STYLE_ID = "excalidraw-custom-fonts";
|
||||
@@ -230,8 +259,42 @@ export const FRONTMATTER_KEYS:{[key:string]: {name: string, type: string, depric
|
||||
"iframe-theme": {name: "excalidraw-iframe-theme", type: "text", depricated: true},
|
||||
"embeddable-theme": {name: "excalidraw-embeddable-theme", type: "text"},
|
||||
"open-as-markdown": {name: "excalidraw-open-md", type: "checkbox"},
|
||||
"embed-as-markdown": {name: "excalidraw-embed-md", type: "checkbox"},
|
||||
};
|
||||
|
||||
export const CaptureUpdateAction = {
|
||||
/**
|
||||
* Immediately undoable.
|
||||
*
|
||||
* Use for updates which should be captured.
|
||||
* Should be used for most of the local updates.
|
||||
*
|
||||
* These updates will _immediately_ make it to the local undo / redo stacks.
|
||||
*/
|
||||
IMMEDIATELY: "IMMEDIATELY",
|
||||
/**
|
||||
* Never undoable.
|
||||
*
|
||||
* Use for updates which should never be recorded, such as remote updates
|
||||
* or scene initialization.
|
||||
*
|
||||
* These updates will _never_ make it to the local undo / redo stacks.
|
||||
*/
|
||||
NEVER: "NEVER",
|
||||
/**
|
||||
* Eventually undoable.
|
||||
*
|
||||
* Use for updates which should not be captured immediately - likely
|
||||
* exceptions which are part of some async multi-step process. Otherwise, all
|
||||
* such updates would end up being captured with the next
|
||||
* `CaptureUpdateAction.IMMEDIATELY` - triggered either by the next `updateScene`
|
||||
* or internally by the editor.
|
||||
*
|
||||
* These updates will _eventually_ make it to the local undo / redo stacks.
|
||||
*/
|
||||
EVENTUALLY: "EVENTUALLY",
|
||||
} as const;
|
||||
|
||||
export const EMBEDDABLE_THEME_FRONTMATTER_VALUES = ["light", "dark", "auto", "dafault"];
|
||||
export const VIEW_TYPE_EXCALIDRAW = "excalidraw";
|
||||
export const VIEW_TYPE_EXCALIDRAW_LOADING = "excalidraw-loading";
|
||||
@@ -446,4 +509,4 @@ export const SCRIPTENGINE_ICON = `<g transform="translate(-8,-8)"><path d="M24.3
|
||||
export const DISK_ICON_NAME = "save";
|
||||
export const EXPORT_IMG_ICON = ` <g transform="scale(4.166)" strokeWidth="1.25" fill="none" stroke="currentColor"><path stroke="none" d="M0 0h24v24H0z" fill="none"></path><path d="M15 8h.01"></path><path d="M12 20h-5a3 3 0 0 1 -3 -3v-10a3 3 0 0 1 3 -3h10a3 3 0 0 1 3 3v5"></path><path d="M4 15l4 -4c.928 -.893 2.072 -.893 3 0l4 4"></path><path d="M14 14l1 -1c.617 -.593 1.328 -.793 2.009 -.598"></path><path d="M19 16v6"></path><path d="M22 19l-3 3l-3 -3"></path></g>`;
|
||||
export const EXPORT_IMG_ICON_NAME = `export-img`;
|
||||
export const EXCALIDRAW_ICON = `<path d="M24 17h121v121H24z" style="fill:none" transform="matrix(.8843 0 0 .83471 -21.223 -14.19)"/><path d="M119.81 105.98a.549.549 0 0 0-.53-.12c-4.19-6.19-9.52-12.06-14.68-17.73l-.85-.93c0-.11-.05-.21-.12-.3a.548.548 0 0 0-.34-.2l-.17-.18-.12-.09c-.15-.32-.53-.56-.95-.35-1.58.81-3 1.97-4.4 3.04-1.87 1.43-3.7 2.92-5.42 4.52-.7.65-1.39 1.33-1.97 2.09-.28.37-.07.72.27.87-1.22 1.2-2.45 2.45-3.68 3.74-.11.12-.17.28-.16.44.01.16.09.31.22.41l2.16 1.65s.01.03.03.04c3.09 3.05 8.51 7.28 14.25 11.76.85.67 1.71 1.34 2.57 2.01.39.47.76.94 1.12 1.4.19.25.55.3.8.11.13.1.26.21.39.31a.57.57 0 0 0 .8-.1c.07-.09.1-.2.11-.31.04 0 .07.03.1.03.15 0 .31-.06.42-.18l10.18-11.12a.56.56 0 0 0-.04-.8l.01-.01Zm-29.23-3.85c.07.09.14.17.21.25 1.16.98 2.4 2.04 3.66 3.12l-5.12-3.91s-.32-.22-.52-.36c-.11-.08-.21-.16-.31-.24l-.38-.32s.07-.07.1-.11l.35-.35c1.72-1.74 4.67-4.64 6.19-6.06-1.61 1.62-4.87 6.37-4.17 7.98h-.01Zm17.53 13.81-4.22-3.22c-1.65-1.71-3.43-3.4-5.24-5.03 2.28 1.76 4.23 3.25 4.52 3.51 2.21 1.97 2.11 1.61 3.63 2.91l1.83 1.33c-.18.16-.36.33-.53.49l.01.01Zm1.06.81-.08-.06c.16-.13.33-.25.49-.38l-.4.44h-.01Zm-66.93-65.3c.14.72.27 1.43.4 2.11.69 3.7 1.33 7.03 2.55 9.56l.48 1.92c.19.73.46 1.64.71 1.83 2.85 2.52 7.22 6.28 11.89 9.82.21.16.5.15.7-.01.01.02.03.03.04.04.11.1.24.15.38.15.16 0 .31-.06.42-.19 5.98-6.65 10.43-12.12 13.6-16.7.2-.25.3-.54.29-.84.2-.24.41-.48.6-.68a.558.558 0 0 0-.1-.86.578.578 0 0 0-.17-.36c-1.39-1.34-2.42-2.31-3.46-3.28-1.84-1.72-3.74-3.5-7.77-7.51-.02-.02-.05-.04-.07-.06a.555.555 0 0 0-.22-.14c-1.11-.39-3.39-.78-6.26-1.28-4.22-.72-10-1.72-15.2-3.27h-.04v-.01s-.02 0-.03.02h-.01l.04-.02s-.31.01-.37.04c-.08.04-.14.09-.19.15-.05.06-.09.12-.47.2-.38.08.08 0 .11 0h-.11v.03c.07.34.05.58.16.97-.02.1.21 1.02.24 1.11l1.83 7.26h.03Zm30.95 6.54s-.03.04-.04.05l-.64-.71c.22.21.44.42.68.66Zm-7.09 9.39s-.07.08-.1.12l-.02-.02c.04-.03.08-.07.13-.1h-.01Zm-7.07 8.47Zm3.02-28.57c.35.35 1.74 1.65 2.06 1.97-1.45-.66-5.06-2.34-6.74-2.88 1.65.29 3.93.66 4.68.91Zm-19.18-2.77c.84 1.44 1.5 6.49 2.16 11.4-.37-1.58-.69-3.12-.99-4.6-.52-2.56-1-4.85-1.67-6.88.14.01.31.03.49.05 0 .01 0 .02.02.03h-.01Zm-.29-1.21c-.23-.02-.44-.04-.62-.05-.02-.04-.03-.08-.04-.12l.66.18v-.01Zm-2.22.45v-.02.02Zm78.54-1.18c.04-.23-1.1-1.24-.74-1.26.85-.04.86-1.35 0-1.31-1.13.06-2.27.32-3.37.53-1.98.37-3.95.78-5.92 1.21-4.39.94-8.77 1.93-13.1 3.11-1.36.37-2.86.7-4.11 1.36-.42.22-.4.67-.17.95-.09.05-.18.08-.28.09-.37.07-.74.13-1.11.19a.566.566 0 0 0-.39.86c-2.32 3.1-4.96 6.44-7.82 9.95-2.81 3.21-5.73 6.63-8.72 10.14-9.41 11.06-20.08 23.6-31.9 34.64-.23.21-.24.57-.03.8.05.06.12.1.19.13-.16.15-.32.3-.48.44-.1.09-.14.2-.16.32-.08.08-.16.17-.23.25-.21.23-.2.59.03.8.23.21.59.2.8-.03.04-.04.08-.09.12-.13a.84.84 0 0 1 1.22 0c.69.74 1.34 1.44 1.95 2.09l-1.38-1.15a.57.57 0 0 0-.8.07c-.2.24-.17.6.07.8l14.82 12.43c.11.09.24.13.37.13.15 0 .29-.06.4-.17l.36-.36a.56.56 0 0 0 .63-.12c20.09-20.18 36.27-35.43 54.8-49.06.17-.12.25-.32.23-.51a.57.57 0 0 0 .48-.39c3.42-10.46 4.08-19.72 4.28-24.27 0-.03.01-.05.02-.07.02-.05.03-.1.04-.14.03-.11.05-.19.05-.19.26-.78.17-1.53-.15-2.15v.02ZM82.98 58.94c.9-1.03 1.79-2.04 2.67-3.02-5.76 7.58-15.3 19.26-28.81 33.14 9.2-10.18 18.47-20.73 26.14-30.12Zm-32.55 52.81-.03-.03c.11.02.19.04.2.04a.47.47 0 0 0-.17 0v-.01Zm6.9 6.42-.05-.04.03-.03c.02 0 .03.02.04.02 0 .02-.02.03-.03.05h.01Zm8.36-7.21 1.38-1.44c.01.01.02.03.03.05-.47.46-.94.93-1.42 1.39h.01Zm2.24-2.21c.26-.3.56-.65.87-1.02.01-.01.02-.03.04-.04 3.29-3.39 6.68-6.82 10.18-10.25.02-.02.05-.04.07-.06.86-.66 1.82-1.39 2.72-2.08-4.52 4.32-9.11 8.78-13.88 13.46v-.01Zm21.65-55.88c-1.86 2.42-3.9 5.56-5.63 8.07-5.46 7.91-23.04 27.28-23.43 27.65-2.71 2.62-10.88 10.46-16.09 15.37-.14.13-.25.24-.34.35a.794.794 0 0 1 .03-1.13c24.82-23.4 39.88-42.89 46-51.38-.13.33-.24.69-.55 1.09l.01-.02Zm16.51 7.1-.01.02c0-.02-.02-.07.01-.02Zm-.91-5.13Zm-5.89 9.45c-2.26-1.31-3.32-3.27-2.71-5.25l.19-.66c.08-.19.17-.38.28-.57.59-.98 1.49-1.85 2.52-2.36.05-.02.1-.03.15-.04a.795.795 0 0 1-.04-.43c.05-.31.25-.58.66-.58.67 0 2.75.62 3.54 1.3.24.19.47.4.68.63.3.35.74.92.96 1.33.13.06.23.62.38.91.14.46.2.93.18 1.4 0 .02 0 .02.01.03-.03.07 0 .37-.04.4-.1.72-.36 1.43-.75 2.05-.04.05-.07.11-.11.16 0 .01-.02.02-.03.04-.3.43-.65.83-1.08 1.13-1.26.89-2.73 1.16-4.2.79a6.33 6.33 0 0 1-.57-.25l-.02-.03Zm16.27-1.63c-.49 2.05-1.09 4.19-1.8 6.38-.03.08-.03.16-.03.23-.1.01-.19.05-.27.11-4.44 3.26-8.73 6.62-12.98 10.11 3.67-3.32 7.39-6.62 11.23-9.95a6.409 6.409 0 0 0 2.11-3.74l.56-3.37.03-.1c.25-.71 1.34-.4 1.17.33h-.02Z" style="fill:currentColor;fill-rule:nonzero" transform="translate(-26.41 -29.49)"/>`;
|
||||
export const EXCALIDRAW_ICON = `<path d="M24 17h121v121H24z" style="fill:none" transform="matrix(.8843 0 0 .83471 -21.223 -14.19)"/><path d="M119.81 105.98a.549.549 0 0 0-.53-.12c-4.19-6.19-9.52-12.06-14.68-17.73l-.85-.93c0-.11-.05-.21-.12-.3a.548.548 0 0 0-.34-.2l-.17-.18-.12-.09c-.15-.32-.53-.56-.95-.35-1.58.81-3 1.97-4.4 3.04-1.87 1.43-3.7 2.92-5.42 4.52-.7.65-1.39 1.33-1.97 2.09-.28.37-.07.72.27.87-1.22 1.2-2.45 2.45-3.68 3.74-.11.12-.17.28-.16.44.01.16.09.31.22.41l2.16 1.65s.01.03.03.04c3.09 3.05 8.51 7.28 14.25 11.76.85.67 1.71 1.34 2.57 2.01.39.47.76.94 1.12 1.4.19.25.55.3.8.11.13.1.26.21.39.31a.57.57 0 0 0 .8-.1c.07-.09.1-.2.11-.31.04 0 .07.03.1.03.15 0 .31-.06.42-.18l10.18-11.12a.56.56 0 0 0-.04-.8l.01-.01Zm-29.23-3.85c.07.09.14.17.21.25 1.16.98 2.4 2.04 3.66 3.12l-5.12-3.91s-.32-.22-.52-.36c-.11-.08-.21-.16-.31-.24l-.38-.32s.07-.07.1-.11l.35-.35c1.72-1.74 4.67-4.64 6.19-6.06-1.61 1.62-4.87 6.37-4.17 7.98h-.01Zm17.53 13.81-4.22-3.22c-1.65-1.71-3.43-3.4-5.24-5.03 2.28 1.76 4.23 3.25 4.52 3.51 2.21 1.97 2.11 1.61 3.63 2.91l1.83 1.33c-.18.16-.36.33-.53.49l.01.01Zm1.06.81-.08-.06c.16-.13.33-.25.49-.38l-.4.44h-.01Zm-66.93-65.3c.14.72.27 1.43.4 2.11.69 3.7 1.33 7.03 2.55 9.56l.48 1.92c.19.73.46 1.64.71 1.83 2.85 2.52 7.22 6.28 11.89 9.82.21.16.5.15.7-.01.01.02.03.03.04.04.11.1.24.15.38.15.16 0 .31-.06.42-.19 5.98-6.65 10.43-12.12 13.6-16.7.2-.25.3-.54.29-.84.2-.24.41-.48.6-.68a.558.558 0 0 0-.1-.86.578.578 0 0 0-.17-.36c-1.39-1.34-2.42-2.31-3.46-3.28-1.84-1.72-3.74-3.5-7.77-7.51-.02-.02-.05-.04-.07-.06a.555.555 0 0 0-.22-.14c-1.11-.39-3.39-.78-6.26-1.28-4.22-.72-10-1.72-15.2-3.27h-.04v-.01s-.02 0-.03.02h-.01l.04-.02s-.31.01-.37.04c-.08.04-.14.09-.19.15-.05.06-.09.12-.47.2-.38.08.08 0 .11 0h-.11v.03c.07.34.05.58.16.97-.02.1.21 1.02.24 1.11l1.83 7.26h.03Zm30.95 6.54s-.03.04-.04.05l-.64-.71c.22.21.44.42.68.66Zm-7.09 9.39s-.07.08-.1.12l-.02-.02c.04-.03.08-.07.13-.1h-.01Zm-7.07 8.47Zm3.02-28.57c.35.35 1.74 1.65 2.06 1.97-1.45-.66-5.06-2.34-6.74-2.88 1.65.29 3.93.66 4.68.91Zm-19.18-2.77c.84 1.44 1.5 6.49 2.16 11.4-.37-1.58-.69-3.12-.99-4.6-.52-2.56-1-4.85-1.67-6.88.14.01.31.03.49.05 0 .01 0 .02.02.03h-.01Zm-.29-1.21c-.23-.02-.44-.04-.62-.05-.02-.04-.03-.08-.04-.12l.66.18v-.01Zm-2.22.45v-.02.02Zm78.54-1.18c.04-.23-1.1-1.24-.74-1.26.85-.04.86-1.35 0-1.31-1.13.06-2.27.32-3.37.53-1.98.37-3.95.78-5.92 1.21-4.39.94-8.77 1.93-13.1 3.11-1.36.37-2.86.7-4.11 1.36-.42.22-.4.67-.17.95-.09.05-.18.08-.28.09-.37.07-.74.13-1.11.19a.566.566 0 0 0-.39.86c-2.32 3.1-4.96 6.44-7.82 9.95-2.81 3.21-5.73 6.63-8.72 10.14-9.41 11.06-20.08 23.6-31.9 34.64-.23.21-.24.57-.03.8.05.06.12.1.19.13-.16.15-.32.3-.48.44-.1.09-.14.2-.16.32-.08.08-.16.17-.23.25-.21.23-.2.59.03.8.23.21.59.2.8-.03.04-.04.08-.09.12-.13a.84.84 0 0 1 1.22 0c.69.74 1.34 1.44 1.95 2.09l-1.38-1.15a.57.57 0 0 0-.8.07c-.2.24-.17.6.07.8l14.82 12.43c.11.09.24.13.37.13.15 0 .29-.06.4-.17l.36-.36a.56.56 0 0 0 .63-.12c20.09-20.18 36.27-35.43 54.8-49.06.17-.12.25-.32.23-.51a.57.57 0 0 0 .48-.39c3.42-10.46 4.08-19.72 4.28-24.27 0-.03.01-.05.02-.07.02-.05.03-.1.04-.14.03-.11.05-.19.05-.19.26-.78.17-1.53-.15-2.15v.02ZM82.98 58.94c.9-1.03 1.79-2.04 2.67-3.02-5.76 7.58-15.3 19.26-28.81 33.14 9.2-10.18 18.47-20.73 26.14-30.12Zm-32.55 52.81-.03-.03c.11.02.19.04.2.04a.47.47 0 0 0-.17 0v-.01Zm6.9 6.42-.05-.04.03-.03c.02 0 .03.02.04.02 0 .02-.02.03-.03.05h.01Zm8.36-7.21 1.38-1.44c.01.01.02.03.03.05-.47.46-.94.93-1.42 1.39h.01Zm2.24-2.21c.26-.3.56-.65.87-1.02.01-.01.02-.03.04-.04 3.29-3.39 6.68-6.82 10.18-10.25.02-.02.05-.04.07-.06.86-.66 1.82-1.39 2.72-2.08-4.52 4.32-9.11 8.78-13.88 13.46v-.01Zm21.65-55.88c-1.86 2.42-3.9 5.56-5.63 8.07-5.46 7.91-23.04 27.28-23.43 27.65-2.71 2.62-10.88 10.46-16.09 15.37-.14.13-.25.24-.34.35a.794.794 0 0 1 .03-1.13c24.82-23.4 39.88-42.89 46-51.38-.13.33-.24.69-.55 1.09l.01-.02Zm16.51 7.1-.01.02c0-.02-.02-.07.01-.02Zm-.91-5.13Zm-5.89 9.45c-2.26-1.31-3.32-3.27-2.71-5.25l.19-.66c.08-.19.17-.38.28-.57.59-.98 1.49-1.85 2.52-2.36.05-.02.1-.03.15-.04a.795.795 0 0 1-.04-.43c.05-.31.25-.58.66-.58.67 0 2.75.62 3.54 1.3.24.19.47.4.68.63.3.35.74.92.96 1.33.13.06.23.62.38.91.14.46.2.93.18 1.4 0 .02 0 .02.01.03-.03.07 0 .37-.04.4-.1.72-.36 1.43-.75 2.05-.04.05-.07.11-.11.16 0 .01-.02.02-.03.04-.3.43-.65.83-1.08 1.13-1.26.89-2.73 1.16-4.2.79a6.33 6.33 0 0 1-.57-.25l-.02-.03Zm16.27-1.63c-.49 2.05-1.09 4.19-1.8 6.38-.03.08-.03.16-.03.23-.1.01-.19.05-.27.11-4.44 3.26-8.73 6.62-12.98 10.11 3.67-3.32 7.39-6.62 11.23-9.95a6.409 6.409 0 0 0 2.11-3.74l.56-3.37.03-.1c.25-.71 1.34-.4 1.17.33h-.02Z" style="fill:currentColor;fill-rule:nonzero" transform="translate(-26.41 -29.49)"/>`;
|
||||
|
||||
@@ -2,7 +2,7 @@ import "obsidian";
|
||||
//import { ExcalidrawAutomate } from "./ExcalidrawAutomate";
|
||||
//export ExcalidrawAutomate from "./ExcalidrawAutomate";
|
||||
//export {ExcalidrawAutomate} from "./ExcaildrawAutomate";
|
||||
export type { ExcalidrawBindableElement, ExcalidrawElement, FileId, FillStyle, StrokeRoundness, StrokeStyle } from "@zsviczian/excalidraw/types/excalidraw/element/types";
|
||||
export type { ExcalidrawBindableElement, ExcalidrawElement, FileId, FillStyle, StrokeRoundness, StrokeStyle } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
export type { Point } from "src/types/types";
|
||||
export const getEA = (view?:any): any => {
|
||||
try {
|
||||
|
||||
@@ -44,7 +44,7 @@ import { initExcalidrawAutomate } from "src/utils/excalidrawAutomateUtils";
|
||||
import { around, dedupe } from "monkey-around";
|
||||
import { t } from "../lang/helpers";
|
||||
import {
|
||||
checkAndCreateFolder,
|
||||
createOrOverwriteFile,
|
||||
fileShouldDefaultAsExcalidraw,
|
||||
getDrawingFilename,
|
||||
getIMGFilename,
|
||||
@@ -61,7 +61,7 @@ import {
|
||||
getFontMetrics,
|
||||
} from "../utils/utils";
|
||||
import { foldExcalidrawSection, getExcalidrawViews, setExcalidrawView } from "../utils/obsidianUtils";
|
||||
import { FileId } from "@zsviczian/excalidraw/types/excalidraw/element/types";
|
||||
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ScriptEngine } from "../shared/Scripts";
|
||||
import { hoverEvent, initializeMarkdownPostProcessor, markdownPostProcessor, legacyExcalidrawPopoverObserver } from "./managers/MarkdownPostProcessor";
|
||||
import { FieldSuggester } from "../shared/Suggesters/FieldSuggester";
|
||||
@@ -412,7 +412,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
|
||||
try {
|
||||
this.isReady = true;
|
||||
switchToExcalidraw(this.app);
|
||||
await switchToExcalidraw(this.app);
|
||||
this.switchToExcalidarwAfterLoad();
|
||||
} catch (e) {
|
||||
new Notice("Error switching views to Excalidraw", 6000);
|
||||
@@ -566,7 +566,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
}
|
||||
}
|
||||
this.packageManager.getPackageMap().forEach(({excalidrawLib}) => {
|
||||
(excalidrawLib as typeof ExcalidrawLib).registerLocalFont({metrics: fontMetrics as any, icon: null}, fourthFontDataURL);
|
||||
(excalidrawLib as typeof ExcalidrawLib).registerLocalFont({metrics: fontMetrics as any}, fourthFontDataURL);
|
||||
});
|
||||
// Add fonts to open Obsidian documents
|
||||
for(const ownerDocument of this.getOpenObsidianDocuments()) {
|
||||
@@ -738,13 +738,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
if (!data || data.startsWith("404: Not Found")) {
|
||||
return null;
|
||||
}
|
||||
if (file) {
|
||||
await this.app.vault.modify(file as TFile, data);
|
||||
} else {
|
||||
await checkAndCreateFolder(folder);
|
||||
file = await this.app.vault.create(localPath, data);
|
||||
}
|
||||
return file;
|
||||
return await createOrOverwriteFile(this.app, file?.path ?? localPath, data);
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -894,7 +888,8 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
normalizePath(file.path.substring(0, file.path.lastIndexOf(file.name))),
|
||||
);
|
||||
log(fname);
|
||||
const result = await this.app.vault.create(
|
||||
const result = await createOrOverwriteFile(
|
||||
this.app,
|
||||
fname,
|
||||
FRONTMATTER + (await this.fileManager.exportSceneToMD(data, false)),
|
||||
);
|
||||
@@ -1078,6 +1073,10 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.eventManager.onActiveLeafChangeHandler(leaf);
|
||||
}
|
||||
|
||||
public setDebounceActiveLeafChangeHandler() {
|
||||
this.eventManager.setDebounceActiveLeafChangeHandler();
|
||||
}
|
||||
|
||||
public registerHotkeyOverrides() {
|
||||
//this is repeated here because the same function is called when settings is closed after hotkeys have changed
|
||||
if (this.popScope) {
|
||||
|
||||
@@ -34,6 +34,7 @@ import { insertLaTeXToView, search } from "src/utils/excalidrawAutomateUtils";
|
||||
import { templatePromt } from "../../shared/Dialogs/Prompt";
|
||||
import { t } from "../../lang/helpers";
|
||||
import {
|
||||
createOrOverwriteFile,
|
||||
getAliasWithSize,
|
||||
getAnnotationFileNameAndFolder,
|
||||
getCropFileNameAndFolder,
|
||||
@@ -51,7 +52,7 @@ import {
|
||||
getImageSize,
|
||||
} from "../../utils/utils";
|
||||
import { extractSVGPNGFileName, getActivePDFPageNumberFromPDFView, getAttachmentsFolderAndFilePath, isObsidianThemeDark, mergeMarkdownFiles, setExcalidrawView } from "../../utils/obsidianUtils";
|
||||
import { ExcalidrawElement, ExcalidrawEmbeddableElement, ExcalidrawImageElement, ExcalidrawTextElement, FileId } from "@zsviczian/excalidraw/types/excalidraw/element/types";
|
||||
import { ExcalidrawElement, ExcalidrawEmbeddableElement, ExcalidrawImageElement, ExcalidrawTextElement, FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ReleaseNotes } from "../../shared/Dialogs/ReleaseNotes";
|
||||
import { ScriptInstallPrompt } from "../../shared/Dialogs/ScriptInstallPrompt";
|
||||
import Taskbone from "../../shared/OCR/Taskbone";
|
||||
@@ -64,12 +65,11 @@ import { EmbeddableSettings } from "../../shared/Dialogs/EmbeddableSettings";
|
||||
import { processLinkText } from "../../utils/customEmbeddableUtils";
|
||||
import { getEA } from "src/core";
|
||||
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { carveOutImage, carveOutPDF, createImageCropperFile } from "../../utils/carveout";
|
||||
import { showFrameSettings } from "../../shared/Dialogs/FrameSettings";
|
||||
import { insertImageToView } from "../../utils/excalidrawViewUtils";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { get } from "http";
|
||||
|
||||
declare const PLUGIN_VERSION:string;
|
||||
|
||||
@@ -166,6 +166,7 @@ export class CommandManager {
|
||||
const fileMenuHandlerCreateNew = (menu: Menu, file: TFile) => {
|
||||
menu.addItem((item: MenuItem) => {
|
||||
item
|
||||
.setSection('action-primary')
|
||||
.setTitle(t("CREATE_NEW"))
|
||||
.setIcon(ICON_NAME)
|
||||
.onClick((e) => {createNewAction(e, file)});
|
||||
@@ -257,7 +258,7 @@ export class CommandManager {
|
||||
new Notice("The compressed string is corrupted. Unable to decompress data.");
|
||||
return;
|
||||
}
|
||||
await this.app.vault.modify(activeFile,header + decompressed + "\n```\n%%" + compressed[1]);
|
||||
await createOrOverwriteFile(this.app, activeFile.path,header + decompressed + "\n```\n%%" + compressed[1]);
|
||||
})();
|
||||
|
||||
}
|
||||
@@ -354,7 +355,16 @@ export class CommandManager {
|
||||
if(excalidrawFname.endsWith(".light.md")) {
|
||||
excalidrawFile = this.app.metadataCache.getFirstLinkpathDest(excalidrawFname.replace(/\.light\.md$/,".md"), view.file.path);
|
||||
}
|
||||
if(!excalidrawFile) return false;
|
||||
//handles the case if the png or svg is not in the same folder as the excalidraw file
|
||||
if(!excalidrawFile) {
|
||||
const basename = imgFile.basename.replace(/(?:\.dark|\.light)$/,"");
|
||||
const candidates = this.app.vault.getMarkdownFiles().filter(f=>f.basename === basename);
|
||||
if(candidates.length === 1) {
|
||||
excalidrawFile = candidates[0];
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(checking) return true;
|
||||
this.plugin.openDrawing(excalidrawFile, "new-tab", true);
|
||||
@@ -756,7 +766,6 @@ export class CommandManager {
|
||||
if (view) {
|
||||
if(!view.exportDialog) {
|
||||
view.exportDialog = new ExportDialog(this.plugin, view,view.file);
|
||||
view.exportDialog.createForm();
|
||||
}
|
||||
view.exportDialog.open();
|
||||
return true;
|
||||
@@ -1038,8 +1047,13 @@ export class CommandManager {
|
||||
x:Math.max(0,centerX - width/2 + view.ownerWindow.screenX),
|
||||
y:Math.max(0,centerY - height/2 + view.ownerWindow.screenY),
|
||||
}
|
||||
|
||||
const focusOnFileTab = this.settings.focusOnFileTab;
|
||||
//override focusOnFileTab for popout windows
|
||||
if(DEVICE.isDesktop) {
|
||||
this.settings.focusOnFileTab = false;
|
||||
}
|
||||
this.plugin.openDrawing(ef.file, DEVICE.isMobile ? "new-tab":"popout-window", true, undefined, false, {x,y,width,height});
|
||||
this.settings.focusOnFileTab = focusOnFileTab;
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1818,10 +1832,7 @@ export class CommandManager {
|
||||
const template = await this.plugin.getBlankDrawing();
|
||||
const target = await this.app.vault.read(activeFile);
|
||||
const mergedTarget = mergeMarkdownFiles(template, target);
|
||||
await this.app.vault.modify(
|
||||
activeFile,
|
||||
mergedTarget,
|
||||
);
|
||||
await createOrOverwriteFile(this.app, activeFile.path, mergedTarget);
|
||||
setExcalidrawView(activeView.leaf);
|
||||
})();
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { WorkspaceLeaf, TFile, Editor, MarkdownView, MarkdownFileInfo, MetadataCache, App, EventRef, Menu, FileView } from "obsidian";
|
||||
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/excalidraw/element/types";
|
||||
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { getLink } from "../../utils/fileUtils";
|
||||
import { editorInsertText, getExcalidrawViews, getParentOfClass, setExcalidrawView } from "../../utils/obsidianUtils";
|
||||
import { editorInsertText, getExcalidrawViews, getParentOfClass, isUnwantedLeaf, setExcalidrawView } from "../../utils/obsidianUtils";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { DEBUGGING, debug } from "src/utils/debugHelper";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
@@ -21,6 +21,7 @@ export class EventManager {
|
||||
private removeEventLisnters:(()=>void)[] = []; //only used if I register an event directly, not via Obsidian's registerEvent
|
||||
private previouslyActiveLeaf: WorkspaceLeaf;
|
||||
private splitViewLeafSwitchTimestamp: number = 0;
|
||||
private debunceActiveLeafChangeHandlerTimer: number|null = null;
|
||||
|
||||
get settings() {
|
||||
return this.plugin.settings;
|
||||
@@ -103,6 +104,15 @@ export class EventManager {
|
||||
this.plugin.registerEvent(this.plugin.app.workspace.on("editor-menu", this.onEditorMenuHandler.bind(this)));
|
||||
}
|
||||
|
||||
public setDebounceActiveLeafChangeHandler() {
|
||||
if(this.debunceActiveLeafChangeHandlerTimer) {
|
||||
window.clearTimeout(this.debunceActiveLeafChangeHandlerTimer);
|
||||
}
|
||||
this.debunceActiveLeafChangeHandlerTimer = window.setTimeout(() => {
|
||||
this.debunceActiveLeafChangeHandlerTimer = null;
|
||||
}, 50);
|
||||
}
|
||||
|
||||
private onLayoutChangeHandler() {
|
||||
getExcalidrawViews(this.app).forEach(excalidrawView=>excalidrawView.refresh());
|
||||
}
|
||||
@@ -164,6 +174,17 @@ export class EventManager {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.onActiveLeafChangeHandler,`onActiveLeafChangeEventHandler`, leaf);
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/723
|
||||
|
||||
if(this.debunceActiveLeafChangeHandlerTimer) {
|
||||
return;
|
||||
}
|
||||
|
||||
//In Obsidian 1.8.x the active excalidraw leaf is obscured by an empty leaf without a parent
|
||||
//This hack resolves it
|
||||
if(this.app.workspace.activeLeaf === leaf && isUnwantedLeaf(leaf)) {
|
||||
leaf.detach();
|
||||
return;
|
||||
}
|
||||
|
||||
if (leaf.view && leaf.view.getViewType() === "pdf") {
|
||||
this.plugin.lastPDFLeafID = leaf.id;
|
||||
}
|
||||
|
||||
@@ -6,10 +6,11 @@ import { changeThemeOfExcalidrawMD, ExcalidrawData, getMarkdownDrawingSection }
|
||||
import ExcalidrawView, { getTextMode } from "src/view/ExcalidrawView";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { DEBUGGING } from "src/utils/debugHelper";
|
||||
import { checkAndCreateFolder, download, getIMGFilename, getLink, getListOfTemplateFiles, getNewUniqueFilepath } from "src/utils/fileUtils";
|
||||
import { checkAndCreateFolder, createFileAndAwaitMetacacheUpdate, download, getIMGFilename, getLink, getListOfTemplateFiles, getNewUniqueFilepath } from "src/utils/fileUtils";
|
||||
import { PaneTarget } from "src/utils/modifierkeyHelper";
|
||||
import { getExcalidrawViews, getNewOrAdjacentLeaf, isObsidianThemeDark, openLeaf } from "src/utils/obsidianUtils";
|
||||
import { errorlog, getExportTheme } from "src/utils/utils";
|
||||
import { imageCache } from "src/shared/ImageCache";
|
||||
|
||||
export class PluginFileManager {
|
||||
private plugin: ExcalidrawPlugin;
|
||||
@@ -172,28 +173,71 @@ export class PluginFileManager {
|
||||
? ""
|
||||
: theme + ".";
|
||||
|
||||
const imageRelativePath = getIMGFilename(
|
||||
excalidrawRelativePath,
|
||||
theme+this.settings.embedType.toLowerCase(),
|
||||
);
|
||||
const imageFullpath = getIMGFilename(
|
||||
const exportExtension = theme+this.settings.embedType.toLowerCase();
|
||||
let imageFullpath = getIMGFilename(
|
||||
file.path,
|
||||
theme+this.settings.embedType.toLowerCase(),
|
||||
exportExtension,
|
||||
);
|
||||
|
||||
if(this.plugin.ea?.onImageExportPathHook) {
|
||||
try {
|
||||
imageFullpath = this.plugin.ea.onImageExportPathHook({
|
||||
exportFilepath: imageFullpath,
|
||||
exportExtension,
|
||||
excalidrawFile: file,
|
||||
action: "export",
|
||||
}) ?? imageFullpath;
|
||||
} catch (e) {
|
||||
errorlog({where: "FileManager.embedDrawing", fn: this.plugin.ea.onImageExportPathHook, error: e});
|
||||
}
|
||||
}
|
||||
|
||||
const createFile = async (path: string):Promise<TFile> => {
|
||||
return await createFileAndAwaitMetacacheUpdate(this.app, path,
|
||||
this.settings.embedType === "SVG"
|
||||
? `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="0" height="0"></svg>`
|
||||
: new Uint8Array([
|
||||
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG signature
|
||||
0x00, 0x00, 0x00, 0x0D, // IHDR chunk length
|
||||
0x49, 0x48, 0x44, 0x52, // IHDR
|
||||
0x00, 0x00, 0x00, 0x01, // width: 1
|
||||
0x00, 0x00, 0x00, 0x01, // height: 1
|
||||
0x08, 0x06, 0x00, 0x00, 0x00, // bit depth: 8, color type: 6 (RGBA), compression: 0, filter: 0, interlace: 0
|
||||
0x1F, 0x15, 0xC4, 0x89, // IHDR CRC
|
||||
0x00, 0x00, 0x00, 0x0B, // IDAT chunk length
|
||||
0x49, 0x44, 0x41, 0x54, // IDAT
|
||||
0x78, 0x9C, 0x62, 0x00, 0x02, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, // compressed data (1x1 transparent pixel)
|
||||
0x0A, 0x2D, 0xB4, // IDAT CRC
|
||||
0x00, 0x00, 0x00, 0x00, // IEND chunk length
|
||||
0x49, 0x45, 0x4E, 0x44, // IEND
|
||||
0xAE, 0x42, 0x60, 0x82 // IEND CRC
|
||||
]).buffer
|
||||
);
|
||||
}
|
||||
|
||||
let imgFile = this.app.vault.getFileByPath(imageFullpath);
|
||||
if (!imgFile) {
|
||||
imgFile = await createFile(imageFullpath);
|
||||
}
|
||||
|
||||
const imageRelativePath = this.app.metadataCache.fileToLinktext(
|
||||
imgFile,
|
||||
activeView.file.path,
|
||||
false,
|
||||
);
|
||||
|
||||
//will hold incorrect value if theme==="", however in that case it won't be used
|
||||
const otherTheme = theme === "dark." ? "light." : "dark.";
|
||||
const otherImageRelativePath = theme === ""
|
||||
//if the hook tinkers with the extension, then I cannot predict the other theme's extension
|
||||
//it would become a messy heuristic to try to guess the other theme's extension
|
||||
const otherImageRelativePath = ((theme === "") || !imageRelativePath.endsWith(exportExtension))
|
||||
? null
|
||||
: getIMGFilename(
|
||||
excalidrawRelativePath,
|
||||
otherTheme+this.settings.embedType.toLowerCase(),
|
||||
);
|
||||
: (imageRelativePath.substring(0, imageRelativePath.lastIndexOf(exportExtension)) + otherTheme+this.settings.embedType.toLowerCase());
|
||||
|
||||
const imgFile = this.app.vault.getAbstractFileByPath(imageFullpath);
|
||||
if (!imgFile) {
|
||||
await this.app.vault.create(imageFullpath, "");
|
||||
await sleep(200); //wait for metadata cache to update
|
||||
if(otherImageRelativePath) {
|
||||
await createFile(
|
||||
imgFile.path.substring(0, imgFile.path.lastIndexOf(exportExtension)) + otherTheme+this.settings.embedType.toLowerCase()
|
||||
);
|
||||
}
|
||||
|
||||
const inclCom = this.settings.embedMarkdownCommentLinks;
|
||||
@@ -367,17 +411,43 @@ export class PluginFileManager {
|
||||
if (!this.isExcalidrawFile(file)) {
|
||||
return;
|
||||
}
|
||||
this.moveBAKFile(oldPath, file.path);
|
||||
|
||||
if (!this.settings.keepInSync) {
|
||||
return;
|
||||
}
|
||||
[EXPORT_TYPES, "excalidraw"].flat().forEach(async (ext: string) => {
|
||||
const oldIMGpath = getIMGFilename(oldPath, ext);
|
||||
const imgFile = this.app.vault.getAbstractFileByPath(
|
||||
normalizePath(oldIMGpath),
|
||||
const imgMap = new Map<string, {oldImgPath: string, newImgPath: string}>();
|
||||
[EXPORT_TYPES, "excalidraw"].flat().forEach(ext => {
|
||||
let oldImgPath = getIMGFilename(oldPath, ext);
|
||||
let newImgPath = getIMGFilename(file.path, ext);
|
||||
if(this.plugin.ea?.onImageExportPathHook) {
|
||||
try {
|
||||
oldImgPath = this.plugin.ea.onImageExportPathHook({
|
||||
exportFilepath: oldImgPath,
|
||||
exportExtension: ext,
|
||||
excalidrawFile: file,
|
||||
oldExcalidrawPath: oldPath,
|
||||
action: "move",
|
||||
}) ?? oldImgPath;
|
||||
newImgPath = this.plugin.ea.onImageExportPathHook({
|
||||
exportFilepath: newImgPath,
|
||||
exportExtension: ext,
|
||||
excalidrawFile: file,
|
||||
action: "export",
|
||||
}) ?? newImgPath;
|
||||
} catch (e) {
|
||||
errorlog({where: "FileManager.renameEventHandler", fn: this.plugin.ea.onImageExportPathHook, error: e});
|
||||
}
|
||||
}
|
||||
imgMap.set(ext, { oldImgPath, newImgPath });
|
||||
});
|
||||
|
||||
imgMap.forEach((path, ext) => {
|
||||
const imgFile = this.app.vault.getFileByPath(
|
||||
normalizePath(path.oldImgPath),
|
||||
);
|
||||
if (imgFile && imgFile instanceof TFile) {
|
||||
const newIMGpath = getIMGFilename(file.path, ext);
|
||||
await this.app.fileManager.renameFile(imgFile, newIMGpath);
|
||||
if (imgFile) {
|
||||
this.app.fileManager.renameFile(imgFile, normalizePath(path.newImgPath));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -453,6 +523,34 @@ export class PluginFileManager {
|
||||
});
|
||||
}
|
||||
|
||||
private async removeBAKFromCache(path: string) {
|
||||
//this will not work in a short period when Obsidian is starting up, however
|
||||
//because there is housekeeping in ImageCache at each startup to delete
|
||||
//BAK files, this is not a major issue.
|
||||
if(!imageCache.isReady() || !path) {
|
||||
return;
|
||||
}
|
||||
await imageCache.removeBAKFromCache(path);
|
||||
}
|
||||
|
||||
private async moveBAKFile(oldPath: string, newPath: string) {
|
||||
if(!oldPath || !newPath) {
|
||||
return;
|
||||
}
|
||||
//this will not work in the short period when Obsidian is starting up, however
|
||||
//this will only effect a very few files, statistically unlikely to cause
|
||||
//much/any real user impact.
|
||||
//a proper queuing feels overkill for this.
|
||||
if(!imageCache.isReady()) {
|
||||
return;
|
||||
}
|
||||
const backup = await imageCache.getBAKFromCache(oldPath);
|
||||
if(backup) {
|
||||
await imageCache.addBAKToCache(newPath, `${backup}`);
|
||||
await this.removeBAKFromCache(oldPath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* watch file delete and delete corresponding .svg and .png
|
||||
* @param file
|
||||
@@ -473,7 +571,7 @@ export class PluginFileManager {
|
||||
//close excalidraw view where this file is open
|
||||
const excalidrawViews = getExcalidrawViews(this.app);
|
||||
for (const excalidrawView of excalidrawViews) {
|
||||
if (excalidrawView.file.path === file.path) {
|
||||
if (file?.path && excalidrawView?.file?.path === file.path) {
|
||||
await excalidrawView.leaf.setViewState({
|
||||
type: VIEW_TYPE_EXCALIDRAW,
|
||||
state: { file: null },
|
||||
@@ -481,16 +579,35 @@ export class PluginFileManager {
|
||||
}
|
||||
}
|
||||
|
||||
this.removeBAKFromCache(file.path);
|
||||
|
||||
//delete PNG and SVG files as well
|
||||
if (this.settings.keepInSync) {
|
||||
const imgMap = new Map<string, string>();
|
||||
[EXPORT_TYPES, "excalidraw"].flat().forEach(ext => {
|
||||
let imgPath = getIMGFilename(file.path, ext);
|
||||
if(this.plugin.ea?.onImageExportPathHook) {
|
||||
try {
|
||||
imgPath = this.plugin.ea.onImageExportPathHook({
|
||||
exportFilepath: imgPath,
|
||||
exportExtension: ext,
|
||||
excalidrawFile: file,
|
||||
action: "delete",
|
||||
}) ?? imgPath;
|
||||
} catch (e) {
|
||||
errorlog({where: "FileManager.deleteEventHandler", fn: this.plugin.ea.onImageExportPathHook, error: e});
|
||||
}
|
||||
}
|
||||
imgMap.set(ext, imgPath);
|
||||
});
|
||||
|
||||
window.setTimeout(() => {
|
||||
[EXPORT_TYPES, "excalidraw"].flat().forEach(async (ext: string) => {
|
||||
const imgPath = getIMGFilename(file.path, ext);
|
||||
const imgFile = this.app.vault.getAbstractFileByPath(
|
||||
imgMap.forEach((imgPath: string, ext: string) => {
|
||||
const imgFile = this.app.vault.getFileByPath(
|
||||
normalizePath(imgPath),
|
||||
);
|
||||
if (imgFile && imgFile instanceof TFile) {
|
||||
await this.app.vault.delete(imgFile);
|
||||
if (imgFile) {
|
||||
this.app.vault.delete(imgFile);
|
||||
}
|
||||
});
|
||||
}, 500);
|
||||
|
||||
@@ -710,7 +710,7 @@ const isTextOnlyEmbed = (internalEmbedEl: Element):boolean => {
|
||||
if(!src) return true; //technically this does not mean this is a text only embed, but still should abort further processing
|
||||
const fnameParts = getEmbeddedFilenameParts(src);
|
||||
return !(fnameParts.hasArearef || fnameParts.hasGroupref || fnameParts.hasFrameref || fnameParts.hasClippedFrameref) &&
|
||||
(fnameParts.hasBlockref || fnameParts.hasSectionref)
|
||||
(fnameParts.hasBlockref || fnameParts.hasSectionref) && fnameParts.blockref !== "as-image"
|
||||
}
|
||||
|
||||
const tmpObsidianWYSIWYG = async (
|
||||
@@ -724,6 +724,9 @@ const tmpObsidianWYSIWYG = async (
|
||||
const file = app.vault.getAbstractFileByPath(ctx.sourcePath);
|
||||
if(!(file instanceof TFile)) return;
|
||||
if(!plugin.isExcalidrawFile(file)) return;
|
||||
if(ctx.frontmatter?.["excalidraw-embed-md"]) {
|
||||
return;
|
||||
}
|
||||
|
||||
//@ts-ignore
|
||||
if (ctx.remainingNestLevel < 4) {
|
||||
@@ -801,15 +804,20 @@ const tmpObsidianWYSIWYG = async (
|
||||
if(Boolean(ctx.frontmatter)) {
|
||||
el.empty();
|
||||
} else {
|
||||
const warningEl = el.querySelector("div>h3[data-heading^='Unable to find section #^");
|
||||
//Obsidian changed this at some point from h3 to h5 and also the text...
|
||||
let warningEl = el.querySelector("div>*[data-heading^='Unable to find ");
|
||||
if(!warningEl) {
|
||||
//changed in Obsidian 1.8.9
|
||||
warningEl = el.querySelector("div > *[data-heading]");
|
||||
}
|
||||
if(warningEl) {
|
||||
const ref = warningEl.getAttr("data-heading").match(/Unable to find section (#\^(?:group=|area=|frame=|clippedframe=)[^ ]*)/)?.[1];
|
||||
const dataHeading = warningEl.getAttr("data-heading");
|
||||
const ref = dataHeading.match(/.+(\^(?:group=|area=|frame=|clippedframe=)[A-Za-z0-9_-]{8,21})/)?.[1];
|
||||
if(ref) {
|
||||
attr.fname = file.path + ref;
|
||||
attr.fname = file.path + "#" +ref;
|
||||
areaPreview = true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
if(!isFrontmatterDiv && !areaPreview) {
|
||||
if(el.parentElement === containerEl) containerEl.removeChild(el);
|
||||
@@ -925,7 +933,7 @@ export const markdownPostProcessor = async (
|
||||
if(docIDs.has(ctx.docId) && !el.hasChildNodes()) {
|
||||
docIDs.delete(ctx.docId);
|
||||
}
|
||||
const isAreaGroupFrameRef = el.querySelectorAll('[data-heading^="Unable to find"]').length === 1;
|
||||
const isAreaGroupFrameRef = el.querySelectorAll('div > *[data-heading]').length === 1;
|
||||
if(!isAreaGroupFrameRef) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -130,7 +130,7 @@ export class ObserverManager {
|
||||
return;
|
||||
}
|
||||
if (this.plugin.isExcalidrawFile(f)) {
|
||||
el.insertBefore(
|
||||
el.insertAfter(
|
||||
createDiv({
|
||||
cls: "nav-file-tag",
|
||||
text: this.settings.experimentalFileTag,
|
||||
|
||||
@@ -4,77 +4,202 @@ import { Packages } from "../../types/types";
|
||||
import { debug, DEBUGGING } from "../../utils/debugHelper";
|
||||
import { Notice } from "obsidian";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { errorHandler } from "../../utils/ErrorHandler";
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom";
|
||||
|
||||
declare let REACT_PACKAGES:string;
|
||||
declare let react:any;
|
||||
declare let reactDOM:any;
|
||||
declare let react: typeof React;
|
||||
declare let reactDOM:typeof ReactDOM;
|
||||
declare let excalidrawLib: typeof ExcalidrawLib;
|
||||
declare const unpackExcalidraw: Function;
|
||||
|
||||
export class PackageManager {
|
||||
private packageMap: Map<Window, Packages> = new Map<Window, Packages>();
|
||||
private EXCALIDRAW_PACKAGE: string;
|
||||
private plugin: ExcalidrawPlugin;
|
||||
private fallbackPackage: Packages | null = null;
|
||||
|
||||
constructor(plugin: ExcalidrawPlugin) {
|
||||
this.plugin = plugin;
|
||||
|
||||
try {
|
||||
this.EXCALIDRAW_PACKAGE = unpackExcalidraw();
|
||||
excalidrawLib = window.eval.call(window,`(function() {${this.EXCALIDRAW_PACKAGE};return ExcalidrawLib;})()`);
|
||||
|
||||
// Use safe evaluation for unpacking the Excalidraw package
|
||||
excalidrawLib = errorHandler.safeEval(
|
||||
`(function() {${this.EXCALIDRAW_PACKAGE};return ExcalidrawLib;})()`,
|
||||
"PackageManager constructor - excalidrawLib initialization",
|
||||
window
|
||||
);
|
||||
|
||||
if (!excalidrawLib) {
|
||||
throw new Error("Failed to initialize excalidrawLib");
|
||||
}
|
||||
|
||||
// Update the exported functions
|
||||
updateExcalidrawLib();
|
||||
this.setPackage(window,{react, reactDOM, excalidrawLib});
|
||||
|
||||
// Create a package with the loaded libraries
|
||||
const initialPackage = {react, reactDOM, excalidrawLib};
|
||||
|
||||
// Validate the package before storing
|
||||
if (this.validatePackage(initialPackage)) {
|
||||
this.setPackage(window, initialPackage);
|
||||
this.fallbackPackage = initialPackage; // Store a valid package as fallback
|
||||
} else {
|
||||
throw new Error("Invalid initial package");
|
||||
}
|
||||
} catch (e) {
|
||||
new Notice("Error loading the Excalidraw package", 6000);
|
||||
errorHandler.handleError(e, "PackageManager constructor");
|
||||
new Notice("Error loading the Excalidraw package. Some features may not work correctly.", 10000);
|
||||
console.error("Error loading the Excalidraw package", e);
|
||||
}
|
||||
|
||||
plugin.logStartupEvent("Excalidraw package unpacked");
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that a package contains all required components
|
||||
*/
|
||||
private validatePackage(pkg: Packages): boolean {
|
||||
if (!pkg) return false;
|
||||
|
||||
// Check that all components exist
|
||||
if (!pkg.react || !pkg.reactDOM || !pkg.excalidrawLib) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Verify that excalidrawLib has essential methods
|
||||
const lib = pkg.excalidrawLib;
|
||||
return (
|
||||
typeof lib === 'object' &&
|
||||
lib !== null &&
|
||||
typeof lib.restore === 'function' &&
|
||||
typeof lib.exportToSvg === 'function'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a package for a specific window
|
||||
*/
|
||||
public setPackage(window: Window, pkg: Packages) {
|
||||
this.packageMap.set(window, pkg);
|
||||
if (this.validatePackage(pkg)) {
|
||||
this.packageMap.set(window, pkg);
|
||||
|
||||
// Update fallback if we don't have one
|
||||
if (!this.fallbackPackage) {
|
||||
this.fallbackPackage = pkg;
|
||||
}
|
||||
} else {
|
||||
errorHandler.handleError(
|
||||
"Attempted to set invalid package",
|
||||
"PackageManager.setPackage"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public getPackageMap() {
|
||||
return this.packageMap;
|
||||
}
|
||||
|
||||
public getPackage(win:Window):Packages {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.getPackage, `ExcalidrawPlugin.getPackage`, win);
|
||||
/**
|
||||
* Gets a package for a window, creating it if necessary
|
||||
* with robust error handling
|
||||
*/
|
||||
public getPackage(win: Window): Packages {
|
||||
try {
|
||||
if ((process.env.NODE_ENV === 'development') && DEBUGGING) {
|
||||
debug(this.getPackage, `PackageManager.getPackage`, win);
|
||||
}
|
||||
|
||||
if(this.packageMap.has(win)) {
|
||||
return this.packageMap.get(win);
|
||||
// Return existing package if available
|
||||
if (this.packageMap.has(win)) {
|
||||
const pkg = this.packageMap.get(win);
|
||||
if (this.validatePackage(pkg)) {
|
||||
return pkg;
|
||||
}
|
||||
// If package exists but is invalid, delete it so we can recreate it
|
||||
this.packageMap.delete(win);
|
||||
}
|
||||
|
||||
// Create new package
|
||||
return errorHandler.wrapWithTryCatch(() => {
|
||||
// Use safe evaluation to load packages in the window context
|
||||
const evalResult = errorHandler.safeEval<{react: typeof React, reactDOM: typeof ReactDOM, excalidrawLib: typeof ExcalidrawLib}>(
|
||||
`(function() {
|
||||
${REACT_PACKAGES + this.EXCALIDRAW_PACKAGE};
|
||||
return {react: React, reactDOM: ReactDOM, excalidrawLib: ExcalidrawLib};
|
||||
})()`,
|
||||
"PackageManager.getPackage - package evaluation",
|
||||
win
|
||||
);
|
||||
|
||||
if (!evalResult || !this.validatePackage(evalResult)) {
|
||||
throw new Error("Failed to create valid package");
|
||||
}
|
||||
|
||||
const newPackage = {
|
||||
react: evalResult.react,
|
||||
reactDOM: evalResult.reactDOM,
|
||||
excalidrawLib: evalResult.excalidrawLib
|
||||
};
|
||||
|
||||
this.packageMap.set(win, newPackage);
|
||||
return newPackage;
|
||||
}, "PackageManager.getPackage", this.fallbackPackage);
|
||||
} catch (error) {
|
||||
errorHandler.handleError(error, "PackageManager.getPackage");
|
||||
|
||||
// Return fallback package if available to prevent data loss
|
||||
if (this.fallbackPackage) {
|
||||
return this.fallbackPackage;
|
||||
}
|
||||
|
||||
// If no fallback, throw error to prevent undefined behavior
|
||||
throw new Error("Failed to get package and no fallback available");
|
||||
}
|
||||
|
||||
const {react:r, reactDOM:rd, excalidrawLib:e} = win.eval.call(win,
|
||||
`(function() {
|
||||
${REACT_PACKAGES + this.EXCALIDRAW_PACKAGE};
|
||||
return {react:React,reactDOM:ReactDOM,excalidrawLib:ExcalidrawLib};
|
||||
})()`);
|
||||
this.packageMap.set(win,{react:r, reactDOM:rd, excalidrawLib:e});
|
||||
return {react:r, reactDOM:rd, excalidrawLib:e};
|
||||
}
|
||||
|
||||
public deletePackage(win: Window) {
|
||||
const { react, reactDOM, excalidrawLib } = this.getPackage(win);
|
||||
try {
|
||||
const pkg = this.packageMap.get(win);
|
||||
if (!pkg) return;
|
||||
|
||||
if (win.ExcalidrawLib === excalidrawLib) {
|
||||
excalidrawLib.destroyObsidianUtils();
|
||||
delete win.ExcalidrawLib;
|
||||
const { react, reactDOM, excalidrawLib } = pkg;
|
||||
|
||||
if (win.ExcalidrawLib === excalidrawLib) {
|
||||
// Safely clean up resources
|
||||
errorHandler.wrapWithTryCatch(() => {
|
||||
if (excalidrawLib && typeof excalidrawLib.destroyObsidianUtils === 'function') {
|
||||
excalidrawLib.destroyObsidianUtils();
|
||||
}
|
||||
delete win.ExcalidrawLib;
|
||||
}, "PackageManager.deletePackage - cleanup ExcalidrawLib");
|
||||
}
|
||||
|
||||
if (win.React === react) {
|
||||
errorHandler.wrapWithTryCatch(() => {
|
||||
Object.keys(win.React || {}).forEach((key) => {
|
||||
delete win.React[key];
|
||||
});
|
||||
delete win.React;
|
||||
}, "PackageManager.deletePackage - cleanup React");
|
||||
}
|
||||
|
||||
if (win.ReactDOM === reactDOM) {
|
||||
errorHandler.wrapWithTryCatch(() => {
|
||||
Object.keys(win.ReactDOM || {}).forEach((key) => {
|
||||
delete win.ReactDOM[key];
|
||||
});
|
||||
delete win.ReactDOM;
|
||||
}, "PackageManager.deletePackage - cleanup ReactDOM");
|
||||
}
|
||||
|
||||
this.packageMap.delete(win);
|
||||
} catch (error) {
|
||||
errorHandler.handleError(error, "PackageManager.deletePackage");
|
||||
}
|
||||
|
||||
if (win.React === react) {
|
||||
Object.keys(win.React).forEach((key) => {
|
||||
delete win.React[key];
|
||||
});
|
||||
delete win.React;
|
||||
}
|
||||
|
||||
if (win.ReactDOM === reactDOM) {
|
||||
Object.keys(win.ReactDOM).forEach((key) => {
|
||||
delete win.ReactDOM[key];
|
||||
});
|
||||
delete win.ReactDOM;
|
||||
}
|
||||
|
||||
this.packageMap.delete(win);
|
||||
}
|
||||
|
||||
public setExcalidrawPackage(pkg: string) {
|
||||
@@ -82,16 +207,22 @@ export class PackageManager {
|
||||
}
|
||||
|
||||
public destroy() {
|
||||
REACT_PACKAGES = "";
|
||||
Object.values(this.packageMap).forEach((p: Packages) => {
|
||||
delete p.excalidrawLib;
|
||||
delete p.reactDOM;
|
||||
delete p.react;
|
||||
});
|
||||
this.packageMap.clear();
|
||||
this.EXCALIDRAW_PACKAGE = "";
|
||||
react = null;
|
||||
reactDOM = null;
|
||||
excalidrawLib = null;
|
||||
try {
|
||||
REACT_PACKAGES = "";
|
||||
|
||||
Array.from(this.packageMap.entries()).forEach(([win, p]) => {
|
||||
this.deletePackage(win);
|
||||
});
|
||||
|
||||
this.packageMap.clear();
|
||||
this.EXCALIDRAW_PACKAGE = "";
|
||||
this.fallbackPackage = null;
|
||||
|
||||
react = null;
|
||||
reactDOM = null;
|
||||
excalidrawLib = null;
|
||||
} catch (error) {
|
||||
errorHandler.handleError(error, "PackageManager.destroy");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,10 @@ import {
|
||||
ButtonComponent,
|
||||
DropdownComponent,
|
||||
getIcon,
|
||||
htmlToMarkdown,
|
||||
Modifier,
|
||||
normalizePath,
|
||||
Notice,
|
||||
PluginSettingTab,
|
||||
Setting,
|
||||
TextComponent,
|
||||
@@ -18,6 +20,7 @@ import { DynamicStyle, GridSettings } from "src/types/types";
|
||||
import { PreviewImageType } from "src/types/utilTypes";
|
||||
import { setDynamicStyle } from "src/utils/dynamicStyling";
|
||||
import {
|
||||
createOrOverwriteFile,
|
||||
getDrawingFilename,
|
||||
getEmbedFilename,
|
||||
} from "src/utils/fileUtils";
|
||||
@@ -28,7 +31,7 @@ import {
|
||||
setLeftHandedMode,
|
||||
} from "src/utils/utils";
|
||||
import { imageCache } from "src/shared/ImageCache";
|
||||
import { ConfirmationPrompt } from "src/shared/Dialogs/Prompt";
|
||||
import { MultiOptionConfirmationPrompt } from "src/shared/Dialogs/Prompt";
|
||||
import { EmbeddableMDCustomProps } from "src/shared/Dialogs/EmbeddableSettings";
|
||||
import { EmbeddalbeMDFileCustomDataSettingsComponent } from "src/shared/Dialogs/EmbeddableMDFileCustomDataSettingsComponent";
|
||||
import { startupScript } from "src/constants/starutpscript";
|
||||
@@ -43,8 +46,10 @@ import { HotkeyEditor } from "src/shared/Dialogs/HotkeyEditor";
|
||||
import { getExcalidrawViews } from "src/utils/obsidianUtils";
|
||||
import { createSliderWithText } from "src/utils/sliderUtils";
|
||||
import { PDFExportSettingsComponent, PDFExportSettings } from "src/shared/Dialogs/PDFExportSettingsComponent";
|
||||
import { ContentSearcher } from "src/shared/components/ContentSearcher";
|
||||
|
||||
export interface ExcalidrawSettings {
|
||||
disableDoubleClickTextEditing: boolean;
|
||||
folder: string;
|
||||
cropFolder: string;
|
||||
annotateFolder: string;
|
||||
@@ -67,7 +72,9 @@ export interface ExcalidrawSettings {
|
||||
drawingFilnameEmbedPostfix: string;
|
||||
drawingFilenameDateTime: string;
|
||||
useExcalidrawExtension: boolean;
|
||||
cropSuffix: string;
|
||||
cropPrefix: string;
|
||||
annotateSuffix: string;
|
||||
annotatePrefix: string;
|
||||
annotatePreserveSize: boolean;
|
||||
displaySVGInPreview: boolean; //No longer used since 1.9.13
|
||||
@@ -173,6 +180,7 @@ export interface ExcalidrawSettings {
|
||||
showNewVersionNotification: boolean;
|
||||
//mathjaxSourceURL: string;
|
||||
latexBoilerplate: string;
|
||||
latexPreambleLocation: string;
|
||||
taskboneEnabled: boolean;
|
||||
taskboneAPIkey: string;
|
||||
pinnedScripts: string[];
|
||||
@@ -198,6 +206,7 @@ export interface ExcalidrawSettings {
|
||||
markdownNodeOneClickEditing: boolean;
|
||||
canvasImmersiveEmbed: boolean,
|
||||
startupScriptPath: string,
|
||||
aiEnabled: boolean,
|
||||
openAIAPIToken: string,
|
||||
openAIDefaultTextModel: string,
|
||||
openAIDefaultVisionModel: string,
|
||||
@@ -225,6 +234,7 @@ export interface ExcalidrawSettings {
|
||||
declare const PLUGIN_VERSION:string;
|
||||
|
||||
export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
disableDoubleClickTextEditing: false,
|
||||
folder: "Excalidraw",
|
||||
cropFolder: "",
|
||||
annotateFolder: "",
|
||||
@@ -247,7 +257,9 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
drawingFilnameEmbedPostfix: " ",
|
||||
drawingFilenameDateTime: "YYYY-MM-DD HH.mm.ss",
|
||||
useExcalidrawExtension: true,
|
||||
cropSuffix: "",
|
||||
cropPrefix: CROPPED_PREFIX,
|
||||
annotateSuffix: "",
|
||||
annotatePrefix: ANNOTATED_PREFIX,
|
||||
annotatePreserveSize: false,
|
||||
displaySVGInPreview: undefined,
|
||||
@@ -315,7 +327,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
experimentalFileTag: "✏️",
|
||||
experimentalLivePreview: true,
|
||||
fadeOutExcalidrawMarkup: false,
|
||||
loadPropertySuggestions: true,
|
||||
loadPropertySuggestions: false,
|
||||
experimentalEnableFourthFont: false,
|
||||
experimantalFourthFont: "Virgil",
|
||||
addDummyTextElement: false,
|
||||
@@ -348,6 +360,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
showNewVersionNotification: true,
|
||||
//mathjaxSourceURL: "https://cdn.jsdelivr.net/npm/mathjax@3.2.1/es5/tex-svg.js",
|
||||
latexBoilerplate: "\\color{blue}",
|
||||
latexPreambleLocation: "preamble.sty",
|
||||
taskboneEnabled: false,
|
||||
taskboneAPIkey: "",
|
||||
pinnedScripts: [],
|
||||
@@ -378,6 +391,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
DYNAMIC_COLOR: true,
|
||||
COLOR: "#000000",
|
||||
OPACITY: 50,
|
||||
GRID_DIRECTION: {horizontal: true, vertical: true},
|
||||
},
|
||||
laserSettings: {
|
||||
DECAY_LENGTH: 50,
|
||||
@@ -398,6 +412,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
markdownNodeOneClickEditing: false,
|
||||
canvasImmersiveEmbed: true,
|
||||
startupScriptPath: "",
|
||||
aiEnabled: true,
|
||||
openAIAPIToken: "",
|
||||
openAIDefaultTextModel: "gpt-3.5-turbo-1106",
|
||||
openAIDefaultVisionModel: "gpt-4o",
|
||||
@@ -502,11 +517,11 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
pdfSettings: {
|
||||
pageSize: "A4",
|
||||
pageOrientation: "portrait",
|
||||
fitToPage: true,
|
||||
fitToPage: 1,
|
||||
paperColor: "white",
|
||||
customPaperColor: "#ffffff",
|
||||
alignment: "center",
|
||||
margin: "normal"
|
||||
margin: "normal",
|
||||
},
|
||||
};
|
||||
|
||||
@@ -592,6 +607,31 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
containerEl.addClass("excalidraw-settings");
|
||||
this.containerEl.empty();
|
||||
|
||||
// ------------------------------------------------
|
||||
// Search and Settings to Clipboard
|
||||
// ------------------------------------------------
|
||||
|
||||
const notebookLMLinkContainer = createDiv("setting-item-description excalidraw-settings-links-container");
|
||||
new ContentSearcher(containerEl, notebookLMLinkContainer);
|
||||
notebookLMLinkContainer.createEl("a",{
|
||||
href: "https://notebooklm.google.com/notebook/42d76a2f-c11d-4002-9286-1683c43d0ab0",
|
||||
attr: {
|
||||
"aria-label": t("NOTEBOOKLM_LINK_ARIA"),
|
||||
"style": "margin: auto;"
|
||||
}},
|
||||
(a)=> {
|
||||
//Lucide: message-circle-question-mark
|
||||
a.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-message-circle-question-mark-icon lucide-message-circle-question-mark"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><path d="M12 17h.01"/></svg>${
|
||||
t("NOTEBOOKLM_LINK_TEXT")
|
||||
}`;
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
// ------------------------------------------------
|
||||
// Promo links
|
||||
// ------------------------------------------------
|
||||
|
||||
const coffeeDiv = containerEl.createDiv("coffee");
|
||||
coffeeDiv.addClass("ex-coffee-div");
|
||||
const coffeeLink = coffeeDiv.createEl("a", {
|
||||
@@ -606,41 +646,53 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
|
||||
const iconLinks = [
|
||||
{
|
||||
icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"></path><path d="M9 18c-4.51 2-5-2-7-2"></path></svg>`,
|
||||
icon: getIcon("bug").outerHTML,
|
||||
href: "https://github.com/zsviczian/obsidian-excalidraw-plugin/issues",
|
||||
aria: "Report bugs and raise feature requsts on the plugin's GitHub page",
|
||||
text: "Bugs and Feature Requests",
|
||||
aria: t("LINKS_BUGS_ARIA"),
|
||||
text: t("LINKS_BUGS"),
|
||||
},
|
||||
{
|
||||
icon: getIcon("globe").outerHTML,
|
||||
href: "https://excalidraw-obsidian.online/",
|
||||
aria: t("LINKS_WIKI_ARIA"),
|
||||
text: t("LINKS_WIKI"),
|
||||
},
|
||||
{
|
||||
icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19c-2.3 0-6.4-.2-8.1-.6-.7-.2-1.2-.7-1.4-1.4-.3-1.1-.5-3.4-.5-5s.2-3.9.5-5c.2-.7.7-1.2 1.4-1.4C5.6 5.2 9.7 5 12 5s6.4.2 8.1.6c.7.2 1.2.7 1.4 1.4.3 1.1.5 3.4.5 5s-.2 3.9-.5 5c-.2.7-.7 1.2-1.4 1.4-1.7.4-5.8.6-8.1.6 0 0 0 0 0 0z"></path><polygon points="10 15 15 12 10 9"></polygon></svg>`,
|
||||
icon: getIcon("youtube").outerHTML,
|
||||
href: "https://www.youtube.com/@VisualPKM",
|
||||
aria: "Check out my YouTube channel to learn about Visual Thinking and Excalidraw",
|
||||
text: "Visual PKM on YouTube",
|
||||
aria: t("LINKS_YT_ARIA"),
|
||||
text: t("LINKS_YT"),
|
||||
},
|
||||
{
|
||||
icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" stroke="none" strokeWidth="2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 640 512"><path d="M524.531,69.836a1.5,1.5,0,0,0-.764-.7A485.065,485.065,0,0,0,404.081,32.03a1.816,1.816,0,0,0-1.923.91,337.461,337.461,0,0,0-14.9,30.6,447.848,447.848,0,0,0-134.426,0,309.541,309.541,0,0,0-15.135-30.6,1.89,1.89,0,0,0-1.924-.91A483.689,483.689,0,0,0,116.085,69.137a1.712,1.712,0,0,0-.788.676C39.068,183.651,18.186,294.69,28.43,404.354a2.016,2.016,0,0,0,.765,1.375A487.666,487.666,0,0,0,176.02,479.918a1.9,1.9,0,0,0,2.063-.676A348.2,348.2,0,0,0,208.12,430.4a1.86,1.86,0,0,0-1.019-2.588,321.173,321.173,0,0,1-45.868-21.853,1.885,1.885,0,0,1-.185-3.126c3.082-2.309,6.166-4.711,9.109-7.137a1.819,1.819,0,0,1,1.9-.256c96.229,43.917,200.41,43.917,295.5,0a1.812,1.812,0,0,1,1.924.233c2.944,2.426,6.027,4.851,9.132,7.16a1.884,1.884,0,0,1-.162,3.126,301.407,301.407,0,0,1-45.89,21.83,1.875,1.875,0,0,0-1,2.611,391.055,391.055,0,0,0,30.014,48.815,1.864,1.864,0,0,0,2.063.7A486.048,486.048,0,0,0,610.7,405.729a1.882,1.882,0,0,0,.765-1.352C623.729,277.594,590.933,167.465,524.531,69.836ZM222.491,337.58c-28.972,0-52.844-26.587-52.844-59.239S193.056,219.1,222.491,219.1c29.665,0,53.306,26.82,52.843,59.239C275.334,310.993,251.924,337.58,222.491,337.58Zm195.38,0c-28.971,0-52.843-26.587-52.843-59.239S388.437,219.1,417.871,219.1c29.667,0,53.307,26.82,52.844,59.239C470.715,310.993,447.538,337.58,417.871,337.58Z"/></svg>`,
|
||||
href: "https://discord.gg/DyfAXFwUHc",
|
||||
aria: "Join the Visual Thinking Workshop Discord Server",
|
||||
text: "Community on Discord",
|
||||
aria: t("LINKS_DISCORD_ARIA"),
|
||||
text: t("LINKS_DISCORD"),
|
||||
},
|
||||
{
|
||||
icon: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 4s-.7 2.1-2 3.4c1.6 10-9.4 17.3-18 11.6 2.2.1 4.4-.6 6-2C3 15.5.5 9.6 3 5c2.2 2.6 5.6 4.1 9 4-.9-4.2 4-6.6 7-3.8 1.1 0 3-1.2 3-1.2z"></path></svg>`,
|
||||
icon: getIcon("twitter").outerHTML,
|
||||
href: "https://twitter.com/zsviczian",
|
||||
aria: "Follow me on Twitter",
|
||||
text: "Follow me on Twitter",
|
||||
aria: t("LINKS_TWITTER"),
|
||||
text: t("LINKS_TWITTER"),
|
||||
},
|
||||
{
|
||||
icon: getIcon("graduation-cap").outerHTML,
|
||||
href: "https://visual-thinking-workshop.com",
|
||||
aria: "Learn about Visual PKM, Excalidraw, Obsidian, ExcaliBrain and more",
|
||||
text: "Join the Visual Thinking Workshop",
|
||||
}
|
||||
aria: t("LINKS_VTW_ARIA"),
|
||||
text: t("LINKS_VTW"),
|
||||
},
|
||||
{
|
||||
icon: getIcon("book").outerHTML,
|
||||
href: "https://sketch-your-mind.com",
|
||||
aria: t("LINKS_BOOK_ARIA"),
|
||||
text: t("LINKS_BOOK"),
|
||||
},
|
||||
];
|
||||
|
||||
const linksEl = containerEl.createDiv("setting-item-description excalidraw-settings-links-container");
|
||||
iconLinks.forEach(({ icon, href, aria, text }) => {
|
||||
linksEl.createEl("a",{href, attr: { "aria-label": aria }}, (a)=> {
|
||||
a.innerHTML = icon + text;
|
||||
a.innerHTML = icon + text;
|
||||
});
|
||||
});
|
||||
|
||||
@@ -678,6 +730,17 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("TOGGLE_SPLASHSCREEN"))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(this.plugin.settings.showSplashscreen)
|
||||
.onChange((value)=> {
|
||||
this.plugin.settings.showSplashscreen = value;
|
||||
this.applySettingsUpdate();
|
||||
})
|
||||
)
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("FOLDER_NAME"))
|
||||
.setDesc(fragWithHTML(t("FOLDER_DESC")))
|
||||
@@ -937,7 +1000,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("CROP_PREFIX_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: Cropped_ ")
|
||||
.setPlaceholder("e.g.: cropped_")
|
||||
.setValue(this.plugin.settings.cropPrefix)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.cropPrefix = value.replaceAll(
|
||||
@@ -949,12 +1012,29 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("CROP_SUFFIX_NAME"))
|
||||
.setDesc(fragWithHTML(t("CROP_SUFFIX_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: _cropped")
|
||||
.setValue(this.plugin.settings.cropSuffix)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.cropSuffix = value.replaceAll(
|
||||
/[<>:"/\\|?*]/g,
|
||||
"_",
|
||||
);
|
||||
text.setValue(this.plugin.settings.cropSuffix);
|
||||
this.applySettingsUpdate();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("ANNOTATE_PREFIX_NAME"))
|
||||
.setDesc(fragWithHTML(t("ANNOTATE_PREFIX_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: Annotated_ ")
|
||||
.setPlaceholder("e.g.: annotated_")
|
||||
.setValue(this.plugin.settings.annotatePrefix)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.annotatePrefix = value.replaceAll(
|
||||
@@ -965,7 +1045,24 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
this.applySettingsUpdate();
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("ANNOTATE_SUFFIX_NAME"))
|
||||
.setDesc(fragWithHTML(t("ANNOTATE_SUFFIX_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: _annotated")
|
||||
.setValue(this.plugin.settings.annotateSuffix)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.annotateSuffix = value.replaceAll(
|
||||
/[<>:"/\\|?*]/g,
|
||||
"_",
|
||||
);
|
||||
text.setValue(this.plugin.settings.annotateSuffix);
|
||||
this.applySettingsUpdate();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("ANNOTATE_PRESERVE_SIZE_NAME"))
|
||||
.setDesc(fragWithHTML(t("ANNOTATE_PRESERVE_SIZE_DESC")))
|
||||
@@ -990,6 +1087,27 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
cls: "excalidraw-setting-h1",
|
||||
});
|
||||
|
||||
let aiEl: HTMLElement;
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("AI_ENABLED_NAME"))
|
||||
.setDesc(fragWithHTML(t("AI_ENABLED_DESC")))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(this.plugin.settings.aiEnabled??true)
|
||||
.onChange(async (value) => {
|
||||
aiEl.style.display = value ? "block" : "none";
|
||||
this.plugin.settings.aiEnabled = value;
|
||||
this.applySettingsUpdate();
|
||||
}),
|
||||
);
|
||||
|
||||
detailsEl = detailsEl.createDiv();
|
||||
aiEl = detailsEl;
|
||||
if(!(this.plugin.settings.aiEnabled??true)) {
|
||||
detailsEl.style.display = "none";
|
||||
}
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("AI_OPENAI_TOKEN_NAME"))
|
||||
.setDesc(fragWithHTML(t("AI_OPENAI_TOKEN_DESC")))
|
||||
@@ -1067,6 +1185,17 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
cls: "excalidraw-setting-h1",
|
||||
});
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("ENABLE_DOUBLE_CLICK_TEXT_EDITING_NAME"))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(!this.plugin.settings.disableDoubleClickTextEditing)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.disableDoubleClickTextEditing = !value;
|
||||
this.applySettingsUpdate();
|
||||
}),
|
||||
);
|
||||
|
||||
const readingModeEl = new Setting(detailsEl)
|
||||
.setName(t("SHOW_DRAWING_OR_MD_IN_READING_MODE_NAME"))
|
||||
.setDesc(fragWithHTML(t("SHOW_DRAWING_OR_MD_IN_READING_MODE_DESC")))
|
||||
@@ -1109,17 +1238,6 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
);
|
||||
addIframe(detailsEl, "H8Njp7ZXYag",999);
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("TOGGLE_SPLASHSCREEN"))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(this.plugin.settings.showSplashscreen)
|
||||
.onChange((value)=> {
|
||||
this.plugin.settings.showSplashscreen = value;
|
||||
this.applySettingsUpdate();
|
||||
})
|
||||
)
|
||||
|
||||
detailsEl = displayDetailsEl.createEl("details");
|
||||
detailsEl.createEl("summary", {
|
||||
text: t("HOTKEY_OVERRIDE_HEAD"),
|
||||
@@ -1378,6 +1496,42 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
getExcalidrawViews(this.app).forEach(excalidrawView=>excalidrawView.updateGridColor());
|
||||
};
|
||||
|
||||
const updateGridDirection = () => {
|
||||
getExcalidrawViews(this.app).forEach(excalidrawView=>
|
||||
excalidrawView.updateGridDirection(this.plugin.settings.gridSettings.GRID_DIRECTION));
|
||||
}
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("GRID_DIRECTION_NAME"))
|
||||
.setDesc(t("GRID_DIRECTION_DESC"))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setTooltip(t("GRID_HORIZONTAL"))
|
||||
.setValue(this.plugin.settings.gridSettings.GRID_DIRECTION?.horizontal ?? true)
|
||||
.onChange((value) => {
|
||||
if(!this.plugin.settings.gridSettings.GRID_DIRECTION) {
|
||||
this.plugin.settings.gridSettings.GRID_DIRECTION = { horizontal: true, vertical: true };
|
||||
} //2.10.1 migration
|
||||
this.plugin.settings.gridSettings.GRID_DIRECTION.horizontal = value;
|
||||
this.applySettingsUpdate();
|
||||
updateGridDirection();
|
||||
}),
|
||||
)
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setTooltip(t("GRID_VERTICAL"))
|
||||
.setValue(this.plugin.settings.gridSettings.GRID_DIRECTION?.vertical ?? true)
|
||||
.onChange((value) => {
|
||||
if(!this.plugin.settings.gridSettings.GRID_DIRECTION) {
|
||||
this.plugin.settings.gridSettings.GRID_DIRECTION = { horizontal: true, vertical: true };
|
||||
} //2.10.1 migration
|
||||
this.plugin.settings.gridSettings.GRID_DIRECTION.vertical = value;
|
||||
this.applySettingsUpdate();
|
||||
updateGridDirection();
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
// Dynamic color toggle
|
||||
let gridColorSection: HTMLDivElement;
|
||||
new Setting(detailsEl)
|
||||
@@ -1972,7 +2126,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
button
|
||||
.setButtonText(t("BACKUP_CACHE_CLEAR"))
|
||||
.onClick(() => {
|
||||
const confirmationPrompt = new ConfirmationPrompt(this.plugin,t("BACKUP_CACHE_CLEAR_CONFIRMATION"));
|
||||
const confirmationPrompt = new MultiOptionConfirmationPrompt(this.plugin,t("BACKUP_CACHE_CLEAR_CONFIRMATION"));
|
||||
confirmationPrompt.waitForClose.then((confirmed) => {
|
||||
if (confirmed) {
|
||||
imageCache.clearBackupCache();
|
||||
@@ -2508,6 +2662,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
this.requestReloadDrawings = true;
|
||||
this.plugin.settings.experimentalEnableFourthFont = value;
|
||||
this.applySettingsUpdate();
|
||||
if(value) {
|
||||
this.plugin.initializeFonts();
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -2613,6 +2770,19 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("LATEX_PREAMBLE_NAME"))
|
||||
.setDesc(fragWithHTML(t("LATEX_PREAMBLE_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: preamble.sty")
|
||||
.setValue(this.plugin.settings.latexPreambleLocation)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.latexPreambleLocation = value;
|
||||
this.applySettingsUpdate();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("FILETYPE_NAME"))
|
||||
.setDesc(fragWithHTML(t("FILETYPE_DESC")))
|
||||
@@ -2784,7 +2954,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
: this.plugin.settings.startupScriptPath + ".md");
|
||||
let f = this.app.vault.getAbstractFileByPath(startupPath);
|
||||
if(!f) {
|
||||
f = await this.app.vault.create(startupPath, startupScript());
|
||||
f = await createOrOverwriteFile(this.app, startupPath, startupScript());
|
||||
}
|
||||
startupScriptButton.setButtonText(t("STARTUP_SCRIPT_BUTTON_OPEN"));
|
||||
this.app.workspace.openLinkText(f.path,"",true);
|
||||
|
||||
@@ -9,6 +9,7 @@ declare var LZString: any;
|
||||
let locale: Partial<typeof en> | null = null;
|
||||
|
||||
function loadLocale(lang: string): Partial<typeof en> {
|
||||
if(lang === "zh") lang = "zh-cn"; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2247
|
||||
if (Object.keys(PLUGIN_LANGUAGES).includes(lang)) {
|
||||
const decompressed = LZString.decompressFromBase64(PLUGIN_LANGUAGES[lang]);
|
||||
let x = {};
|
||||
|
||||
149
src/lang/langDiffWithEn.js
Normal file
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* Language Pack Diff Checker Script
|
||||
*
|
||||
* Purpose:
|
||||
* Compare src/lang/locale/en.ts and a target language file (e.g. zh-cn.ts), output missing and extra keys.
|
||||
* Output is color-coded:
|
||||
* - Green: Key exists in en.ts but missing in the target language file
|
||||
* - Red: Key exists in the target language file but not in en.ts
|
||||
* - Yellow: The same key exists in both files but the line numbers are different
|
||||
*
|
||||
* Dependencies:
|
||||
* Node.js environment, no extra dependencies required.
|
||||
*
|
||||
* Usage:
|
||||
* 1. Open a terminal in this file's directory (or project root).
|
||||
* 2. Run:
|
||||
* node src/lang/langDiffWithEn.js zh-cn
|
||||
* # or node src/lang/langDiffWithEn.js ja
|
||||
* # The argument is the language file name (without extension), default is zh-cn
|
||||
*
|
||||
* Output:
|
||||
* + (green): Key exists in en.ts but missing in the target language file
|
||||
* - (red): Key exists in the target language file but not in en.ts
|
||||
* ! (yellow): The same key exists in both files but the line numbers are different
|
||||
* If there is no output, the two files have identical keys.
|
||||
*/
|
||||
/**
|
||||
* 语言包差异检测脚本
|
||||
*
|
||||
* 用途:
|
||||
* 比较 src/lang/locale/en.ts 与指定语言文件(如 zh-cn.ts)中的 key,输出缺失和多余的 key。
|
||||
* 输出内容会用不同颜色区分:
|
||||
* - 绿色:en.ts 有但目标语言缺失的 key
|
||||
* - 红色:目标语言有但 en.ts 没有的 key
|
||||
* - 黄色:相同的 key 所在的行号不相同
|
||||
*
|
||||
* 依赖:
|
||||
* Node.js 环境,无需额外依赖。
|
||||
*
|
||||
* 用法:
|
||||
* 1. 在命令行进入本文件所在目录(或项目根目录)。
|
||||
* 2. 运行:
|
||||
* node src/lang/langDiffWithEn.js zh-cn
|
||||
* # 或 node src/lang/langDiffWithEn.js ja
|
||||
* # 参数为语言文件名(不带扩展名),默认为 zh-cn
|
||||
*
|
||||
* 输出说明:
|
||||
* + 开头(绿色):en.ts 有但目标语言缺失的 key
|
||||
* - 开头(红色):目标语言有但 en.ts 没有的 key
|
||||
* ! 开头(黄色):相同的 key 所在的行号不相同
|
||||
* 若无输出则表示两个文件 key 完全一致。
|
||||
*/
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
/**
|
||||
* 读取 locale 文件夹下指定语言和 en.ts 文件,逐行解析键值和行号
|
||||
* @param lang 语言文件名(不含扩展名),如 zh-cn
|
||||
* @returns { en: Record<string, {value: string, line: number}>, lang: Record<string, {value: string, line: number}> }
|
||||
*/
|
||||
function readLocaleFiles(lang = "zh-cn") {
|
||||
// 构造 locale 目录路径
|
||||
const localeDir = path.join(__dirname, "./locale");
|
||||
// 获取 en.ts 文件路径
|
||||
const enFile = path.join(localeDir, "en.ts");
|
||||
// 获取指定语言文件路径
|
||||
const langFile = path.join(localeDir, `${lang}.ts`);
|
||||
/**
|
||||
* 解析指定的语言文件,提取每个 key 的值和所在行号
|
||||
* @param file 文件路径
|
||||
* @returns {Record<string, {value: string, line: number}>}
|
||||
*/
|
||||
const parse = (file) => {
|
||||
// 读取文件内容并按行分割
|
||||
const lines = fs.readFileSync(file, "utf8").split(/\r?\n/);
|
||||
const result = {};
|
||||
let inExport = false;
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
// 检查是否进入 export default 块
|
||||
if (!inExport && line.includes("export default")) {
|
||||
inExport = true;
|
||||
continue;
|
||||
}
|
||||
if (!inExport) continue;
|
||||
// 匹配 key: "value", 格式的行
|
||||
const m = line.match(/^\s*([A-Z0-9_]+)\s*:\s*.*?,?$/);
|
||||
if (m) {
|
||||
let key = m[1];
|
||||
// 保存 key 及其所在行号
|
||||
result[key] = i + 1;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
};
|
||||
// 返回 en 和指定语言的解析结果
|
||||
return {
|
||||
en: parse(enFile),
|
||||
lang: parse(langFile),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较 en 和 lang 的 key/value,输出差异
|
||||
*/
|
||||
|
||||
function diffLang(lang = "zh-cn") {
|
||||
const { en, lang: l } = readLocaleFiles(lang);
|
||||
const allKeys = new Set([...Object.keys(en), ...Object.keys(l)]);
|
||||
const diffs = [];
|
||||
for (const key of allKeys) {
|
||||
if (!(key in en)) {
|
||||
diffs.push(`- ${key}: ${l[key]}`);
|
||||
} else if (!(key in l)) {
|
||||
diffs.push(`+ ${key}: ${en[key]}`);
|
||||
} else {
|
||||
if (en[key] !== l[key]) {
|
||||
diffs.push(`! ${key}: en: ${en[key]} <--> lang: ${l[key]}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return diffs;
|
||||
}
|
||||
|
||||
// CLI
|
||||
if (require.main === module) {
|
||||
const lang = process.argv[2] || "zh-cn";
|
||||
const diffs = diffLang(lang);
|
||||
if (diffs.length === 0) {
|
||||
console.log(`语言文件 ${lang} 与 en.ts 无差异`);
|
||||
} else {
|
||||
diffs.forEach((line) => {
|
||||
if (line.startsWith("+")) {
|
||||
// 绿色
|
||||
console.log("\x1b[32m%s\x1b[0m", line);
|
||||
} else if (line.startsWith("-")) {
|
||||
// 红色
|
||||
console.log("\x1b[31m%s\x1b[0m", line);
|
||||
} else if (line.startsWith("!")) {
|
||||
// 黄色
|
||||
console.log("\x1b[33m%s\x1b[0m", line);
|
||||
} else {
|
||||
// 默认
|
||||
console.log(line);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ export default {
|
||||
DUPLICATE_IMAGE: "Duplicate selected image with a different image ID",
|
||||
CONVERT_NOTE_TO_EXCALIDRAW: "Convert markdown note to Excalidraw Drawing",
|
||||
CONVERT_EXCALIDRAW: "Convert *.excalidraw to *.md files",
|
||||
CREATE_NEW: "Create new drawing",
|
||||
CREATE_NEW: "New drawing",
|
||||
CONVERT_FILE_KEEP_EXT: "*.excalidraw => *.excalidraw.md",
|
||||
CONVERT_FILE_REPLACE_EXT: "*.excalidraw => *.md (Logseq compatibility)",
|
||||
DOWNLOAD_LIBRARY: "Export stencil library as an *.excalidrawlib file",
|
||||
@@ -44,7 +44,7 @@ export default {
|
||||
TRANSCLUDE_MOST_RECENT: "Embed the most recently edited drawing",
|
||||
TOGGLE_LEFTHANDED_MODE: "Toggle left-handed mode",
|
||||
TOGGLE_SPLASHSCREEN: "Show splash screen in new drawings",
|
||||
FLIP_IMAGE: "Open the back-of-the-note of the selected excalidraw image",
|
||||
FLIP_IMAGE: "Open the back-of-the-note for the selected image in a popout window",
|
||||
NEW_IN_NEW_PANE: "Create new drawing - IN AN ADJACENT WINDOW",
|
||||
NEW_IN_NEW_TAB: "Create new drawing - IN A NEW TAB",
|
||||
NEW_IN_ACTIVE_PANE: "Create new drawing - IN THE CURRENT ACTIVE WINDOW",
|
||||
@@ -158,6 +158,10 @@ export default {
|
||||
CONVERT_FILE: "Convert to new format",
|
||||
BACKUP_AVAILABLE: "We encountered an error while loading your drawing. This might have occurred if Obsidian unexpectedly closed during a save operation. For example, if you accidentally closed Obsidian on your mobile device while saving.<br><br><b>GOOD NEWS:</b> Fortunately, a local backup is available. However, please note that if you last modified this drawing on a different device (e.g., tablet) and you are now on your desktop, that other device likely has a more recent backup.<br><br>I recommend trying to open the drawing on your other device first and restore the backup from its local storage.<br><br>Would you like to load the backup?",
|
||||
BACKUP_RESTORED: "Backup restored",
|
||||
BACKUP_SAVE_AS_FILE: "This drawing is empty. A non-empty backup is available. Would you like to restore it as a new file and open it in a new tab?",
|
||||
BACKUP_SAVE: "Restore",
|
||||
BACKUP_DELETE: "Delete Backup",
|
||||
BACKUP_CANCEL: "Cancel",
|
||||
CACHE_NOT_READY: "I apologize for the inconvenience, but an error occurred while loading your file.<br><br><mark>Having a little patience can save you a lot of time...</mark><br><br>The plugin has a backup cache, but it appears that you have just started Obsidian. Initializing the Backup Cache may take some time, usually up to a minute or more depending on your device's performance. You will receive a notification in the top right corner when the cache initialization is complete.<br><br>Please press OK to attempt loading the file again and check if the cache has finished initializing. If you see a completely empty file behind this message, I recommend waiting until the backup cache is ready before proceeding. Alternatively, you can choose Cancel to manually correct your file.<br>",
|
||||
OBSIDIAN_TOOLS_PANEL: "Obsidian Tools Panel",
|
||||
ERROR_SAVING_IMAGE: "Unknown error occurred while fetching the image. It could be that for some reason the image is not available or rejected the fetch request from Obsidian",
|
||||
@@ -188,7 +192,32 @@ export default {
|
||||
SAVE_IS_TAKING_LONG: "Saving your previous file is taking a long time. Please wait...",
|
||||
SAVE_IS_TAKING_VERY_LONG: "For better performance, consider splitting large drawings into several smaller files.",
|
||||
|
||||
//ContentSearcher.ts
|
||||
SEARCH_COPIED_TO_CLIPBOARD: "Markdown ready on clipboard",
|
||||
SEARCH_COPY_TO_CLIPBOARD_ARIA: "Copy the entire dialog to the clipboard as Markdown. Ideal for use with tools like ChatGPT to search and understand.",
|
||||
SEARCH_SHOWHIDE_ARIA: "Show/Hide search bar",
|
||||
SEARCH_NEXT: "Next",
|
||||
SEARCH_PREVIOUS: "Previous",
|
||||
|
||||
|
||||
|
||||
//settings.ts
|
||||
NOTEBOOKLM_LINK_ARIA: "Ask NotebookLM for help about the plugin. This model is pre-loaded with all my video transcripts, release notes and other helpful content. Chat with NotebookLM to explore my 250+ videos and the Excalidraw documentation.",
|
||||
NOTEBOOKLM_LINK_TEXT: "Learn the Plugin. Access the NotebookLM knowledgebase.",
|
||||
LINKS_BUGS_ARIA: "Report bugs and raise feature requsts on the plugin's GitHub page",
|
||||
LINKS_BUGS: "Report Bugs",
|
||||
LINKS_YT_ARIA: "Check out my YouTube channel to learn about Visual Thinking and Excalidraw",
|
||||
LINKS_YT: "Learn on YouTube",
|
||||
LINKS_DISCORD_ARIA: "Join the Visual Thinking Workshop Discord Server",
|
||||
LINKS_DISCORD: "Join the Community",
|
||||
LINKS_TWITTER: "Follow me",
|
||||
LINKS_VTW_ARIA: "Learn about Visual PKM, Excalidraw, Obsidian, ExcaliBrain and more",
|
||||
LINKS_VTW: "Join a Workshop",
|
||||
LINKS_BOOK_ARIA: "Read Sketch Your Mind, my book on Visual Thinking",
|
||||
LINKS_BOOK: "Read the Book",
|
||||
LINKS_WIKI: "Plugin Wiki",
|
||||
LINKS_WIKI_ARIA: "Explore the Excalidraw Plugin Wiki",
|
||||
|
||||
RELEASE_NOTES_NAME: "Display Release Notes after update",
|
||||
RELEASE_NOTES_DESC:
|
||||
"<b><u>Toggle ON:</u></b> Display release notes each time you update Excalidraw to a newer version.<br>" +
|
||||
@@ -203,17 +232,25 @@ export default {
|
||||
FOLDER_NAME: "Excalidraw folder (CAsE sEnsITive!)",
|
||||
FOLDER_DESC:
|
||||
"Default location for new drawings. If empty, drawings will be created in the Vault root.",
|
||||
CROP_SUFFIX_NAME: "Crop file suffix",
|
||||
CROP_SUFFIX_DESC:
|
||||
"The last part of the filename for new drawings created when cropping an image. " +
|
||||
"Leave empty if you don't need a suffix.",
|
||||
CROP_PREFIX_NAME: "Crop file prefix",
|
||||
CROP_PREFIX_DESC:
|
||||
"The first part of the filename for new drawings created when cropping an image. " +
|
||||
"If empty the default 'cropped_' will be used.",
|
||||
"Leave empty if you don't need a prefix.",
|
||||
ANNOTATE_SUFFIX_NAME: "Annotation file suffix",
|
||||
ANNOTATE_SUFFIX_DESC:
|
||||
"The last part of the filename for new drawings created when annotating an image. " +
|
||||
"Leave empty if you don't need a suffix.",
|
||||
ANNOTATE_PREFIX_NAME: "Annotation file prefix",
|
||||
ANNOTATE_PREFIX_DESC:
|
||||
"The first part of the filename for new drawings created when annotating an image. " +
|
||||
"If empty the default 'annotated_' will be used.",
|
||||
"Leave empty if you don't need a prefix.",
|
||||
ANNOTATE_PRESERVE_SIZE_NAME: "Preserve image size when annotating",
|
||||
ANNOTATE_PRESERVE_SIZE_DESC:
|
||||
"When annotating an image in markdown the replacment image link will include the width of the original image.",
|
||||
"When annotating an image in markdown the replacement image link will include the width of the original image.",
|
||||
CROP_FOLDER_NAME: "Crop file folder (CaSE senSItive!)",
|
||||
CROP_FOLDER_DESC:
|
||||
"Default location for new drawings created when cropping an image. If empty, drawings will be created following the Vault attachments settings.",
|
||||
@@ -233,7 +270,7 @@ export default {
|
||||
"Template.md, the setting would be: Excalidraw/Template.md (or just Excalidraw/Template - you may omit the .md file extension). " +
|
||||
"If you are using Excalidraw in compatibility mode, then your template must be a legacy Excalidraw file as well " +
|
||||
"such as Excalidraw/Template.excalidraw. <br><b>Template Folder:</b> You can also set a folder as your template. " +
|
||||
"In this case you will be prompted which tempalte to use when creating a new drawing.<br>" +
|
||||
"In this case you will be prompted which template to use when creating a new drawing.<br>" +
|
||||
"<b>Pro Tip:</b> If you are using the Obsidian Templater plugin, you can add Templater code to your different Excalidraw " +
|
||||
"templates to automate configuration of your drawings.",
|
||||
SCRIPT_FOLDER_NAME: "Excalidraw Automate script folder (CASE SeNSitiVE!)",
|
||||
@@ -247,6 +284,8 @@ export default {
|
||||
`While the OpenAI API is in beta, its use is strictly limited — as such we require you use your own API key. ` +
|
||||
`You can create an OpenAI account, add a small credit (5 USD minimum), and generate your own API key. ` +
|
||||
`Once API key is set, you can use the AI tools in Excalidraw.`,
|
||||
AI_ENABLED_NAME: "Enable AI features",
|
||||
AI_ENABLED_DESC: "You need to reopen Excalidraw for the changes to take effect.",
|
||||
AI_OPENAI_TOKEN_NAME: "OpenAI API key",
|
||||
AI_OPENAI_TOKEN_DESC:
|
||||
"You can get your OpenAI API key from your <a href='https://platform.openai.com/api-keys'>OpenAI account</a>.",
|
||||
@@ -343,7 +382,7 @@ FILENAME_HEAD: "Filename",
|
||||
LEFTHANDED_MODE_NAME: "Left-handed mode",
|
||||
LEFTHANDED_MODE_DESC:
|
||||
"Currently only has effect in tray-mode. If turned on, the tray will be on the right side." +
|
||||
"<br><b><u>Toggle ON:</u></b> Left-handed mode.<br><b><u>Toggle OFF:</u></b> Right-handed moded",
|
||||
"<br><b><u>Toggle ON:</u></b> Left-handed mode.<br><b><u>Toggle OFF:</u></b> Right-handed mode.",
|
||||
IFRAME_MATCH_THEME_NAME: "Markdown embeds to match Excalidraw theme",
|
||||
IFRAME_MATCH_THEME_DESC:
|
||||
"<b><u>Toggle ON:</u></b> Set this to true if for example you are using Obsidian in dark-mode but use excalidraw with a light background. " +
|
||||
@@ -369,6 +408,7 @@ FILENAME_HEAD: "Filename",
|
||||
DEFAULT_PEN_MODE_NAME: "Pen mode",
|
||||
DEFAULT_PEN_MODE_DESC:
|
||||
"Should pen mode be automatically enabled when opening Excalidraw?",
|
||||
ENABLE_DOUBLE_CLICK_TEXT_EDITING_NAME: "Enable double-click text create",
|
||||
DISABLE_DOUBLE_TAP_ERASER_NAME: "Enable double-tap eraser in pen mode",
|
||||
DISABLE_SINGLE_FINGER_PANNING_NAME: "Enable single-finger panning in pen mode",
|
||||
SHOW_PEN_MODE_FREEDRAW_CROSSHAIR_NAME: "Show (+) crosshair in pen mode",
|
||||
@@ -379,7 +419,8 @@ FILENAME_HEAD: "Filename",
|
||||
SHOW_DRAWING_OR_MD_IN_HOVER_PREVIEW_DESC:
|
||||
"...even if the file has the <b>excalidraw-open-md: true</b> frontmatter key.<br>" +
|
||||
"When this setting is off and the file is set to open in md by default, the hover preview will show the " +
|
||||
"markdown side of the document.",
|
||||
"markdown side of the document.<br>" +
|
||||
"Note: <b>excalidraw-open-md</b> is different from <b>excalidraw-embed-md</b>. If <b>excalidraw-embed-md</b> is set to true, the hover preview will always show the markdown side, regardless of this setting. To force image rendering when embedding, use <code>![[drawing#^as-image]]</code> in your markdown file.",
|
||||
SHOW_DRAWING_OR_MD_IN_READING_MODE_NAME: "Render as image when in markdown reading mode of an Excalidraw file",
|
||||
SHOW_DRAWING_OR_MD_IN_READING_MODE_DESC:
|
||||
"When you are in markdown reading mode (aka. reading the back side of the drawing) should the Excalidraw drawing be rendered as an image? " +
|
||||
@@ -396,7 +437,7 @@ FILENAME_HEAD: "Filename",
|
||||
"⚠️ You must close and reopen the Excalidraw/markdown file for changes to take effect. ⚠️",
|
||||
HOTKEY_OVERRIDE_HEAD: "Hotkey overrides",
|
||||
HOTKEY_OVERRIDE_DESC: `Some of the Excalidraw hotkeys such as <code>${labelCTRL()}+Enter</code> to edit text or <code>${labelCTRL()}+K</code> to create an element link ` +
|
||||
"conflict with Obsidian hotkey settings. The hotkey combinations you add below will override Obsidian's hotkey settings while useing Excalidraw, thus " +
|
||||
"conflict with Obsidian hotkey settings. The hotkey combinations you add below will override Obsidian's hotkey settings while using Excalidraw, thus " +
|
||||
`you can add <code>${labelCTRL()}+G</code> if you want to default to Group Object in Excalidraw instead of opening Graph View.`,
|
||||
THEME_HEAD: "Theme and styling",
|
||||
ZOOM_HEAD: "Zoom",
|
||||
@@ -427,6 +468,10 @@ FILENAME_HEAD: "Filename",
|
||||
GRID_OPACITY_NAME: "Grid opacity",
|
||||
GRID_OPACITY_DESC: "Grid opacity will also control the opacity of the binding box when binding an arrow to an element.<br>" +
|
||||
"Set the opacity of the grid. 0 is transparent, 100 is opaque.",
|
||||
GRID_DIRECTION_NAME: "Grid direction",
|
||||
GRID_DIRECTION_DESC: "The first toggle shows/hides the horizontal grid, the second toggle shows/hides the vertical grid.",
|
||||
GRID_HORIZONTAL: "Render horizontal grid",
|
||||
GRID_VERTICAL: "Render vertical grid",
|
||||
LASER_HEAD: "Laser pointer",
|
||||
LASER_COLOR: "Laser pointer color",
|
||||
LASER_DECAY_TIME_NAME: "Laser pointer decay time",
|
||||
@@ -456,7 +501,7 @@ FILENAME_HEAD: "Filename",
|
||||
|
||||
FOCUS_ON_EXISTING_TAB_NAME: "Focus on Existing Tab",
|
||||
FOCUS_ON_EXISTING_TAB_DESC: "When opening a link, Excalidraw will focus on the existing tab if the file is already open. " +
|
||||
"Enabling this setting overrides 'Reuse Adjacent Pane' when the file is already open.",
|
||||
"Enabling this setting overrides 'Reuse Adjacent Pane' when the file is already open except for the 'Open the back-of-the-note of the selected excalidraw image' command palette action.",
|
||||
SECOND_ORDER_LINKS_NAME: "Show second-order links",
|
||||
SECOND_ORDER_LINKS_DESC: "Show links when clicking on a link in Excalidraw. Second-order link are backlinks pointing to the link being clicked. " +
|
||||
"When using image icons to connect similar notes, second order links allow you to get to related notes in one click instead of two. " +
|
||||
@@ -527,7 +572,7 @@ FILENAME_HEAD: "Filename",
|
||||
"Use the <code>http://iframely.server.crestify.com/iframely?url=</code> to get title of page when dropping a link into Excalidraw",
|
||||
PDF_TO_IMAGE: "PDF to Image",
|
||||
PDF_TO_IMAGE_SCALE_NAME: "PDF to Image conversion scale",
|
||||
PDF_TO_IMAGE_SCALE_DESC: "Sets the resolution of the image that is generated from the PDF page. Higher resolution will result in bigger images in memory and consequently a higher load on your system (slower performance), but sharper imagee. " +
|
||||
PDF_TO_IMAGE_SCALE_DESC: "Sets the resolution of the image that is generated from the PDF page. Higher resolution will result in bigger images in memory and consequently a higher load on your system (slower performance), but sharper image. " +
|
||||
"Additionally, if you want to copy PDF pages (as images) to Excalidraw.com, the bigger image size may result in exceeding the 2MB limit on Excalidraw.com.",
|
||||
EMBED_TOEXCALIDRAW_HEAD: "Embed files into Excalidraw",
|
||||
EMBED_TOEXCALIDRAW_DESC: "In the Embed Files section of Excalidraw Settings, you can configure how various files are embedded into Excalidraw. This includes options for embedding interactive markdown files, PDFs, and markdown files as images.",
|
||||
@@ -687,7 +732,7 @@ FILENAME_HEAD: "Filename",
|
||||
DUMMY_TEXT_ELEMENT_LINT_SUPPORT_NAME: "Linter compatibility",
|
||||
DUMMY_TEXT_ELEMENT_LINT_SUPPORT_DESC: "Excalidraw is sensitive to the file structure below <code># Excalidraw Data</code>. Automatic linting of documents can create errors in Excalidraw Data. " +
|
||||
"While I've made some effort to make the data loading resilient to " +
|
||||
"lint changes, this solution is not foolproof.<br><mark>The best is to avoid liniting or otherwise automatically changing Excalidraw documents using different plugins.</mark><br>" +
|
||||
"lint changes, this solution is not foolproof.<br><mark>The best is to avoid linting or otherwise automatically changing Excalidraw documents using different plugins.</mark><br>" +
|
||||
"Use this setting if for good reasons you have decided to ignore my recommendation and configured linting of Excalidraw files.<br> " +
|
||||
"The <code>## Text Elements</code> section is sensitive to empty lines. A common linting approach is to add an empty line after section headings. In case of Excalidraw this will break/change the first text element in your drawing. " +
|
||||
"To overcome this, you can enable this setting. When enabled, Excalidraw will add a dummy element to the beginning of <code>## Text Elements</code> that the linter can safely modify." ,
|
||||
@@ -722,6 +767,8 @@ FILENAME_HEAD: "Filename",
|
||||
"restart Obsidian after closing settings, for this change to take effect.",
|
||||
LATEX_DEFAULT_NAME: "Default LaTeX formula for new equations",
|
||||
LATEX_DEFAULT_DESC: "Leave empty if you don't want a default formula. You can add default formatting here such as <code>\\color{white}</code>.",
|
||||
LATEX_PREAMBLE_NAME: "LaTeX preamble file (CasE SEnSiTivE!)",
|
||||
LATEX_PREAMBLE_DESC: "Full filepath to the preamble file, leave empty for default. If the file doesn't exist this option will be ignored.<br><strong>Important:</strong> Requires obsidian reload after change to take effect!",
|
||||
NONSTANDARD_HEAD: "Non-Excalidraw.com supported features",
|
||||
NONSTANDARD_DESC: `These settings in the "Non-Excalidraw.com Supported Features" section provide customization options beyond the default Excalidraw.com features. These features are not available on excalidraw.com. When exporting the drawing to Excalidraw.com these features will appear different.
|
||||
You can configure the number of custom pens displayed next to the Obsidian Menu on the canvas, allowing you to choose from a range of options. Additionally, you can enable a local font option, which adds a local font to the list of fonts on the element properties panel for text elements. `,
|
||||
@@ -740,7 +787,7 @@ FILENAME_HEAD: "Filename",
|
||||
"ExcalidrawAutomate is a scripting and automation API for Excalidraw. Unfortunately, the documentation of the API is sparse. " +
|
||||
"I recommend reading the <a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/docs/API/ExcalidrawAutomate.d.ts'>ExcalidrawAutomate.d.ts</a> file, " +
|
||||
"visiting the <a href='https://zsviczian.github.io/obsidian-excalidraw-plugin/'>ExcalidrawAutomate How-to</a> page - though the information " +
|
||||
"here has not been updated for a long while -, and finally to enable the field suggester below. The field suggester will show you the available " +
|
||||
"here has not been updated for a long while -, and finally to enable the field suggester below. The field suggester will show you the available " +
|
||||
"functions, their parameters and short description as you type. The field suggester is the most up-to-date documentation of the API.",
|
||||
FIELD_SUGGESTER_NAME: "Enable Field Suggester",
|
||||
FIELD_SUGGESTER_DESC:
|
||||
@@ -802,10 +849,10 @@ FILENAME_HEAD: "Filename",
|
||||
<strong>Note:</strong> If you're using Obsidian Sync and want to synchronize these font files across your devices, ensure that Obsidian Sync is set to synchronize "All other file types".`,
|
||||
LOAD_CHINESE_FONTS_NAME: "Load Chinese fonts from file at startup",
|
||||
LOAD_JAPANESE_FONTS_NAME: "Load Japanese fonts from file at startup",
|
||||
LOAD_KOREAN_FONTS_NAME: "Load Korean fonts frome file at startup",
|
||||
LOAD_KOREAN_FONTS_NAME: "Load Korean fonts from file at startup",
|
||||
SCRIPT_SETTINGS_HEAD: "Settings for installed Scripts",
|
||||
SCRIPT_SETTINGS_DESC: "Some of the Excalidraw Automate Scripts include settings. Settings are organized by script. Settings will only become visible in this list after you have executed the newly downloaded script once.",
|
||||
TASKBONE_HEAD: "Taskbone Optical Character Recogntion",
|
||||
TASKBONE_HEAD: "Taskbone Optical Character Recognition",
|
||||
TASKBONE_DESC: "This is an experimental integration of optical character recognition into Excalidraw. Please note, that taskbone is an independent external service not provided by Excalidraw, nor the Excalidraw-Obsidian plugin project. " +
|
||||
"The OCR service will grab legible text from freedraw lines and embedded pictures on your canvas and place the recognized text in the frontmatter of your drawing as well as onto clipboard. " +
|
||||
"Having the text in the frontmatter will enable you to search in Obsidian for the text contents of these. " +
|
||||
@@ -814,7 +861,7 @@ FILENAME_HEAD: "Filename",
|
||||
TASKBONE_ENABLE_DESC: "By enabling this service your agree to the Taskbone <a href='https://www.taskbone.com/legal/terms/' target='_blank'>Terms and Conditions</a> and the " +
|
||||
"<a href='https://www.taskbone.com/legal/privacy/' target='_blank'>Privacy Policy</a>.",
|
||||
TASKBONE_APIKEY_NAME: "Taskbone API Key",
|
||||
TASKBONE_APIKEY_DESC: "Taskbone offers a free service with a reasonable number of scans per month. If you want to use this feature more frequently, or you want to supoprt " +
|
||||
TASKBONE_APIKEY_DESC: "Taskbone offers a free service with a reasonable number of scans per month. If you want to use this feature more frequently, or you want to support " +
|
||||
"the developer of Taskbone (as you can imagine, there is no such thing as 'free', providing this awesome OCR service costs some money to the developer of Taskbone), you can " +
|
||||
"purchase a paid API key from <a href='https://www.taskbone.com/' target='_blank'>taskbone.com</a>. In case you have purchased a key, simply overwrite this auto generated free-tier API-key with your paid key.",
|
||||
|
||||
@@ -859,7 +906,7 @@ FILENAME_HEAD: "Filename",
|
||||
|
||||
//ExcalidrawData.ts
|
||||
LOAD_FROM_BACKUP: "Excalidraw file was corrupted. Loading from backup file.",
|
||||
FONT_LOAD_SLOW: "Loading Fonts...\n\n This is taking longer than expected. If this delay occurs regulary then you may download the fonts locally to your Vault. \n\n" +
|
||||
FONT_LOAD_SLOW: "Loading Fonts...\n\n This is taking longer than expected. If this delay occurs regularly then you may download the fonts locally to your Vault. \n\n" +
|
||||
"(click=dismiss, right-click=Info)",
|
||||
FONT_INFO_TITLE: "Starting v2.5.3 fonts load from the Internet",
|
||||
FONT_INFO_DETAILED: `
|
||||
@@ -901,8 +948,12 @@ FILENAME_HEAD: "Filename",
|
||||
|
||||
//IFrameActionsMenu.tsx
|
||||
NARROW_TO_HEADING: "Narrow to heading...",
|
||||
PIN_VIEW: "Pin view",
|
||||
DO_NOT_PIN_VIEW: "Do not pin view",
|
||||
NARROW_TO_BLOCK: "Narrow to block...",
|
||||
SHOW_ENTIRE_FILE: "Show entire file",
|
||||
SELECT_SECTION: "Select section from document",
|
||||
SELECT_VIEW: "Select view from base",
|
||||
ZOOM_TO_FIT: "Zoom to fit",
|
||||
RELOAD: "Reload original link",
|
||||
OPEN_IN_BROWSER: "Open current link in browser",
|
||||
@@ -952,6 +1003,7 @@ FILENAME_HEAD: "Filename",
|
||||
PROMPT_BUTTON_INSERT_SPACE: "Insert space",
|
||||
PROMPT_BUTTON_INSERT_LINK: "Insert markdown link to file",
|
||||
PROMPT_BUTTON_UPPERCASE: "Uppercase",
|
||||
PROMPT_BUTTON_SPECIAL_CHARS: "Special Characters",
|
||||
PROMPT_SELECT_TEMPLATE: "Select a template",
|
||||
|
||||
//ModifierKeySettings
|
||||
@@ -981,6 +1033,7 @@ FILENAME_HEAD: "Filename",
|
||||
|
||||
//Utils.ts
|
||||
UPDATE_AVAILABLE: `A newer version of Excalidraw is available in Community Plugins.\n\nYou are using ${PLUGIN_VERSION}.\nThe latest is`,
|
||||
SCRIPT_UPDATES_AVAILABLE: `Script updates available - check the script store.\n\n${DEVICE.isDesktop ? `This message is available in console.log (${DEVICE.isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i"})\n\n` : ""}If you have organized scripts into subfolders under the script store folder and have multiple copies of the same script, you may need to clean up unused versions to clear this alert. For private copies of scripts that should not be updated, store them outside the script store folder.`,
|
||||
ERROR_PNG_TOO_LARGE: "Error exporting PNG - PNG too large, try a smaller resolution",
|
||||
|
||||
//modifierkeyHelper.ts
|
||||
@@ -1050,6 +1103,12 @@ FILENAME_HEAD: "Filename",
|
||||
EXPORTDIALOG_ORIENTATION_LANDSCAPE: "Landscape",
|
||||
EXPORTDIALOG_PDF_FIT_TO_PAGE: "Page Fitting",
|
||||
EXPORTDIALOG_PDF_FIT_OPTION: "Fit to page",
|
||||
EXPORTDIALOG_PDF_FIT_2_OPTION: "Fit to max 2-pages",
|
||||
EXPORTDIALOG_PDF_FIT_4_OPTION: "Fit to max 4-pages",
|
||||
EXPORTDIALOG_PDF_FIT_6_OPTION: "Fit to max 6-pages",
|
||||
EXPORTDIALOG_PDF_FIT_8_OPTION: "Fit to max 8-pages",
|
||||
EXPORTDIALOG_PDF_FIT_12_OPTION: "Fit to max 12-pages",
|
||||
EXPORTDIALOG_PDF_FIT_16_OPTION: "Fit to max 16-pages",
|
||||
EXPORTDIALOG_PDF_SCALE_OPTION: "Use image scale (may span multiple pages)",
|
||||
EXPORTDIALOG_PDF_PAPER_COLOR: "Paper Color",
|
||||
EXPORTDIALOG_PDF_PAPER_WHITE: "White",
|
||||
@@ -1057,6 +1116,8 @@ FILENAME_HEAD: "Filename",
|
||||
EXPORTDIALOG_PDF_PAPER_CUSTOM: "Custom color",
|
||||
EXPORTDIALOG_PDF_ALIGNMENT: "Position on Page",
|
||||
EXPORTDIALOG_PDF_ALIGN_CENTER: "Center",
|
||||
EXPORTDIALOG_PDF_ALIGN_CENTER_LEFT: "Center Left",
|
||||
EXPORTDIALOG_PDF_ALIGN_CENTER_RIGHT: "Center Right",
|
||||
EXPORTDIALOG_PDF_ALIGN_TOP_LEFT: "Top Left",
|
||||
EXPORTDIALOG_PDF_ALIGN_TOP_CENTER: "Top Center",
|
||||
EXPORTDIALOG_PDF_ALIGN_TOP_RIGHT: "Top Right",
|
||||
@@ -1078,5 +1139,21 @@ FILENAME_HEAD: "Filename",
|
||||
EXPORTDIALOG_PNGTOCLIPBOARD : "PNG to Clipboard",
|
||||
EXPORTDIALOG_SVGTOCLIPBOARD : "SVG to Clipboard",
|
||||
EXPORTDIALOG_PDF: "Export PDF",
|
||||
EXPORTDIALOG_PDFTOVAULT: "PDF to Vault",
|
||||
|
||||
EXPORTDIALOG_PDF_PROGRESS_NOTICE: "Exporting PDF. If this image is large, it may take a while.",
|
||||
EXPORTDIALOG_PDF_PROGRESS_DONE: "Export complete",
|
||||
EXPORTDIALOG_PDF_PROGRESS_ERROR: "Error exporting PDF, check developer console for details",
|
||||
|
||||
// Screenshot tab
|
||||
EXPORTDIALOG_NOT_AVAILALBE: "Sorry, this feature is only available when the drawing is open in the main Obsidian workspace.",
|
||||
EXPORTDIALOG_TAB_SCREENSHOT: "Screenshot",
|
||||
EXPORTDIALOG_SCREENSHOT_DESC: "Screenshots will include embeddables such as markdown pages, YouTube, websites, etc. They are only available on desktop, cannot be automatically exported, and only support PNG format.",
|
||||
SCREENSHOT_DESKTOP_ONLY: "Screenshot feature is only available on desktop",
|
||||
SCREENSHOT_FILE_SUCCESS: "Screenshot saved to vault",
|
||||
SCREENSHOT_CLIPBOARD_SUCCESS: "Screenshot copied to clipboard",
|
||||
SCREENSHOT_CLIPBOARD_ERROR: "Failed to copy screenshot to clipboard: ",
|
||||
SCREENSHOT_ERROR: "Error capturing screenshot - see console log",
|
||||
|
||||
//exportUtils.ts
|
||||
PDF_EXPORT_DESKTOP_ONLY: "PDF export is only available on desktop",
|
||||
};
|
||||
|
||||
@@ -30,7 +30,7 @@ export default {
|
||||
"脚本已是最新 - 点击重新安装",
|
||||
OPEN_AS_EXCALIDRAW: "打开为 Excalidraw 绘图",
|
||||
TOGGLE_MODE: "在 Excalidraw 和 Markdown 模式之间切换",
|
||||
DUPLICATE_IMAGE : "复制选定的图像,并分配一个不同的图像 ID",
|
||||
DUPLICATE_IMAGE: "复制选定的图像,并分配一个不同的图像 ID",
|
||||
CONVERT_NOTE_TO_EXCALIDRAW: "转换:空白 Markdown 文档 => Excalidraw 绘图文件",
|
||||
CONVERT_EXCALIDRAW: "转换: *.excalidraw => *.md",
|
||||
CREATE_NEW: "新建绘图文件",
|
||||
@@ -44,7 +44,7 @@ export default {
|
||||
TRANSCLUDE_MOST_RECENT: "嵌入最近编辑过的绘图(形如 ![[drawing]])到当前 Markdown 文档中",
|
||||
TOGGLE_LEFTHANDED_MODE: "切换为左手模式",
|
||||
TOGGLE_SPLASHSCREEN: "在新绘图中显示启动画面",
|
||||
FLIP_IMAGE: "打开当前所选 excalidraw 图像的“背景笔记”",
|
||||
FLIP_IMAGE: "在弹出窗口中打开当前所选图像的“背景笔记”",
|
||||
NEW_IN_NEW_PANE: "新建绘图 - 于新面板",
|
||||
NEW_IN_NEW_TAB: "新建绘图 - 于新页签",
|
||||
NEW_IN_ACTIVE_PANE: "新建绘图 - 于当前面板",
|
||||
@@ -58,8 +58,8 @@ export default {
|
||||
NEW_IN_POPOUT_WINDOW_EMBED: "新建绘图 - 于新窗口 - 并将其嵌入(形如 ![[drawing]])到当前 Markdown 文档中",
|
||||
TOGGLE_LOCK: "文本元素:原文模式(RAW)⟺ 预览模式(PREVIEW)",
|
||||
DELETE_FILE: "从库中删除所选图像(或以图像形式嵌入绘图中的 Markdown)的源文件",
|
||||
COPY_ELEMENT_LINK: "复制所选元素的链接(形如 [[file#^id]]])",
|
||||
COPY_DRAWING_LINK: "复制绘图的嵌入链接(形如 ![[darwing]])",
|
||||
COPY_ELEMENT_LINK: "复制所选元素的链接(形如 [[file#^id]])",
|
||||
COPY_DRAWING_LINK: "复制绘图的嵌入链接(形如 ![[drawing]])",
|
||||
INSERT_LINK_TO_ELEMENT:
|
||||
`复制所选元素为内部链接(形如 [[file#^id]] )。\n按住 ${labelCTRL()} 可复制元素所在分组为内部链接(形如 [[file#^group=id]] )。\n按住 ${labelSHIFT()} 可复制所选元素所在区域为内部链接(形如 [[file#^area=id]] )。`,
|
||||
INSERT_LINK_TO_ELEMENT_GROUP:
|
||||
@@ -91,15 +91,15 @@ export default {
|
||||
`插入 LaTeX 公式(例如:\\binom{n}{k} = \\frac{n!}{k!(n-k)!})。`,
|
||||
ENTER_LATEX: "输入 LaTeX 表达式",
|
||||
READ_RELEASE_NOTES: "阅读本插件的更新说明",
|
||||
RUN_OCR: "OCR 完整画布:识别涂鸦和图片里的文本并复制到剪贴板和文档属性中",
|
||||
RERUN_OCR: "重新运行 OCR 完整画笔:识别涂鸦和图片里的文本并复制到剪贴板和文档属性中",
|
||||
RUN_OCR: "OCR 整个画布:识别涂鸦和图片里的文本并复制到剪贴板和文档属性中",
|
||||
RERUN_OCR: "重新 OCR 整个画布:识别涂鸦和图片里的文本并复制到剪贴板和文档属性中",
|
||||
RUN_OCR_ELEMENTS: "OCR 选中的元素:识别涂鸦和图片里的文本并复制到剪贴板",
|
||||
TRAY_MODE: "绘图工具属性页:面板模式 ⟺ 托盘模式",
|
||||
SEARCH: "搜索文本",
|
||||
CROP_PAGE: "对所选页面裁剪并添加蒙版",
|
||||
CROP_IMAGE: "对图片裁剪并添加蒙版",
|
||||
ANNOTATE_IMAGE : "在 Excalidraw 中标注图像",
|
||||
INSERT_ACTIVE_PDF_PAGE_AS_IMAGE: "将当前激活的的 PDF 页面作为图片插入",
|
||||
INSERT_ACTIVE_PDF_PAGE_AS_IMAGE: "将当前激活的 PDF 页面作为图片插入",
|
||||
RESET_IMG_TO_100: "重置图像元素的尺寸为 100%",
|
||||
RESET_IMG_ASPECT_RATIO: "重置所选图像元素的纵横比",
|
||||
TEMPORARY_DISABLE_AUTOSAVE: "临时禁用自动保存功能,直到本次 Obsidian 退出(小白慎用!)",
|
||||
@@ -158,7 +158,11 @@ export default {
|
||||
CONVERT_FILE: "转换为新格式",
|
||||
BACKUP_AVAILABLE: "加载绘图文件时出错,可能是由于 Obsidian 在上次保存时意外退出了(手机上更容易发生这种意外)。<br><br><b>好消息:</b>这台设备上存在备份。您是否想要恢复本设备上的备份?<br><br>(我建议您先尝试在最近使用过的其他设备上打开该绘图,以检查是否有更新的备份。)",
|
||||
BACKUP_RESTORED: "已恢复备份",
|
||||
CACHE_NOT_READY: "抱歉,加载绘图文件时出错。<br><br><mark>现在有耐心,将来更省心。</mark><br><br>该插件有备份机制,但您似乎刚刚打开 Obsidian,需要等待一分钟或更长的时间来读取缓存。缓存读取完毕时,您将会在右上角收到提示。<br><br>请点击 OK 并耐心等待缓存,或者选择点击取消后手动修复你的文件。<br>",
|
||||
BACKUP_SAVE_AS_FILE : "此绘图为空。存在一个非空的备份。您是否希望将其恢复为新文件并在新标签页中打开?" ,
|
||||
BACKUP_SAVE : "恢复" ,
|
||||
BACKUP_DELETE : "删除备份" ,
|
||||
BACKUP_CANCEL : "取消" ,
|
||||
CACHE_NOT_READY : "很抱歉给您带来不便,加载文件时发生了错误。<br><br><mark>稍作等待可能会节省您大量时间……</mark><br><br>插件有一个备份缓存,但似乎您刚刚启动了 Obsidian。初始化备份缓存可能需要一些时间,通常取决于设备性能,可能需要一分钟或更长时间。当缓存初始化完成时,您会在右上角收到通知。<br><br>请按“确定”尝试重新加载文件,并检查缓存是否已完成初始化。如果在此消息后看到一个完全空白的文件,我建议等待备份缓存准备就绪后再继续操作。或者,您也可以选择“取消”以手动修复您的文件。<br>" ,
|
||||
OBSIDIAN_TOOLS_PANEL: "Obsidian 工具面板",
|
||||
ERROR_SAVING_IMAGE: "获取图像时发生未知错误。可能是由于某种原因,图像不可用或拒绝了 Obsidian 的获取请求。",
|
||||
WARNING_PASTING_ELEMENT_AS_TEXT: "你不能将 Excalidraw 元素粘贴为文本元素!",
|
||||
@@ -188,7 +192,32 @@ export default {
|
||||
SAVE_IS_TAKING_LONG: "保存您之前的文件花费的时间较长,请稍候...",
|
||||
SAVE_IS_TAKING_VERY_LONG: "为了更好的性能,请考虑将大型绘图拆分成几个较小的文件。",
|
||||
|
||||
//ContentSearcher.ts
|
||||
SEARCH_COPIED_TO_CLIPBOARD: "Markdown 已复制到剪贴板",
|
||||
SEARCH_COPY_TO_CLIPBOARD_ARIA: "将整个对话框复制为 Markdown 到剪贴板。非常适合搭配 ChatGPT 等工具进行搜索和理解。",
|
||||
SEARCH_SHOWHIDE_ARIA : "显示/隐藏搜索栏" ,
|
||||
SEARCH_NEXT: "下一个",
|
||||
SEARCH_PREVIOUS: "上一个",
|
||||
|
||||
|
||||
|
||||
//settings.ts
|
||||
NOTEBOOKLM_LINK_ARIA : "向 NotebookLM 咨询有关插件的帮助。此模型已预加载我的所有视频转录、发布说明以及其他有用内容。与 NotebookLM 聊天,探索我的 250+ 视频以及 Excalidraw 文档。" ,
|
||||
NOTEBOOKLM_LINK_TEXT : "了解插件。访问 NotebookLM 知识库。" ,
|
||||
LINKS_BUGS_ARIA: "在插件的 GitHub 页面报告错误和提交功能请求",
|
||||
LINKS_BUGS: "报告错误",
|
||||
LINKS_YT_ARIA: "访问我的 YouTube 频道学习视觉思维和 Excalidraw",
|
||||
LINKS_YT: "在 YouTube 学习",
|
||||
LINKS_DISCORD_ARIA: "加入视觉思维研讨会 Discord 服务器",
|
||||
LINKS_DISCORD: "加入社区",
|
||||
LINKS_TWITTER: "关注我",
|
||||
LINKS_VTW_ARIA: "了解视觉知识管理、Excalidraw、Obsidian、ExcaliBrain 等内容",
|
||||
LINKS_VTW: "参加研讨会",
|
||||
LINKS_BOOK_ARIA: "阅读我的视觉思维著作《Sketch Your Mind》",
|
||||
LINKS_BOOK: "阅读书籍",
|
||||
LINKS_WIKI : "插件 Wiki" ,
|
||||
LINKS_WIKI_ARIA : "探索 Excalidraw 插件 Wiki" ,
|
||||
|
||||
RELEASE_NOTES_NAME: "显示更新说明",
|
||||
RELEASE_NOTES_DESC:
|
||||
"<b>开启:</b>每次更新本插件后,显示最新发行版本的说明。<br>" +
|
||||
@@ -203,14 +232,22 @@ export default {
|
||||
FOLDER_NAME: "Excalidraw 文件夹(區分大小寫!)",
|
||||
FOLDER_DESC:
|
||||
"新绘图的默认存储路径。若为空,将在库的根目录中创建新绘图。",
|
||||
CROP_SUFFIX_NAME : "裁剪文件后缀" ,
|
||||
CROP_SUFFIX_DESC :
|
||||
"为裁剪图像时创建的新图纸文件名的最后部分。" +
|
||||
"如果不需要后缀,请留空。" ,
|
||||
CROP_PREFIX_NAME: "剪贴文件的前缀",
|
||||
CROP_PREFIX_DESC:
|
||||
"当剪贴图片进来时保存的文件名的前缀。 " +
|
||||
"留空则使用 'cropped_'",
|
||||
"如果不需要前缀,请留空。" ,
|
||||
ANNOTATE_SUFFIX_NAME : "注释文件后缀" ,
|
||||
ANNOTATE_SUFFIX_DESC :
|
||||
"为注释图像时创建的新绘图文件名的最后部分。" +
|
||||
"如果不需要后缀,请留空。" ,
|
||||
ANNOTATE_PREFIX_NAME: "标注文件的前缀",
|
||||
ANNOTATE_PREFIX_DESC:
|
||||
"在标注图像时创建新绘图的文件名的第一部分。" +
|
||||
"留空则使用'annotated_'",
|
||||
"如果不需要前缀,请留空。" ,
|
||||
ANNOTATE_PRESERVE_SIZE_NAME: "在标注时保留图像尺寸",
|
||||
ANNOTATE_PRESERVE_SIZE_DESC:
|
||||
"当在 Markdown 中标注图像时,替换后的图像链接将包含原始图像的宽度。",
|
||||
@@ -236,7 +273,7 @@ export default {
|
||||
"在这种情况下,创建新绘图时将提示您选择使用哪个模板。<br>" +
|
||||
"<b>专业提示:</b> 如果您正在使用 Obsidian Templater 插件,您可以将 Templater 代码添加到不同的" +
|
||||
"Excalidraw 模板中,以自动配置您的绘图",
|
||||
SCRIPT_FOLDER_NAME: "Excalidraw 自动化脚本的文件夹(大小写敏感!)",
|
||||
SCRIPT_FOLDER_NAME: "Excalidraw 自动化脚本的文件夹(區分大小寫!)",
|
||||
SCRIPT_FOLDER_DESC:
|
||||
"此文件夹用于存放 Excalidraw 自动化脚本。" +
|
||||
"您可以在 Obsidian 命令面板中执行这些脚本," +
|
||||
@@ -247,6 +284,8 @@ export default {
|
||||
`目前 OpenAI API 还处于测试中,您需要在自己的。` +
|
||||
`OpenAI 账户中充值至少 5 美元后才能生成 API key,` +
|
||||
`然后就可以在 Excalidraw 中配置并使用 AI。`,
|
||||
AI_ENABLED_NAME : "启用 AI 功能" ,
|
||||
AI_ENABLED_DESC : "您需要重新打开 Excalidraw 才能使更改生效。" ,
|
||||
AI_OPENAI_TOKEN_NAME: "OpenAI API key",
|
||||
AI_OPENAI_TOKEN_DESC:
|
||||
"您可以访问您的<a href='https://platform.openai.com/api-keys'> OpenAI 账户</a>来获取自己的 OpenAI API key。",
|
||||
@@ -369,13 +408,14 @@ FILENAME_HEAD: "文件名",
|
||||
DEFAULT_PEN_MODE_NAME: "触控笔模式(Pen mode)",
|
||||
DEFAULT_PEN_MODE_DESC:
|
||||
"打开绘图时,是否自动开启触控笔模式?",
|
||||
ENABLE_DOUBLE_CLICK_TEXT_EDITING_NAME : "启用双击文本创建",
|
||||
DISABLE_DOUBLE_TAP_ERASER_NAME: "启用手写模式下的双击橡皮擦功能",
|
||||
DISABLE_SINGLE_FINGER_PANNING_NAME: "启用手写模式下的单指平移功能",
|
||||
SHOW_PEN_MODE_FREEDRAW_CROSSHAIR_NAME: "在触控笔模式下显示十字准星(+)",
|
||||
SHOW_PEN_MODE_FREEDRAW_CROSSHAIR_DESC:
|
||||
"在触控笔模式下使用涂鸦功能会显示十字准星 <b><u>打开:</u></b> 显示 <b><u>关闭:</u></b> 隐藏<br>"+
|
||||
"效果取决于设备。十字准星通常在绘图板、MS Surface 上可见。但在 iOS 上不可见。",
|
||||
SHOW_DRAWING_OR_MD_IN_HOVER_PREVIEW_NAME: "在鼠标悬停预览时将 Excalidraw 文件渲染文图片",
|
||||
SHOW_DRAWING_OR_MD_IN_HOVER_PREVIEW_NAME: "在鼠标悬停预览时将 Excalidraw 文件渲染为图片",
|
||||
SHOW_DRAWING_OR_MD_IN_HOVER_PREVIEW_DESC:
|
||||
"...即使文件具有 `<b>excalidraw-open-md: true</b>` frontmatter 属性。<br>" +
|
||||
"当此设置关闭且文件默认设置为以 md 格式打开时,悬停预览将显示文档的 Markdown 部分(背景笔记)。" +
|
||||
@@ -386,13 +426,14 @@ FILENAME_HEAD: "文件名",
|
||||
"此设置不会影响您在 Excalidraw 模式下的绘图显示,或者在将绘图嵌入 Markdown 文档时,或在渲染悬停预览时。<br><ul>" +
|
||||
"<li>请参阅下面‘嵌入和导出’部分的 <a href='#"+TAG_PDFEXPORT+"'>PDF 导出</a> 相关设置。</li></ul><br>" +
|
||||
"您必须关闭当前的 Excalidraw/Markdown 文件并重新打开,以使此更改生效。",
|
||||
SHOW_DRAWING_OR_MD_IN_EXPORTPDF_NAME: "在将 Excalidraw 文件导出为 PDF 时将文件渲染为图像",
|
||||
SHOW_DRAWING_OR_MD_IN_EXPORTPDF_NAME : "在 Obsidian 中导出为 PDF 格式时将 Excalidraw 渲染为图像" ,
|
||||
SHOW_DRAWING_OR_MD_IN_EXPORTPDF_DESC:
|
||||
"处于 Markdown 视图模式时,此设置控制 Excalidraw 在使用 Obsidian 的 <b>导出为 PDF</b> 功能时,将 Excalidraw 文件导出为 PDF 的行为。<br>" +
|
||||
"<ul><li>当 <b>启用</b> 时,PDF 将仅显示 Excalidraw 绘图;</li>" +
|
||||
"<li>当 <b>禁用</b> 时,PDF 将显示文档的 Markdown 部分(背景笔记)。</li></ul>" +
|
||||
"请参阅上面‘外观和行为’部分的 <<a href='#"+TAG_MDREADINGMODE+"'>>Markdown 阅读模式</a> 相关设置。" +
|
||||
"⚠️ 注意,您必须关闭当前的 Excalidraw/Markdown 文件并重新打开,以使此更改生效。⚠️",
|
||||
"此设置控制在使用 Obsidian 内置的<b>导出为 PDF</b>功能,如何将 Excalidraw 文件导出为 PDF。<br>" +
|
||||
"<ul><li><b>启用:</b>PDF 将包含图像格式的 Excalidraw 绘图。</li>" +
|
||||
"<li><b>禁用:</b>PDF 将包含作为文本的 Markdown 内容。</li></ul>" +
|
||||
"注意:此设置不会影响 Excalidraw 本身的 PDF 导出功能。<br>" +
|
||||
"请参阅上方“外观和行为”部分中与<a href='#" + TAG_MDREADINGMODE + "'>Markdown 阅读模式</a>相关的其他设置。<br>" +
|
||||
"⚠️ 您必须关闭并重新打开 Excalidraw/Markdown 文件,设置更改才会生效。⚠️",
|
||||
HOTKEY_OVERRIDE_HEAD: "热键覆盖",
|
||||
HOTKEY_OVERRIDE_DESC: `一些 Excalidraw 的热键,例如 ${labelCTRL()}+Enter 用于编辑文本,或 ${labelCTRL()}+K 用于创建元素链接。` +
|
||||
"与 Obsidian 的热键设置发生冲突。您在下面添加的热键组合将在使用 Excalidraw 时覆盖 Obsidian 的热键设置," +
|
||||
@@ -426,6 +467,10 @@ FILENAME_HEAD: "文件名",
|
||||
GRID_OPACITY_NAME: "网格透明度",
|
||||
GRID_OPACITY_DESC: "网格透明度还将控制将箭头绑定到元素时绑定框的透明度。<br>"+
|
||||
"设置网格的不透明度。 0 表示完全透明,100 表示完全不透明。",
|
||||
GRID_DIRECTION_NAME : "网格方向" ,
|
||||
GRID_DIRECTION_DESC : "第一个开关显示/隐藏水平网格,第二个开关显示/隐藏垂直网格。" ,
|
||||
GRID_HORIZONTAL : "渲染水平网格" ,
|
||||
GRID_VERTICAL : "渲染垂直网格" ,
|
||||
LASER_HEAD: "激光笔工具(更多工具 > 激光笔)",
|
||||
LASER_COLOR: "激光笔颜色",
|
||||
LASER_DECAY_TIME_NAME: "激光笔消失时间",
|
||||
@@ -455,7 +500,7 @@ FILENAME_HEAD: "文件名",
|
||||
|
||||
FOCUS_ON_EXISTING_TAB_NAME: "聚焦于当前标签页",
|
||||
FOCUS_ON_EXISTING_TAB_DESC: "当打开一个链接时,如果该文件已经打开,Excalidraw 将会聚焦到现有的标签页上 " +
|
||||
"启用这个设置会在文件已经打开的情况下覆盖“重用相邻窗格”的设置。",
|
||||
"启用此设置时,如果文件已打开,将覆盖“重用相邻窗格”,但“打开所选 Excalidraw 图像的背影笔记”命令面板操作除外。",
|
||||
SECOND_ORDER_LINKS_NAME: "显示二级链接",
|
||||
SECOND_ORDER_LINKS_DESC: "在 Excalidraw 中点击链接时显示链接。二级链接是指指向被点击链接的反向链接" +
|
||||
"当使用图标连接相似的笔记时,二级链接可以让你直接到达相关笔记,而不需要两次点击。" +
|
||||
@@ -661,6 +706,7 @@ FILENAME_HEAD: "文件名",
|
||||
EXPORT_EMBED_SCENE_DESC:
|
||||
"在导出的图像中嵌入 Excalidraw 场景。可以通过在文件级别添加 <code>excalidraw-export-embed-scene: true/false</code> frontmatter 元数据键来覆盖此设置。" +
|
||||
"此设置仅在您下次(重新)打开绘图时生效。",
|
||||
PDF_EXPORT_SETTINGS : "PDF 导出设置",
|
||||
EXPORT_HEAD: "导出设置",
|
||||
EXPORT_SYNC_NAME:
|
||||
"保持 SVG/PNG 文件名与绘图文件同步",
|
||||
@@ -720,6 +766,8 @@ FILENAME_HEAD: "文件名",
|
||||
"更改此选项后,您可能需要重启 Obsidian 来使其生效。",
|
||||
LATEX_DEFAULT_NAME: "插入 LaTeX 时的默认表达式",
|
||||
LATEX_DEFAULT_DESC: "允许留空。允许使用类似 <code>\\color{white}</code> 的格式化表达式。",
|
||||
LATEX_PREAMBLE_NAME : "LaTeX 前言文件(區分大小寫!)" ,
|
||||
LATEX_PREAMBLE_DESC : "前言文件的完整路径,留空则使用默认值。如果文件不存在,此选项将被忽略。<br><strong>重要:</strong>更改后需要重新加载 Obsidian 才能生效!" ,
|
||||
NONSTANDARD_HEAD: "非 Excalidraw.com 官方支持的特性",
|
||||
NONSTANDARD_DESC: `这些特性不受 Excalidraw.com 官方支持。如果在 Excalidraw.com 导入绘图,这些特性将会发生不可预知的变化。
|
||||
包括:自定义画笔工具的数量,自定义字体等。`,
|
||||
@@ -899,8 +947,12 @@ FILENAME_HEAD: "文件名",
|
||||
|
||||
//IFrameActionsMenu.tsx
|
||||
NARROW_TO_HEADING: "缩放至标题",
|
||||
PIN_VIEW: "锁定视图",
|
||||
DO_NOT_PIN_VIEW: "取消锁定视图",
|
||||
NARROW_TO_BLOCK: "缩放至块",
|
||||
SHOW_ENTIRE_FILE: "显示全部",
|
||||
SELECT_SECTION: "从文档选择章节",
|
||||
SELECT_VIEW: "从 base 选择视图",
|
||||
ZOOM_TO_FIT: "缩放至合适大小",
|
||||
RELOAD: "重载链接",
|
||||
OPEN_IN_BROWSER: "在浏览器中打开",
|
||||
@@ -950,6 +1002,7 @@ FILENAME_HEAD: "文件名",
|
||||
PROMPT_BUTTON_INSERT_SPACE: "插入空格",
|
||||
PROMPT_BUTTON_INSERT_LINK: "插入内部链接",
|
||||
PROMPT_BUTTON_UPPERCASE: "大写",
|
||||
PROMPT_BUTTON_SPECIAL_CHARS : "特殊字符" ,
|
||||
PROMPT_SELECT_TEMPLATE: "选择一个模板",
|
||||
|
||||
//ModifierKeySettings
|
||||
@@ -979,6 +1032,7 @@ FILENAME_HEAD: "文件名",
|
||||
|
||||
//Utils.ts
|
||||
UPDATE_AVAILABLE: `Excalidraw 的新版本已在社区插件中可用。\n\n您正在使用 ${PLUGIN_VERSION}。\n最新版本是`,
|
||||
SCRIPT_UPDATES_AVAILABLE : `脚本更新可用 - 请检查脚本存储。\n\n ${ DEVICE . isDesktop ? `此消息可在控制台日志中查看 ( ${ DEVICE . isMacOS ? "CMD+OPT+i" : "CTRL+SHIFT+i" } )\n\n` : "" } 如果您已将脚本组织到脚本存储文件夹下的子文件夹中,并且存在同一脚本的多个副本,可能需要清理未使用的版本以消除此警报。对于不需要更新的私人脚本副本,请将它们存储在脚本存储文件夹之外。` ,
|
||||
ERROR_PNG_TOO_LARGE: "导出 PNG 时出错 - PNG 文件过大,请尝试较小的分辨率",
|
||||
|
||||
// ModifierkeyHelper.ts
|
||||
@@ -1006,4 +1060,99 @@ FILENAME_HEAD: "文件名",
|
||||
LINK_CLICK_POPOUT : "在弹出窗口中打开" ,
|
||||
LINK_CLICK_NEW_TAB : "在新标签页中打开" ,
|
||||
LINK_CLICK_MD_PROPS : "显示 Markdown 图片属性对话框(仅在嵌入 Markdown 文档为图片时适用)" ,
|
||||
|
||||
// 导出对话框
|
||||
// 对话框和标签页
|
||||
EXPORTDIALOG_TITLE: "导出图形",
|
||||
EXPORTDIALOG_TAB_IMAGE: "图像",
|
||||
EXPORTDIALOG_TAB_PDF: "PDF",
|
||||
// 设置持久化
|
||||
EXPORTDIALOG_SAVE_SETTINGS: "将图像设置保存到文件 doc.properties 吗?",
|
||||
EXPORTDIALOG_SAVE_SETTINGS_SAVE: "保存为预设",
|
||||
EXPORTDIALOG_SAVE_SETTINGS_ONETIME: "仅本次使用",
|
||||
// 图像设置
|
||||
EXPORTDIALOG_IMAGE_SETTINGS: "图像",
|
||||
EXPORTDIALOG_IMAGE_DESC: "PNG 支持透明。外部文件可以包含 Excalidraw 场景数据。",
|
||||
EXPORTDIALOG_PADDING: "边距",
|
||||
EXPORTDIALOG_SCALE: "缩放",
|
||||
EXPORTDIALOG_CURRENT_PADDING: "当前边距:",
|
||||
EXPORTDIALOG_SIZE_DESC: "缩放会影响输出大小",
|
||||
EXPORTDIALOG_SCALE_VALUE: "缩放:",
|
||||
EXPORTDIALOG_IMAGE_SIZE: "大小:",
|
||||
// 主题和背景
|
||||
EXPORTDIALOG_EXPORT_THEME: "主题",
|
||||
EXPORTDIALOG_THEME_LIGHT: "浅色",
|
||||
EXPORTDIALOG_THEME_DARK: "深色",
|
||||
EXPORTDIALOG_BACKGROUND: "背景",
|
||||
EXPORTDIALOG_BACKGROUND_TRANSPARENT: "透明",
|
||||
EXPORTDIALOG_BACKGROUND_USE_COLOR: "使用场景颜色",
|
||||
// 选择
|
||||
EXPORTDIALOG_SELECTED_ELEMENTS: "导出",
|
||||
EXPORTDIALOG_SELECTED_ALL: "整个场景",
|
||||
EXPORTDIALOG_SELECTED_SELECTED: "仅选中部分",
|
||||
// 导出选项
|
||||
EXPORTDIALOG_EMBED_SCENE: "包含场景数据吗?",
|
||||
EXPORTDIALOG_EMBED_YES: "是",
|
||||
EXPORTDIALOG_EMBED_NO: "否",
|
||||
// PDF 设置
|
||||
EXPORTDIALOG_PDF_SETTINGS: "PDF",
|
||||
EXPORTDIALOG_PAGE_SIZE: "页面大小",
|
||||
EXPORTDIALOG_PAGE_ORIENTATION: "方向",
|
||||
EXPORTDIALOG_ORIENTATION_PORTRAIT: "纵向",
|
||||
EXPORTDIALOG_ORIENTATION_LANDSCAPE: "横向",
|
||||
EXPORTDIALOG_PDF_FIT_TO_PAGE: "页面适配",
|
||||
EXPORTDIALOG_PDF_FIT_OPTION: "适配页面",
|
||||
EXPORTDIALOG_PDF_FIT_2_OPTION: "适配至最多 2 页" ,
|
||||
EXPORTDIALOG_PDF_FIT_4_OPTION: "适配至最多 4 页" ,
|
||||
EXPORTDIALOG_PDF_FIT_6_OPTION: "适配至最多 6 页" ,
|
||||
EXPORTDIALOG_PDF_FIT_8_OPTION: "适配至最多 8 页" ,
|
||||
EXPORTDIALOG_PDF_FIT_12_OPTION: "适配至最多 12 页" ,
|
||||
EXPORTDIALOG_PDF_FIT_16_OPTION: "适配至最多 16 页" ,
|
||||
EXPORTDIALOG_PDF_SCALE_OPTION: "使用图像缩放(可能跨多页)",
|
||||
EXPORTDIALOG_PDF_PAPER_COLOR: "纸张颜色",
|
||||
EXPORTDIALOG_PDF_PAPER_WHITE: "白色",
|
||||
EXPORTDIALOG_PDF_PAPER_SCENE: "使用场景颜色",
|
||||
EXPORTDIALOG_PDF_PAPER_CUSTOM: "自定义颜色",
|
||||
EXPORTDIALOG_PDF_ALIGNMENT: "页面位置",
|
||||
EXPORTDIALOG_PDF_ALIGN_CENTER: "居中",
|
||||
EXPORTDIALOG_PDF_ALIGN_CENTER_LEFT: "左对齐居中" ,
|
||||
EXPORTDIALOG_PDF_ALIGN_CENTER_RIGHT: "右对齐居中" ,
|
||||
EXPORTDIALOG_PDF_ALIGN_TOP_LEFT: "左上角",
|
||||
EXPORTDIALOG_PDF_ALIGN_TOP_CENTER: "顶部居中",
|
||||
EXPORTDIALOG_PDF_ALIGN_TOP_RIGHT: "右上角",
|
||||
EXPORTDIALOG_PDF_ALIGN_BOTTOM_LEFT: "左下角",
|
||||
EXPORTDIALOG_PDF_ALIGN_BOTTOM_CENTER: "底部居中",
|
||||
EXPORTDIALOG_PDF_ALIGN_BOTTOM_RIGHT: "右下角",
|
||||
EXPORTDIALOG_PDF_MARGIN: "边距",
|
||||
EXPORTDIALOG_PDF_MARGIN_NONE: "无",
|
||||
EXPORTDIALOG_PDF_MARGIN_TINY: "小",
|
||||
EXPORTDIALOG_PDF_MARGIN_NORMAL: "正常",
|
||||
EXPORTDIALOG_SAVE_PDF_SETTINGS: "保存 PDF 设置",
|
||||
EXPORTDIALOG_SAVE_CONFIRMATION: "PDF 配置已保存为插件默认设置",
|
||||
// 按钮
|
||||
EXPORTDIALOG_PNGTOFILE: "导出 PNG 文件",
|
||||
EXPORTDIALOG_SVGTOFILE: "导出 SVG 文件",
|
||||
EXPORTDIALOG_PNGTOVAULT: "PNG 保存到 Vault",
|
||||
EXPORTDIALOG_SVGTOVAULT: "SVG 保存到 Vault",
|
||||
EXPORTDIALOG_EXCALIDRAW: "Excalidraw",
|
||||
EXPORTDIALOG_PNGTOCLIPBOARD: "PNG 复制到剪贴板",
|
||||
EXPORTDIALOG_SVGTOCLIPBOARD: "SVG 复制到剪贴板",
|
||||
EXPORTDIALOG_PDF: "导出 PDF 文件",
|
||||
|
||||
EXPORTDIALOG_PDF_PROGRESS_NOTICE: "正在导出 PDF。如果图像较大,可能需要一些时间。" ,
|
||||
EXPORTDIALOG_PDF_PROGRESS_DONE: "导出完成" ,
|
||||
EXPORTDIALOG_PDF_PROGRESS_ERROR: "导出 PDF 时出错,请检查开发者控制台以获取详细信息" ,
|
||||
|
||||
// Screenshot tab
|
||||
EXPORTDIALOG_NOT_AVAILALBE : "抱歉,此功能仅在绘图在主 Obsidian 工作区打开时可用。",
|
||||
EXPORTDIALOG_TAB_SCREENSHOT : "截图" ,
|
||||
EXPORTDIALOG_SCREENSHOT_DESC : "截图将包括可嵌入的内容,例如 markdown 页面、YouTube、网站等。它们仅在桌面端可用,无法自动导出,并且仅支持 PNG 格式。" ,
|
||||
SCREENSHOT_DESKTOP_ONLY : "截图功能仅在桌面端可用" ,
|
||||
SCREENSHOT_FILE_SUCCESS : "截图已保存到仓库" ,
|
||||
SCREENSHOT_CLIPBOARD_SUCCESS : "截图已复制到剪贴板" ,
|
||||
SCREENSHOT_CLIPBOARD_ERROR : "无法复制截图到剪贴板:" ,
|
||||
SCREENSHOT_ERROR : "截图出错 - 请查看控制台日志" ,
|
||||
|
||||
// exportUtils.ts
|
||||
PDF_EXPORT_DESKTOP_ONLY: "PDF 导出功能仅限桌面端使用" ,
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ExcalidrawElement, FileId } from "@zsviczian/excalidraw/types/excalidraw/element/types";
|
||||
import { ExcalidrawElement, FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { BinaryFileData } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { Notice } from "obsidian";
|
||||
|
||||
import { getEA } from "src/core";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ExcalidrawEmbeddableElement } from "@zsviczian/excalidraw/types/excalidraw/element/types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
|
||||
import { ExcalidrawEmbeddableElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { Modal, Notice, Setting, TFile, ToggleComponent } from "obsidian";
|
||||
import { getEA } from "src/core";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
@@ -12,6 +12,7 @@ import { getYouTubeStartAt, isValidYouTubeStart, isYouTube, updateYouTubeStartTi
|
||||
import { EmbeddalbeMDFileCustomDataSettingsComponent } from "./EmbeddableMDFileCustomDataSettingsComponent";
|
||||
import { isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
|
||||
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { CaptureUpdateAction } from "src/constants/constants";
|
||||
|
||||
export type EmbeddableMDCustomProps = {
|
||||
useObsidianDefaults: boolean;
|
||||
@@ -225,8 +226,7 @@ export class EmbeddableSettings extends Modal {
|
||||
if(dirty) {
|
||||
(async() => {
|
||||
await this.ea.addElementsToView();
|
||||
//@ts-ignore
|
||||
this.ea.viewUpdateScene({appState: {}, storeAction: "update"});
|
||||
this.ea.viewUpdateScene({appState: {}, captureUpdate: CaptureUpdateAction.NEVER});
|
||||
this.close(); //close should only run once update scene is done
|
||||
})();
|
||||
} else {
|
||||
|
||||
@@ -6,9 +6,11 @@ import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { fragWithHTML, getExportPadding, getExportTheme, getPNGScale, getWithBackground, shouldEmbedScene } from "src/utils/utils";
|
||||
import { PageOrientation, PageSize, PDFMargin, PDFPageAlignment, PDFPageMarginString, STANDARD_PAGE_SIZES, exportSVGToClipboard } from "src/utils/exportUtils";
|
||||
import { PageOrientation, PageSize, PDFPageAlignment, PDFPageMarginString, exportSVGToClipboard, exportPNG, exportPNGToClipboard } from "src/utils/exportUtils";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { PDFExportSettings, PDFExportSettingsComponent } from "./PDFExportSettingsComponent";
|
||||
import { captureScreenshot } from "src/utils/screenshot";
|
||||
import { exportImageToFile, getIMGFilename } from "src/utils/fileUtils";
|
||||
|
||||
|
||||
|
||||
@@ -34,15 +36,16 @@ export class ExportDialog extends Modal {
|
||||
public saveToVault: boolean;
|
||||
public pageSize: PageSize = "A4";
|
||||
public pageOrientation: PageOrientation = "portrait";
|
||||
private activeTab: "image" | "pdf" = "image";
|
||||
private activeTab: "image" | "pdf" | "screenshot" = "image";
|
||||
private contentContainer: HTMLDivElement;
|
||||
private buttonContainerRow1: HTMLDivElement;
|
||||
private buttonContainerRow2: HTMLDivElement;
|
||||
public fitToPage: boolean = true;
|
||||
public fitToPage: number = 1;
|
||||
public paperColor: "white" | "scene" | "custom" = "white";
|
||||
public customPaperColor: string = "#ffffff";
|
||||
public alignment: PDFPageAlignment = "center";
|
||||
public margin: PDFPageMarginString = "normal";
|
||||
private scaleSetting:Setting;
|
||||
|
||||
constructor(
|
||||
private plugin: ExcalidrawPlugin,
|
||||
@@ -70,6 +73,7 @@ export class ExportDialog extends Modal {
|
||||
this.margin = plugin.settings.pdfSettings.margin;
|
||||
|
||||
this.saveSettings = false;
|
||||
this.createForm();
|
||||
}
|
||||
|
||||
destroy() {
|
||||
@@ -85,19 +89,35 @@ export class ExportDialog extends Modal {
|
||||
this.containerEl.remove();
|
||||
}
|
||||
|
||||
get isSelectedOnly(): boolean {
|
||||
return this.hasSelectedElements && this.exportSelectedOnly;
|
||||
}
|
||||
|
||||
updateBoundingBox() {
|
||||
if(this.isSelectedOnly) {
|
||||
this.boundingBox = this.ea.getBoundingBox(this.view.getViewSelectedElements());
|
||||
} else {
|
||||
this.boundingBox = this.ea.getBoundingBox(this.ea.getViewElements());
|
||||
}
|
||||
if(this.scaleSetting) {
|
||||
this.scaleSetting.setDesc(this.size());
|
||||
}
|
||||
}
|
||||
|
||||
onOpen(): void {
|
||||
this.containerEl.classList.add("excalidraw-release");
|
||||
this.titleEl.setText(t("EXPORTDIALOG_TITLE"));
|
||||
this.hasSelectedElements = this.view.getViewSelectedElements().length > 0;
|
||||
//@ts-ignore
|
||||
this.selectedOnlySetting.setVisibility(this.hasSelectedElements);
|
||||
this.updateBoundingBox();
|
||||
}
|
||||
|
||||
async onClose() {
|
||||
this.dirty = this.saveSettings;
|
||||
}
|
||||
|
||||
async createForm() {
|
||||
createForm() {
|
||||
if(DEVICE.isDesktop) {
|
||||
// Create tab container
|
||||
const tabContainer = this.contentEl.createDiv("nav-buttons-container");
|
||||
@@ -112,11 +132,17 @@ export class ExportDialog extends Modal {
|
||||
cls: `nav-button ${this.activeTab === "pdf" ? "is-active" : ""}`
|
||||
});
|
||||
|
||||
const screenshotTab = tabContainer.createEl("button", {
|
||||
text: t("EXPORTDIALOG_TAB_SCREENSHOT"),
|
||||
cls: `nav-button ${this.activeTab === "screenshot" ? "is-active" : ""}`
|
||||
});
|
||||
|
||||
// Tab click handlers
|
||||
imageTab.onclick = () => {
|
||||
this.activeTab = "image";
|
||||
imageTab.addClass("is-active");
|
||||
pdfTab.removeClass("is-active");
|
||||
screenshotTab.removeClass("is-active");
|
||||
this.renderContent();
|
||||
};
|
||||
|
||||
@@ -124,8 +150,17 @@ export class ExportDialog extends Modal {
|
||||
this.activeTab = "pdf";
|
||||
pdfTab.addClass("is-active");
|
||||
imageTab.removeClass("is-active");
|
||||
screenshotTab.removeClass("is-active");
|
||||
this.renderContent();
|
||||
};
|
||||
|
||||
screenshotTab.onclick = () => {
|
||||
this.activeTab = "screenshot";
|
||||
screenshotTab.addClass("is-active");
|
||||
imageTab.removeClass("is-active");
|
||||
pdfTab.removeClass("is-active");
|
||||
this.renderContent();
|
||||
}
|
||||
}
|
||||
|
||||
// Create content container
|
||||
@@ -156,32 +191,62 @@ export class ExportDialog extends Modal {
|
||||
this.buttonContainerRow1.empty();
|
||||
this.buttonContainerRow2.empty();
|
||||
|
||||
if (this.activeTab === "image") {
|
||||
this.createImageSettings();
|
||||
this.createExportSettings();
|
||||
this.createImageButtons();
|
||||
} else {
|
||||
this.createImageSettings();
|
||||
this.createPDFSettings();
|
||||
this.createPDFButton();
|
||||
this.createHeader();
|
||||
switch (this.activeTab) {
|
||||
case "pdf":
|
||||
this.createImageSettings();
|
||||
this.createPDFSettings();
|
||||
this.createPDFButton();
|
||||
break;
|
||||
case "screenshot":
|
||||
if(this.view.isInMainObsidianWorkspace) {
|
||||
this.createImageSettings(true);
|
||||
this.createImageButtons(true);
|
||||
}
|
||||
break;
|
||||
case "image":
|
||||
default:
|
||||
this.createImageSettings(false);
|
||||
this.createExportSettings();
|
||||
this.createImageButtons();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private size ():DocumentFragment {
|
||||
const width = Math.round(this.scale*this.boundingBox.width + this.padding*2);
|
||||
const height = Math.round(this.scale*this.boundingBox.height + this.padding*2);
|
||||
return fragWithHTML(`${t("EXPORTDIALOG_SIZE_DESC")}<br>${t("EXPORTDIALOG_SCALE_VALUE")} <b>${this.scale}</b><br>${t("EXPORTDIALOG_IMAGE_SIZE")} <b>${width}x${height}</b>`);
|
||||
}
|
||||
|
||||
private createHeader() {
|
||||
switch (this.activeTab) {
|
||||
case "pdf":
|
||||
this.contentContainer.createEl("h1",{text: t("EXPORTDIALOG_PDF_SETTINGS")});
|
||||
//this.contentContainer.createEl("p",{text: t("EXPORTDIALOG_PDF_DESC")});
|
||||
break;
|
||||
case "screenshot":
|
||||
this.contentContainer.createEl("h1",{text: t("EXPORTDIALOG_TAB_SCREENSHOT")});
|
||||
if(this.view.isInMainObsidianWorkspace) {
|
||||
this.contentContainer.createEl("p",{text: t("EXPORTDIALOG_SCREENSHOT_DESC")})
|
||||
} else {
|
||||
this.contentContainer.createEl("p",{text: t("EXPORTDIALOG_NOT_AVAILALBE")})
|
||||
}
|
||||
break;
|
||||
case "image":
|
||||
default:
|
||||
this.contentContainer.createEl("h1",{text: t("EXPORTDIALOG_IMAGE_SETTINGS")});
|
||||
this.contentContainer.createEl("p",{text: t("EXPORTDIALOG_IMAGE_DESC")})
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private createImageSettings() {
|
||||
let scaleSetting:Setting;
|
||||
private createImageSettings(isScreenshot: boolean = false) {
|
||||
let paddingSetting: Setting;
|
||||
|
||||
this.contentContainer.createEl("h1",{text: t("EXPORTDIALOG_IMAGE_SETTINGS")});
|
||||
this.contentContainer.createEl("p",{text: t("EXPORTDIALOG_IMAGE_DESC")})
|
||||
|
||||
this.createSaveSettingsDropdown();
|
||||
|
||||
const size = ():DocumentFragment => {
|
||||
const width = Math.round(this.scale*this.boundingBox.width + this.padding*2);
|
||||
const height = Math.round(this.scale*this.boundingBox.height + this.padding*2);
|
||||
return fragWithHTML(`${t("EXPORTDIALOG_SIZE_DESC")}<br>${t("EXPORTDIALOG_SCALE_VALUE")} <b>${this.scale}</b><br>${t("EXPORTDIALOG_IMAGE_SIZE")} <b>${width}x${height}</b>`);
|
||||
}
|
||||
|
||||
const padding = ():DocumentFragment => {
|
||||
return fragWithHTML(`${t("EXPORTDIALOG_CURRENT_PADDING")} <b>${this.padding}</b>`);
|
||||
}
|
||||
@@ -195,21 +260,21 @@ export class ExportDialog extends Modal {
|
||||
.setValue(this.padding)
|
||||
.onChange(value => {
|
||||
this.padding = value;
|
||||
scaleSetting.setDesc(size());
|
||||
this.scaleSetting.setDesc(this.size());
|
||||
paddingSetting.setDesc(padding());
|
||||
})
|
||||
})
|
||||
|
||||
scaleSetting = new Setting(this.contentContainer)
|
||||
this.scaleSetting = new Setting(this.contentContainer)
|
||||
.setName(t("EXPORTDIALOG_SCALE"))
|
||||
.setDesc(size())
|
||||
.setDesc(this.size())
|
||||
.addSlider(slider =>
|
||||
slider
|
||||
.setLimits(0.2,7,0.1)
|
||||
.setValue(this.scale)
|
||||
.onChange(value => {
|
||||
this.scale = value;
|
||||
scaleSetting.setDesc(size());
|
||||
this.scaleSetting.setDesc(this.size());
|
||||
})
|
||||
)
|
||||
|
||||
@@ -225,17 +290,19 @@ export class ExportDialog extends Modal {
|
||||
})
|
||||
)
|
||||
|
||||
new Setting(this.contentContainer)
|
||||
.setName(t("EXPORTDIALOG_BACKGROUND"))
|
||||
.addDropdown(dropdown =>
|
||||
dropdown
|
||||
.addOption("transparent", t("EXPORTDIALOG_BACKGROUND_TRANSPARENT"))
|
||||
.addOption("with-color", t("EXPORTDIALOG_BACKGROUND_USE_COLOR"))
|
||||
.setValue(this.transparent?"transparent":"with-color")
|
||||
.onChange(value => {
|
||||
this.transparent = value === "transparent";
|
||||
})
|
||||
)
|
||||
if(!isScreenshot) {
|
||||
new Setting(this.contentContainer)
|
||||
.setName(t("EXPORTDIALOG_BACKGROUND"))
|
||||
.addDropdown(dropdown =>
|
||||
dropdown
|
||||
.addOption("transparent", t("EXPORTDIALOG_BACKGROUND_TRANSPARENT"))
|
||||
.addOption("with-color", t("EXPORTDIALOG_BACKGROUND_USE_COLOR"))
|
||||
.setValue(this.transparent?"transparent":"with-color")
|
||||
.onChange(value => {
|
||||
this.transparent = value === "transparent";
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
this.selectedOnlySetting = new Setting(this.contentContainer)
|
||||
.setName(t("EXPORTDIALOG_SELECTED_ELEMENTS"))
|
||||
@@ -246,8 +313,11 @@ export class ExportDialog extends Modal {
|
||||
.setValue(this.exportSelectedOnly?"selected":"all")
|
||||
.onChange(value => {
|
||||
this.exportSelectedOnly = value === "selected";
|
||||
this.updateBoundingBox();
|
||||
})
|
||||
);
|
||||
//@ts-ignore
|
||||
this.selectedOnlySetting.setVisibility(this.hasSelectedElements);
|
||||
}
|
||||
|
||||
private createExportSettings() {
|
||||
@@ -276,7 +346,7 @@ export class ExportDialog extends Modal {
|
||||
paperColor: this.paperColor,
|
||||
customPaperColor: this.customPaperColor,
|
||||
alignment: this.alignment,
|
||||
margin: this.margin
|
||||
margin: this.margin,
|
||||
};
|
||||
|
||||
new PDFExportSettingsComponent(
|
||||
@@ -294,14 +364,29 @@ export class ExportDialog extends Modal {
|
||||
).render();
|
||||
}
|
||||
|
||||
private createImageButtons() {
|
||||
private createImageButtons(isScreenshot: boolean = false) {
|
||||
if(DEVICE.isDesktop) {
|
||||
const bPNG = this.buttonContainerRow1.createEl("button", {
|
||||
text: t("EXPORTDIALOG_PNGTOFILE"),
|
||||
cls: "excalidraw-export-button"
|
||||
});
|
||||
bPNG.onclick = () => {
|
||||
this.view.exportPNG(this.embedScene, this.hasSelectedElements && this.exportSelectedOnly);
|
||||
if(isScreenshot) {
|
||||
//allow dialog to close before taking screenshot
|
||||
setTimeout(async () => {
|
||||
const png = await captureScreenshot(this.view, {
|
||||
zoom: this.scale,
|
||||
margin: this.padding,
|
||||
selectedOnly: this.isSelectedOnly,
|
||||
theme: this.theme
|
||||
});
|
||||
if(png) {
|
||||
exportPNG(png, this.view.file.basename);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this.view.exportPNG(this.embedScene, this.isSelectedOnly);
|
||||
}
|
||||
this.close();
|
||||
};
|
||||
}
|
||||
@@ -311,7 +396,22 @@ export class ExportDialog extends Modal {
|
||||
cls: "excalidraw-export-button"
|
||||
});
|
||||
bPNGVault.onclick = () => {
|
||||
this.view.savePNG(this.view.getScene(this.hasSelectedElements && this.exportSelectedOnly));
|
||||
if(isScreenshot) {
|
||||
//allow dialog to close before taking screenshot
|
||||
setTimeout(async () => {
|
||||
const png = await captureScreenshot(this.view, {
|
||||
zoom: this.scale,
|
||||
margin: this.padding,
|
||||
selectedOnly: this.isSelectedOnly,
|
||||
theme: this.theme
|
||||
});
|
||||
if(png) {
|
||||
exportImageToFile(this.view, getIMGFilename(this.view.file.path,"png"), png, ".png");
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this.view.savePNG({scene: this.view.getScene(this.isSelectedOnly)});
|
||||
}
|
||||
this.close();
|
||||
};
|
||||
|
||||
@@ -320,10 +420,27 @@ export class ExportDialog extends Modal {
|
||||
cls: "excalidraw-export-button"
|
||||
});
|
||||
bPNGClipboard.onclick = async () => {
|
||||
this.view.exportPNGToClipboard(this.embedScene, this.hasSelectedElements && this.exportSelectedOnly);
|
||||
if(isScreenshot) {
|
||||
//allow dialog to close before taking screenshot
|
||||
setTimeout(async () => {
|
||||
const png = await captureScreenshot(this.view, {
|
||||
zoom: this.scale,
|
||||
margin: this.padding,
|
||||
selectedOnly: this.isSelectedOnly,
|
||||
theme: this.theme
|
||||
});
|
||||
if(png) {
|
||||
exportPNGToClipboard(png);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
this.view.exportPNGToClipboard(this.embedScene, this.isSelectedOnly);
|
||||
}
|
||||
this.close();
|
||||
};
|
||||
|
||||
if(isScreenshot) return;
|
||||
|
||||
if(DEVICE.isDesktop) {
|
||||
const bExcalidraw = this.buttonContainerRow2.createEl("button", {
|
||||
text: t("EXPORTDIALOG_EXCALIDRAW"),
|
||||
@@ -339,7 +456,7 @@ export class ExportDialog extends Modal {
|
||||
cls: "excalidraw-export-button"
|
||||
});
|
||||
bSVG.onclick = () => {
|
||||
this.view.exportSVG(this.embedScene, this.hasSelectedElements && this.exportSelectedOnly);
|
||||
this.view.exportSVG(this.embedScene, this.isSelectedOnly);
|
||||
this.close();
|
||||
};
|
||||
}
|
||||
@@ -349,7 +466,7 @@ export class ExportDialog extends Modal {
|
||||
cls: "excalidraw-export-button"
|
||||
});
|
||||
bSVGVault.onclick = () => {
|
||||
this.view.saveSVG(this.view.getScene(this.hasSelectedElements && this.exportSelectedOnly));
|
||||
this.view.saveSVG({scene: this.view.getScene(this.isSelectedOnly)});
|
||||
this.close();
|
||||
};
|
||||
|
||||
@@ -358,7 +475,7 @@ export class ExportDialog extends Modal {
|
||||
cls: "excalidraw-export-button"
|
||||
});
|
||||
bSVGClipboard.onclick = async () => {
|
||||
const svg = await this.view.getSVG(this.embedScene, this.hasSelectedElements && this.exportSelectedOnly);
|
||||
const svg = await this.view.getSVG(this.embedScene, this.isSelectedOnly);
|
||||
exportSVGToClipboard(svg);
|
||||
this.close();
|
||||
};
|
||||
@@ -378,26 +495,12 @@ export class ExportDialog extends Modal {
|
||||
paperColor: this.paperColor,
|
||||
customPaperColor: this.customPaperColor,
|
||||
alignment: this.alignment,
|
||||
margin: this.margin
|
||||
margin: this.margin,
|
||||
};
|
||||
await this.plugin.saveSettings();
|
||||
new Notice(t("EXPORTDIALOG_SAVE_CONFIRMATION"));
|
||||
};
|
||||
|
||||
const bPDFVault = this.buttonContainerRow1.createEl("button", {
|
||||
text: t("EXPORTDIALOG_PDFTOVAULT"),
|
||||
cls: "excalidraw-export-button"
|
||||
});
|
||||
bPDFVault.onclick = () => {
|
||||
this.view.exportPDF(
|
||||
true,
|
||||
this.hasSelectedElements && this.exportSelectedOnly,
|
||||
this.pageSize,
|
||||
this.pageOrientation
|
||||
);
|
||||
this.close();
|
||||
};
|
||||
|
||||
if (!DEVICE.isDesktop) return;
|
||||
const bPDFExport = this.buttonContainerRow1.createEl("button", {
|
||||
text: t("EXPORTDIALOG_PDF"),
|
||||
@@ -405,8 +508,7 @@ export class ExportDialog extends Modal {
|
||||
});
|
||||
bPDFExport.onclick = () => {
|
||||
this.view.exportPDF(
|
||||
false,
|
||||
this.hasSelectedElements && this.exportSelectedOnly,
|
||||
this.isSelectedOnly,
|
||||
this.pageSize,
|
||||
this.pageOrientation
|
||||
);
|
||||
@@ -416,7 +518,7 @@ export class ExportDialog extends Modal {
|
||||
|
||||
public getPaperColor(): string {
|
||||
switch (this.paperColor) {
|
||||
case "white": return "#ffffff";
|
||||
case "white": return this.theme === "light" ? "#ffffff" : "#000000";
|
||||
case "scene": return this.api.getAppState().viewBackgroundColor;
|
||||
case "custom": return this.customPaperColor;
|
||||
default: return "#ffffff";
|
||||
|
||||
105
src/shared/Dialogs/FloatingModal.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import { App, Modal } from "obsidian";
|
||||
|
||||
export class FloatingModal extends Modal {
|
||||
private dragging = false;
|
||||
private offsetX = 0;
|
||||
private offsetY = 0;
|
||||
private pointerDownHandler: (e: PointerEvent) => void;
|
||||
private pointerMoveHandler: (e: PointerEvent) => void;
|
||||
private pointerUpHandler: () => void;
|
||||
|
||||
constructor(app: App) {
|
||||
super(app);
|
||||
|
||||
// Initialize event handlers with proper binding
|
||||
this.pointerDownHandler = this.handlePointerDown.bind(this);
|
||||
this.pointerMoveHandler = this.handlePointerMove.bind(this);
|
||||
this.pointerUpHandler = this.handlePointerUp.bind(this);
|
||||
}
|
||||
|
||||
private handlePointerDown(e: PointerEvent): void {
|
||||
// Ignore if clicking on interactive elements
|
||||
if (
|
||||
e.target instanceof HTMLInputElement ||
|
||||
e.target instanceof HTMLTextAreaElement ||
|
||||
e.target instanceof HTMLSelectElement ||
|
||||
e.target instanceof HTMLButtonElement ||
|
||||
(e.target as HTMLElement).closest(".clickable-icon")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.dragging = true;
|
||||
const { modalEl } = this;
|
||||
this.offsetX = e.clientX - modalEl.getBoundingClientRect().left;
|
||||
this.offsetY = e.clientY - modalEl.getBoundingClientRect().top;
|
||||
|
||||
// Add global event listeners for move and up events
|
||||
document.addEventListener("pointermove", this.pointerMoveHandler);
|
||||
document.addEventListener("pointerup", this.pointerUpHandler);
|
||||
// Capture the pointer to ensure we get events even when outside the target
|
||||
(e.target as HTMLElement).setPointerCapture(e.pointerId);
|
||||
}
|
||||
|
||||
private handlePointerMove(e: PointerEvent): void {
|
||||
if (!this.dragging) return;
|
||||
const { modalEl } = this;
|
||||
|
||||
e.preventDefault();
|
||||
|
||||
const x = e.clientX - this.offsetX;
|
||||
const y = e.clientY - this.offsetY;
|
||||
|
||||
// Position the modal element
|
||||
modalEl.style.left = `${x}px`;
|
||||
modalEl.style.top = `${y}px`;
|
||||
modalEl.style.transform = "none"; // Remove centering transform
|
||||
}
|
||||
|
||||
private handlePointerUp(): void {
|
||||
this.dragging = false;
|
||||
document.removeEventListener("pointermove", this.pointerMoveHandler);
|
||||
document.removeEventListener("pointerup", this.pointerUpHandler);
|
||||
}
|
||||
|
||||
open(): void {
|
||||
super.open();
|
||||
setTimeout(() => {
|
||||
//@ts-ignore
|
||||
const { containerEl, modalEl, bgEl } = this;
|
||||
containerEl.style.pointerEvents = "none";
|
||||
if (bgEl) bgEl.style.display = "none";
|
||||
|
||||
// Set initial position and make modal draggable
|
||||
if (modalEl) {
|
||||
modalEl.style.pointerEvents = "auto";
|
||||
// Position absolute is needed for custom positioning
|
||||
modalEl.style.position = "absolute";
|
||||
|
||||
// Center the modal initially
|
||||
const rect = modalEl.getBoundingClientRect();
|
||||
const centerX = window.innerWidth / 2 - rect.width / 2;
|
||||
const centerY = window.innerHeight / 2 - rect.height / 2;
|
||||
|
||||
modalEl.style.left = `${centerX}px`;
|
||||
modalEl.style.top = `${centerY}px`;
|
||||
modalEl.style.transform = "none";
|
||||
|
||||
// Add pointer down listener to start dragging
|
||||
modalEl.addEventListener("pointerdown", this.pointerDownHandler);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
close(): void {
|
||||
const { modalEl } = this;
|
||||
// Clean up event listeners
|
||||
if (modalEl) {
|
||||
modalEl.removeEventListener("pointerdown", this.pointerDownHandler);
|
||||
}
|
||||
document.removeEventListener("pointermove", this.pointerMoveHandler);
|
||||
document.removeEventListener("pointerup", this.pointerUpHandler);
|
||||
|
||||
super.close();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { CaptureUpdateAction } from "src/constants/constants";
|
||||
|
||||
export const showFrameSettings = (ea: ExcalidrawAutomate) => {
|
||||
const {enabled, clip, name, outline} = ea.getExcalidrawAPI().getAppState().frameRendering;
|
||||
@@ -64,7 +65,7 @@ export const showFrameSettings = (ea: ExcalidrawAutomate) => {
|
||||
appState: {
|
||||
frameRendering: settings
|
||||
},
|
||||
storeAction: "update",
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
frameSettingsModal.close();
|
||||
})
|
||||
|
||||
@@ -70,7 +70,7 @@ export class InsertPDFModal extends Modal {
|
||||
this.setImageSizeMessage = null;
|
||||
}
|
||||
|
||||
private async getPageDimensions (pdfDoc: any) {
|
||||
private async getPDFPageDimensions (pdfDoc: any) {
|
||||
try {
|
||||
const scale = this.plugin.settings.pdfScale;
|
||||
const canvas = createEl("canvas");
|
||||
@@ -197,7 +197,7 @@ export class InsertPDFModal extends Modal {
|
||||
rangeOnChange(`1-${numPages}`);
|
||||
importButtonMessages();
|
||||
numPagesMessages();
|
||||
this.getPageDimensions(this.pdfDoc);
|
||||
this.getPDFPageDimensions(this.pdfDoc);
|
||||
} else {
|
||||
importButton.setDisabled(true);
|
||||
}
|
||||
|
||||
@@ -11,184 +11,325 @@ Thank you & Enjoy!
|
||||
`;
|
||||
|
||||
export const RELEASE_NOTES: { [k: string]: string } = {
|
||||
Intro: `After each update you'll be prompted with the release notes. You can disable this in plugin settings.
|
||||
Intro: `After each update, you’ll see these release notes (you can turn this off in the plugin settings).
|
||||
|
||||
I develop this plugin as a hobby, spending my free time doing this. If you find it valuable, then please say THANK YOU or...
|
||||
I build this plugin in my free time, as a labor of love. Curious about the philosophy behind it? Check out [📕 Sketch Your Mind](https://sketch-your-mind.com). If you find it valuable, say THANK YOU or…
|
||||
|
||||
<div class="ex-coffee-div"><a href="https://ko-fi.com/zsolt"><img src="https://storage.ko-fi.com/cdn/kofi6.png?v=6" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
|
||||
`,
|
||||
"2.7.5":`
|
||||
"2.14.1":`
|
||||
## New
|
||||
- New frontmatter option \`excalidraw-embed-md\`. When set to \`true\`, embedding this Excalidraw file into another markdown file will display its markdown content (the "back of the note") instead of rendering it as an image.
|
||||
- If you want to always display the drawing as an image, even when \`excalidraw-embed-md\` is enabled, use the special embed syntax: \`![[drawing#^as-image]]\`. Here, \`as-image\` is a phantom block reference that forces image rendering.
|
||||
- Added Spanish translation by [@Joakim31](https://github.com/Joakim31) [#2425](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2425)
|
||||
- Incremental minor updates from the main [Excalidraw project](https://github.com/excalidraw/excalidraw).
|
||||
|
||||
## Fixed
|
||||
- PDF export scenario described in [#2184](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2184)
|
||||
- Elbow arrows do not work within frames [#2187](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2187)
|
||||
- Embedding images into Excalidraw with areaRef links did not work as expected due to conflicting SVG viewbox and width and height values
|
||||
- Can't exit full-screen mode in popout windows using the Command Palette toggle action [#2188](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2188)
|
||||
- If the image mask extended beyond the image in "Mask and Crop" image mode, the mask got misaligned from the image.
|
||||
- PDF image embedding fixes that impacted some PDF files (not all):
|
||||
- When cropping the PDF page in the scene (by double-clicking the image to crop), the size and position of the PDF cutout drifted.
|
||||
- Using PDF++ there was a small offset in the position of the cutout in PDF++ and the image in Excalidraw.
|
||||
- Updated a number of scripts including Split Ellipse, Select Similar Elements, and Concatenate Lines
|
||||
- Styling issues impacting native Obsidian search/replace dialogs. [#2420](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2420)
|
||||
- Now using native Obsidian attachment location function. 🙏 [mnaoumov](https://github.com/mnaoumov) [#2421](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2421), potentially fixes [#179](https://github.com/RainCat1998/obsidian-custom-attachment-location/issues/179) of the Obsidian Custom Attachment Location plugin issue.
|
||||
`,
|
||||
"2.14.0":`
|
||||
## A Big "Small" Update
|
||||
- Added search to Excalidraw Settings, plus added a link to access the public NotebookLM workbook pre-loaded with everything about the plugin
|
||||
- New Taiwan-idiomatic Traditional Chinese translation by [@rlan](https://github.com/rlan) [#2413](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2413)
|
||||
`,
|
||||
"2.13.2":`
|
||||
## New
|
||||
- Excalidraw now properly supports drag and drop of obsidian links from Bases.
|
||||
- ExcalidrawAutomate exposes a new class: \`FloatingModal\`. This is a modified version of the Obsidian.Modal class that allows the modal to be dragged around the screen and that does not dim the background. You can use it to create custom dialogs that behave like Obsidian modals but with more flexibility.
|
||||
`,
|
||||
"2.13.1":`
|
||||
## New
|
||||
- Support for Obsidian bases as embeddables in Excalidraw.
|
||||
- **Note:** The feature is only available to Insiders who have Obsidian 1.9.4 or later installed.
|
||||
- If your base includes multiple views you can pin the desired view similar to filtering to a section (click top left # button; \`[[my.base|my view]]\`).
|
||||
|
||||
## Fixed
|
||||
- Cannot type in embedded web forms. In certain cases, typing within these embeds would trigger Excalidraw hotkeys instead of interacting with the embedded content. [#2403](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2403)
|
||||
`,
|
||||
"2.13.0":`
|
||||
<div class="excalidraw-videoWrapper"><div>
|
||||
<iframe src="https://www.youtube.com/embed/QzhyQb4JF3Q" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
|
||||
</div></div>
|
||||
|
||||
## New
|
||||
- **Flexible Auto-Export Location:** Take control of where your auto-exported .png, .svg, and .excalidraw files are saved. Addressing a long-standing request, you can now define custom output paths using the new **Excalidraw Hooks**.
|
||||
- Implement the \`onImageExportPathHook\` callback in your ExcalidrawAutomate startup script to control the *destination path*.
|
||||
- Get the skeleton script via plugin settings or download it [here](https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/refs/heads/master/src/constants/assets/startupScript.md).
|
||||
|
||||
- **Control Auto-Export Trigger:** Use the \`onTriggerAutoexportHook\` in your startup script to decide *if* and *how* auto-export runs for a file, based on its properties or frontmatter, *before* the export path is determined.
|
||||
|
||||
- **Improved "Open Excalidraw drawing":** The Command Palette command now searches the *entire Vault* for the matching Excalidraw file when used on an embedded .svg or .png, useful when exports are in different folders.
|
||||
|
||||
- **Placeholder Files for New Embeds:** When embedding a new drawing as PNG/SVG via the Command Palette, empty placeholder files are now created immediately based on your auto-export setting. This ensures Obsidian correctly updates links if you rename the file soon after creation (when "Keep filenames in sync" is on).
|
||||
|
||||
- **Paste Obsidian URLs into Excalidraw:** Pasting an Obsidian URL for an image or file into Excalidraw now inserts the associated image directly into the drawing.
|
||||
|
||||
- **\`onImageFilePathHook\` Drag & Drop Support:** The \`onImageFilePathHook\` (for controlling location/filename of *embedded* files) is now triggered when dragging and dropping files into Excalidraw from outside Obsidian, matching the existing behavior for pasting.
|
||||
|
||||
## New in ExcalidrawAutomate
|
||||
${String.fromCharCode(96,96,96)}
|
||||
/**
|
||||
* Add, modify, or delete keys in element.customData and preserve existing keys.
|
||||
* Creates customData={} if it does not exist.
|
||||
* Takes the element id for an element in ea.elementsDict and the newData to add or modify.
|
||||
* To delete keys set key value in newData to undefined. So {keyToBeDeleted:undefined} will be deleted.
|
||||
* @param id
|
||||
* @param newData
|
||||
* @returns undefined if element does not exist in elementsDict, returns the modified element otherwise.
|
||||
*/
|
||||
public addAppendUpdateCustomData(id:string, newData: Partial<Record<string, unknown>>);
|
||||
${String.fromCharCode(96,96,96)}
|
||||
\`\`\`ts
|
||||
splitFolderAndFilename(filepath: string) : {
|
||||
folderpath: string;
|
||||
filename: string;
|
||||
basename: string;
|
||||
extension: string;
|
||||
}
|
||||
\`\`\`
|
||||
`,
|
||||
"2.7.4":`
|
||||
"2.12.4":`
|
||||
## Fixed
|
||||
- Regression from 2.7.3 where image fileId got overwritten in some cases
|
||||
- White flash when opening a dark drawing [#2178](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2178)
|
||||
- ExaliBrain did not render after the 2.12.3 update. [#2384](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2384)
|
||||
`,
|
||||
"2.7.3":`
|
||||
"2.12.3":`
|
||||
## Minor fixes
|
||||
- Includes all recent updates and fixes from excalidraw.com
|
||||
- Fixed issue with line editor snapping out of edit mode
|
||||
- Fixed long-standing issue with wireframe to code calling a deprecated OpenAI endpoint
|
||||
- "Load Excalidraw Properties into Obsidian Suggester" setting now defaults to false for new installations. [#2380](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2380)
|
||||
- Taskbone OCR result does not get saved to frontmatter in some cases [#1123](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1123)
|
||||
|
||||
## New
|
||||
- If the cropped file or annotated file prefix is set to empty, there will now be no prefix added to the file name. Additionally, now you can also set a suffix to the file name. [#2370](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2370)
|
||||
`,
|
||||
"2.12.2": `
|
||||
## Fixed
|
||||
- BUG: Excalidraw theme changes to Light from Dark when clicking line element node [#2360](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2360)
|
||||
`,
|
||||
"2.12.1": `
|
||||
## New
|
||||
- "Text to Path" text input window is now draggable.
|
||||
|
||||
## Fixed
|
||||
- Minor fixes to the Polygon line feature introduced in 2.12.0. [#9580](https://github.com/excalidraw/excalidraw/pull/9580)
|
||||
- Fix new Improved Unlock UI, where if a lock element was over an unlocked element, the unlocked element was not selectable. [#9582](https://github.com/excalidraw/excalidraw/pull/9582)
|
||||
- Fixed ghost point issue when moving a shape after dragging a point in the line editor [#9530](https://github.com/excalidraw/excalidraw/pull/9530)
|
||||
|
||||
## New in ExcalidrawAutomate
|
||||
${String.fromCharCode(96,96,96)}js
|
||||
untils.inputPrompt({
|
||||
header: string,
|
||||
placeholder?: string,
|
||||
value?: string,
|
||||
buttons?: { caption: string; tooltip?:string; action: Function }[],
|
||||
lines?: number,
|
||||
displayEditorButtons?: boolean,
|
||||
customComponents?: (container: HTMLElement) => void,
|
||||
blockPointerInputOutsideModal?: boolean,
|
||||
controlsOnTop?: boolean,
|
||||
draggable?: boolean,
|
||||
});
|
||||
${String.fromCharCode(96,96,96)}
|
||||
`,
|
||||
"2.12.0": `
|
||||
<div class="excalidraw-videoWrapper"><div>
|
||||
<iframe src="https://www.youtube.com/embed/ISuORbVKyhQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
|
||||
<iframe src="https://www.youtube.com/embed/-fldh3cE2gs" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
|
||||
</div></div>
|
||||
|
||||
## Fixed
|
||||
- Toggling image size anchoring on and off by modifying the image link did not update the image in the view until the user forced saved it or closed and opened the drawing again. This was a side-effect of the less frequent view save introduced in 2.7.1
|
||||
|
||||
- Dynamic styling was not working when frames were present in the scene.
|
||||
- Minor fix to the screenshot feature. This also resolves the long-standing issue where window control buttons (close, minimize, maximize) appeared in full-screen mode.
|
||||
- Fixed an issue where ALT/OPT + dragging an embeddable object sometimes failed, resulting in an empty object instead of dragging the element.
|
||||
|
||||
## New
|
||||
- **Shade Master Script**: A new script that allows you to modify the color lightness, hue, saturation, and transparency of selected Excalidraw elements, SVG images, and nested Excalidraw drawings. When a single image is selected, you can map colors individually. The original image remains unchanged, and a mapping table is added under ${String.fromCharCode(96)}## Embedded Files${String.fromCharCode(96)} for SVG and nested drawings. This helps maintain links between drawings while allowing different color themes.
|
||||
- New Command Palette Command: "Duplicate selected image with a different image ID". Creates a copy of the selected image with a new image ID. This allows you to add multiple color mappings to the same image. In the scene, the image will be treated as if a different image, but loaded from the same file in the Vault.
|
||||
|
||||
## QoL Improvements
|
||||
- New setting under ${String.fromCharCode(96)}Embedding Excalidraw into your notes and Exporting${String.fromCharCode(96)} > ${String.fromCharCode(96)}Image Caching and rendering optimization${String.fromCharCode(96)}. You can now set the number of concurrent workers that render your embedded images. Increasing the number will increase the speed but temporarily reduce the responsiveness of your system in case of large drawings.
|
||||
- Moved pen-related settings under ${String.fromCharCode(96)}Excalidraw appearance and behavior${String.fromCharCode(96)} to their sub-heading called ${String.fromCharCode(96)}Pen${String.fromCharCode(96)}.
|
||||
- Minor error fixing and performance optimizations when loading and updating embedded images.
|
||||
- Color maps in ${String.fromCharCode(96)}## Embedded Files${String.fromCharCode(96)} may now include color keys "stroke" and "fill". If set, these will change the fill and stroke attributes of the SVG root element of the relevant file.
|
||||
|
||||
## New in ExcalidrawAutomate
|
||||
${String.fromCharCode(96,96,96)}ts
|
||||
// Updates the color map of an SVG image element in the view. If a ColorMap is provided, it will be used directly.
|
||||
// If an SVGColorInfo is provided, it will be converted to a ColorMap.
|
||||
// The view will be marked as dirty and the image will be reset using the color map.
|
||||
updateViewSVGImageColorMap(
|
||||
elements: ExcalidrawImageElement | ExcalidrawImageElement[],
|
||||
colors: ColorMap | SVGColorInfo | ColorMap[] | SVGColorInfo[]
|
||||
): Promise<void>;
|
||||
|
||||
// Retrieves the color map for an image element.
|
||||
// The color map contains information about the mapping of colors used in the image.
|
||||
// If the element already has a color map, it will be returned.
|
||||
getColorMapForImageElement(el: ExcalidrawElement): ColorMap;
|
||||
|
||||
// Retrieves the color map for an SVG image element.
|
||||
// The color map contains information about the fill and stroke colors used in the SVG.
|
||||
// If the element already has a color map, it will be merged with the colors extracted from the SVG.
|
||||
getColorMapForImgElement(el: ExcalidrawElement): Promise<SVGColorInfo>;
|
||||
|
||||
// Extracts the fill (background) and stroke colors from an Excalidraw file and returns them as an SVGColorInfo.
|
||||
getColosFromExcalidrawFile(file:TFile, img: ExcalidrawImageElement): Promise<SVGColorInfo>;
|
||||
|
||||
// Extracts the fill and stroke colors from an SVG string and returns them as an SVGColorInfo.
|
||||
getColorsFromSVGString(svgString: string): SVGColorInfo;
|
||||
|
||||
// upgraded the addImage function.
|
||||
// 1. It now accepts an object as the input parameter, making your scripts more readable
|
||||
// 2. AddImageOptions now includes colorMap as an optional parameter, this will only have an effect in case of SVGs and nested Excalidraws
|
||||
// 3. The API function is backwards compatible, but I recommend new implementations to use the object based input
|
||||
addImage(opts: AddImageOptions}): Promise<string>;
|
||||
|
||||
interface AddImageOptions {
|
||||
topX: number;
|
||||
topY: number;
|
||||
imageFile: TFile | string;
|
||||
scale?: boolean;
|
||||
anchor?: boolean;
|
||||
colorMap?: ColorMap;
|
||||
}
|
||||
|
||||
type SVGColorInfo = Map<string, {
|
||||
mappedTo: string;
|
||||
fill: boolean;
|
||||
stroke: boolean;
|
||||
}>;
|
||||
|
||||
interface ColorMap {
|
||||
[color: string]: string;
|
||||
};
|
||||
${String.fromCharCode(96,96,96)}
|
||||
- **Line Polygons**: Draw a closed line shape, and it will automatically snap into a polygon. [#9477](https://github.com/excalidraw/excalidraw/pull/9477)
|
||||
- Updated the Split Ellipse and Boolean Operations scripts to support this feature.
|
||||
- When entering line editor mode (CTRL/CMD + click), the lock point is now marked for easier editing. You can break the polygon using the polygon action in the elements panel.
|
||||
- **Popout Override**: The "Open the back-of-the-note for the selected image in a popout window" action now overrides the "Focus on Existing Tab" setting and always opens a new popout.
|
||||
- **Text Arch Enhancements**: The Text Arch script now supports fitting text to a wider range of paths and shapes. Text can also be edited and refitted to different paths.
|
||||
- **Improved Unlock UI**: Single-clicking a locked element now shows an unlock button. [#9546](https://github.com/excalidraw/excalidraw/pull/9546)
|
||||
- **Script Update Alerts**: On startup, Excalidraw will notify you if any installed scripts have available updates.
|
||||
`,
|
||||
"2.7.2":`
|
||||
## Fixed
|
||||
- The plugin did not load on **iOS 16 and older**. [#2170](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2170)
|
||||
- Added empty line between ${String.fromCharCode(96)}# Excalidraw Data${String.fromCharCode(96)} and ${String.fromCharCode(96)}## Text Elements${String.fromCharCode(96)}. This will now follow **correct markdown linting**. [#2168](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2168)
|
||||
- Adding an **embeddable** to view did not **honor the element background and element stroke colors**, even if it was configured in plugin settings. [#2172](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2172)
|
||||
- **Deconstruct selected elements script** did not copy URLs and URIs for images embedded from outside Obsidian. Please update your script from the script library.
|
||||
- When **rearranging tabs in Obsidian**, e.g. having two tabs side by side, and moving one of them to another location, if the tab was an Excalidraw tab, it appeared as non-responsive after the move, until the tab was resized.
|
||||
"2.11.1": `
|
||||
## Fixed:
|
||||
- The new "Screenshot" option in the Export Image dialog was not working properly. [#2339](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2339)
|
||||
|
||||
## Source Code Refactoring
|
||||
- Updated filenames, file locations, and file name letter-casing across the project
|
||||
- Extracted onDrop, onDragover, etc. handlers to DropManger in ExcalidrawView
|
||||
`,
|
||||
"2.7.1":`
|
||||
## Fixed
|
||||
- Deleting excalidraw file from file system while it is open in fullscreen mode in Obsidian causes Obsidian to be stuck in full-screen view [#2161](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2161)
|
||||
- Chinese fonts are not rendered in LaTeX statements [#2162](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2162)
|
||||
- Since Electron 32 (newer Obsidian Desktop installers) drag and drop links from Finder or OS File Explorer did not work. [Electron breaking change](https://www.electronjs.org/docs/latest/breaking-changes#removed-filepath). This is now fixed
|
||||
- Addressed unnecessary image reloads when changing windows in Obsidian
|
||||
`,
|
||||
"2.7.0":`
|
||||
## Fixed
|
||||
- Various Markdown embeddable "fuzziness":
|
||||
- Fixed issues with appearance settings and edit mode toggling when single-click editing is enabled.
|
||||
- Ensured embeddable file editing no longer gets interrupted unexpectedly.
|
||||
- **Hover Preview**: Disabled hover preview for back-of-the-note cards to reduce distractions.
|
||||
- **Settings Save**: Fixed an issue where plugin settings unnecessarily saved on every startup.
|
||||
## New from Excalidraw.com
|
||||
- Quarter snap points for diamonds [#9387](https://github.com/excalidraw/excalidraw/pull/9387)
|
||||
- Precise highlights for bindings [#9472](https://github.com/excalidraw/excalidraw/pull/9472)
|
||||
|
||||
## New Features
|
||||
- **Image Cropping Snaps to Objects**: When snapping is enabled in the scene, image cropping now aligns to nearby objects.
|
||||
- **Session Persistence for Pen Mode**: Excalidraw remembers the last pen mode when switching between drawings within the same session.
|
||||
`,
|
||||
"2.11.0": `
|
||||
## New
|
||||
- New "Screenshot" option in the Export Image dialog. This allows you to take a screenshot of the current view, including embedded web pages, youtube videos, and markdown documents. Screenshot is only possible in PNG.
|
||||
- Expose parameter in plugin settings to disable AI functionality [#2325](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2325)
|
||||
- Enable (disable) double-click text editing option in Excalidraw appearance and behavior (based on request on Discord)
|
||||
- Added two new PDF export sizes: "Match image", "HD Screen".
|
||||
- Switch between basic shapes. Quickly change the shape of the selected element by pressing TAB [#9270](https://github.com/excalidraw/excalidraw/pull/9270)
|
||||
- Updated the Scribble Helper Script. Now controls are at the top so your palm does accidently trigger them. I added a new button to insert special characters. Scribble helper now makes use of the new text element wrapping in Excalidraw.
|
||||
|
||||
## Fixed in the plugin
|
||||
- Scaling multiple embeddables at once did not work. [#2276](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2276)
|
||||
- When creating multiple back-of-the-note the second card is not created correctly if autosave has not yet happened.
|
||||
- Drawing reloads while editing the back-of-the-note card in certain cases causes editing to be interrupted.
|
||||
- Moved Excalidraw filetype indicator ✏️ to after filename where other filetype tags are displayed. You can turn the filetype indicator on/off in plugin settings under Miscellaneous.
|
||||
|
||||
## Fixed by Excalidraw.com
|
||||
- Alt-duplicate now preserves the original element. Previously, using Alt to duplicate would swap the original with the new element, leading to unexpected behavior and several downstream issues. [#9403](https://github.com/excalidraw/excalidraw/pull/9403)
|
||||
- When dragging the arrow endpoint, update the binding only on the dragged side [#9367](https://github.com/excalidraw/excalidraw/pull/9367)
|
||||
- Laser pointer trail disappearing on pointerup [#9413](https://github.com/excalidraw/excalidraw/pull/9413) [#9427](https://github.com/excalidraw/excalidraw/pull/9427)
|
||||
`,
|
||||
"2.10.1": `
|
||||
|
||||
## Fixed by Excalidraw.com
|
||||
- Eraser performance improvement regression. Erasing locked elements. [#9400](https://github.com/excalidraw/excalidraw/pull/9400)
|
||||
|
||||
## New
|
||||
- Grid Customization Options in plugin settings (appearance and behavior/grid): You can now selectively show or hide vertical and horizontal grid lines independently. This allows you to create alternative grid styles, such as horizontal-only lined grids instead of the traditional checkered pattern.
|
||||
|
||||
## Fixed in ExcalidrawAutomate
|
||||
- ${String.fromCharCode(96)}ea.createSVG${String.fromCharCode(96)} throws error [#2321](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2321)
|
||||
|
||||
---
|
||||
|
||||
## ❤️ Enjoying the plugin?
|
||||
|
||||
Support my work by checking out my new book, now available for pre-order:
|
||||
[Sketch Your Mind: Nurture a Playful and Creative Brain](https://sketch-your-mind.com) is about visual Personal Knowledge Management. It explores the thinking behind Excalidraw and how it helps you structure and evolve ideas visually. It’s the book I wish I had when I began my own PKM journey.
|
||||
|
||||
<div class="ex-coffee-div"><a href="https://sketch-your-mind.com"><img src="https://raw.githubusercontent.com/zsviczian/sketch-your-mind/refs/heads/main/images/cover-mini.jpg" border="0" alt="Pre-order Sketch Your Mind" height="100%"></a></div>
|
||||
`,
|
||||
"2.10.0": `
|
||||
## New from Excalidraw.com
|
||||
- Lasso select [#9169](https://github.com/excalidraw/excalidraw/pull/9169)
|
||||
- Add container to multiple text elements [#9348](https://github.com/excalidraw/excalidraw/pull/9348)
|
||||
|
||||
## Fixed from Excalidraw.com
|
||||
- Rounded diamond edge elbow arrow U route [#9349](https://github.com/excalidraw/excalidraw/pull/9349)
|
||||
- Improved eraser performance [#9352](https://github.com/excalidraw/excalidraw/pull/9352)
|
||||
- Keep arrow label horizontal [#9364](https://github.com/excalidraw/excalidraw/pull/9364)
|
||||
|
||||
## Fixed in ExcalidrawAutomate
|
||||
- ${String.fromCharCode(96)}ea.addText${String.fromCharCode(96)} did not honor the width parameter.
|
||||
`,
|
||||
"2.9.2":`
|
||||
- More minor fix. Toolbars are not responsive when dynamic styling is turned off. [#2287](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2287)
|
||||
`,
|
||||
"2.9.1":`
|
||||
- Minor emergency fix. Reverting: [#9203](https://github.com/excalidraw/excalidraw/pull/9203)
|
||||
`,
|
||||
"2.9.0":`
|
||||
## New
|
||||
- QoL improvement: The context menu requires a longer press and hold for it to be displayed on mobile devices. When you want to precision adjust an element it happens that you linger on the point for just a little longer and the context menu appears unwantedly.
|
||||
- Elbow arrow improvements [#9236](https://github.com/excalidraw/excalidraw/pull/9236), [#8593](https://github.com/excalidraw/excalidraw/pull/8593), [#9197](https://github.com/excalidraw/excalidraw/pull/9197), [#9191](https://github.com/excalidraw/excalidraw/pull/9191), [#9236](https://github.com/excalidraw/excalidraw/pull/9236)
|
||||
|
||||
## Fixed Obsidian 1.8.9 regressions
|
||||
- Custom references (like #^group) broken in Live Preview in Obsidian 1.8.9 due to translation update [#2279](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2279)
|
||||
- Excalidraw tabs only show on a second click on Obsidian Mobile
|
||||
|
||||
## Refactoring
|
||||
- **Mermaid Diagrams**: Excalidraw now uses its own Mermaid package, breaking future dependencies on Obsidian's Mermaid updates. This ensures stability and includes all fixes and improvements made to Excalidraw Mermaid since February 2024. The plugin file size has increased slightly, but this change significantly improves maintainability while remaining invisible to users.
|
||||
- **MathJax Optimization**: MathJax (LaTeX equation SVG image generation) now loads only on demand, with the package compressed to minimize the startup and file size impact caused by the inclusion of Mermaid.
|
||||
- **On-Demand Language Loading**: Non-English language files are now compressed and load only when needed, counterbalancing the increase in file size due to Mermaid and improving load speeds.
|
||||
- **Codebase Restructuring**: Improved type safety by removing many ${String.fromCharCode(96)}//@ts-ignore${String.fromCharCode(96)} commands and enhancing modularity. Introduced new management classes: **CommandManager**, **EventManager**, **PluginFileManager**, **ObserverManager**, and **PackageManager**. Further restructuring is planned for upcoming releases to improve maintainability and stability.
|
||||
- The Excalidraw component moved to React 19. Obsidian for now remains on React 18. This refactoring ensures that Excalidraw continues to work in Obsidian and Obsidian will receive future Excalidraw updates. [#9182](https://github.com/excalidraw/excalidraw/pull/9182)
|
||||
`,
|
||||
"2.6.8":`
|
||||
"2.8.3":`
|
||||
## Fixed
|
||||
- Chinese translation not available since 2.8.0. [#2247](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2247)
|
||||
- Since the most recent Samsung Android update, adding images from the gallery returns an Unsupported Image Type error. [#2245](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2245)
|
||||
- Duplicating/removing frame while children selected [#9079](https://github.com/excalidraw/excalidraw/pull/9079)
|
||||
`,
|
||||
"2.8.2":`
|
||||
## New
|
||||
- **QoL improvements**:
|
||||
- Obsidian-link search button in Element Link Editor.
|
||||
- Add Any File now searches file aliases as well.
|
||||
- Cosmetic changes to file search modals (display path, show file type icon).
|
||||
- Text Element cursor-color matches the text color.
|
||||
- New script in script store: [Image Occlusion](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Image%20Occlusion.md) by [@TrillStones](https://github.com/TrillStones) 🙏
|
||||
- Moved "Create new drawing" option up in the context menu [#2243](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2243)
|
||||
|
||||
## Fixed
|
||||
- Excalidraw icon on the **ribbon menu kept reappearing** every time you reopen Obsidian [#2115](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2115)
|
||||
- In pen mode, when **single-finger panning** is enabled, Excalidraw should still **allow actions with the mouse**.
|
||||
- When **editing a drawing in split mode** (drawing is on one side, markdown view is on the other), editing the markdown note sometimes causes the drawing to re-zoom and jump away from the selected area.
|
||||
- Hover-Editor compatibility resolved [2041](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2041)
|
||||
- ${String.fromCharCode(96)}ExcalidrawAutomate.create() ${String.fromCharCode(96)} will now correctly include the markdown text in templates above Excalidraw Data and below YAML front matter. This also fixes the same issue with the **Deconstruct Selected Element script**.
|
||||
|
||||
- In rare cases drawing content gets overwritten with another drawing [#2152](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2152)
|
||||
- "Wrap selection in frame" sets dark mode to light mode [#2240](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2240)
|
||||
- Multiple bug fixes from Excalidraw.com
|
||||
- Elbow arrows within boxes [#9077](https://github.com/excalidraw/excalidraw/issues/9077)
|
||||
- Elbow arrow orthogonality [#9073](https://github.com/excalidraw/excalidraw/pull/9073)
|
||||
- Improve library sidebar performance [#9060](https://github.com/excalidraw/excalidraw/pull/9060)
|
||||
- Opacity slider now displays numerical value [#9009](https://github.com/excalidraw/excalidraw/pull/9009)
|
||||
- Resize a frame and its children together when box selecting the frame and its children together [#9031](https://github.com/excalidraw/excalidraw/pull/9031)
|
||||
- Excalidraw screen flickering in dark mode [#9057](https://github.com/excalidraw/excalidraw/pull/9057)
|
||||
`,
|
||||
"2.6.7":`
|
||||
Hoping to finally move on to 2.7.0... but still have one last bug to fix in 2.6.x!
|
||||
"2.8.1":`
|
||||
## Fixed
|
||||
- Unable to open Excalidraw files after the 2.8.0 update. [#2235](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2235)
|
||||
`,
|
||||
"2.8.0":`
|
||||
<div class="excalidraw-videoWrapper"><div>
|
||||
<iframe src="https://www.youtube.com/embed/tWi5xTUTz7E" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
|
||||
</div></div>
|
||||
|
||||
## New
|
||||
- Updated "Export Image" dialog
|
||||
- 🚀 PDF Export option including tiling of images over multiple pages. Only available on desktop :(
|
||||
- SVG to clipboard
|
||||
- More granular setting for padding and scale
|
||||
- Slideshow script can now print slides to PDF (update script from script store)
|
||||
- Set local graph to show the links in the embeddable when it is activated/deactivated [#2200](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2200)
|
||||
|
||||
## Fixed
|
||||
I misread a line in the Excalidraw package code... ended up breaking image loading in 2.6.6. The icon library script didn't work right, and updating nested drawings caused all images in the scene to be dropped from memory. This led to image-placeholders in exports and broke copy-paste to Excalidraw.com and between drawings. I am surprised no one reported it! 😳
|
||||
`,
|
||||
"2.6.6":`
|
||||
## Fixed
|
||||
- Images and LaTeX formulas did not update in the scene when the source was changed until the Excalidraw drawing was closed and reopened. [#2105](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2105)
|
||||
`,
|
||||
"2.6.5":`
|
||||
## Fixed
|
||||
- Text sizing issue in the drawing that is first loaded after Obsidian restarts [#2086](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2086)
|
||||
- Excalidraw didn't load if there was a file in the Excalidraw folder with a name that starts the same way as the Scripts folder name. [#2095](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2095)
|
||||
- **OVERSIZED EXCALIDRAW TOOLBAR**: Added a new setting under "Excalidraw Appearance and Behavior > Theme and Styling" called "Limit Obsidian Font Size to Editor Text." This setting is off by default. When enabled, it restricts Obsidian's custom font size adjustments to editor text only, preventing unintended scaling of Excalidraw UI elements and other themes that rely on the default interface font size. Feel free to experiment with this setting to improve Excalidraw UI consistency. However, because this change affects the broader Obsidian UI, it's recommended to turn it off if any layout issues arise. [#2087](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2087)`,
|
||||
"2.6.4":`
|
||||
## Fixed
|
||||
- Error saving when cropping images embedded from a URL (not from a file in the Vault) [#2096](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2096)
|
||||
- Fixed several LaTeX issues. 🙏 @Sintuz [#1631](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1631), [#2195](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2195), [#1842](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1842)
|
||||
- Fixed support for *.jfif and *.avif images [#2212](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2212)
|
||||
- PDF++ selection is not correctly showing after embedded into a drawing (for some specific files) [#2213](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2213)
|
||||
- iOS 18 can't upload image and library [#2182](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2182)
|
||||
- Image block references are broken in hover previews [#2218](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2218)
|
||||
- ⚠️ Note there is a known issue in Obsidian 1.8.2 ⚠️ affecting preview windows in Excalidraw. I received confirmation that this will be fixed in 1.8.3. For now, if hover previews are important to you, you can downgrade to Obsidian 1.8.1 [#2228](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2225)
|
||||
- Mobile elements panel and context menu are not scrollable [#2216](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2216)
|
||||
- "Local Font" menu disappears when opening a drawing in an Obsidian popout-window [#2205](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2205)
|
||||
|
||||
## Updates from Excalidraw.com
|
||||
- Pressing delete on a frame will only delete the children [#9011](https://github.com/excalidraw/excalidraw/pull/9011)
|
||||
- New crowfoot arrowheads and a new arrowhead picker [#8942](https://github.com/excalidraw/excalidraw/pull/8942)
|
||||
- Fixed some of the arrow binding issues [#9010](https://github.com/excalidraw/excalidraw/pull/9010), [#2209](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2209)
|
||||
- New context menu action: "Wrap selection in frame" [#9005](https://github.com/excalidraw/excalidraw/pull/9005)
|
||||
- Elbow arrow segment fixing and positioning [#8952](https://github.com/excalidraw/excalidraw/pull/8952)
|
||||
- When drag creating a new frame, do not add a partial group to it. When wrapping a selected partial group in a frame however, do add it to the wrapping frame. But such that it should be separated from the previous containing group. [#9014](https://github.com/excalidraw/excalidraw/pull/9014)
|
||||
|
||||
## New in ExcalidrawAutomate
|
||||
- New hook: ${String.fromCharCode(96)}onImageFileNameHook${String.fromCharCode(96)}. When set, this callback is triggered when a image is being saved in Excalidraw.
|
||||
- PDF export functions, paving the way for slideshow to export slides to PDF
|
||||
${String.fromCharCode(96,96,96)}ts
|
||||
/**
|
||||
* Returns the dimensions of a standard page size in pixels.
|
||||
*/
|
||||
function getPagePDFDimensions(
|
||||
pageSize: PageSize,
|
||||
orientation: PageOrientation
|
||||
): PageDimensions;
|
||||
|
||||
/**
|
||||
* Creates a PDF from the provided SVG elements with specified scaling and page properties.
|
||||
*/
|
||||
function createPDF(props: {
|
||||
SVG: SVGSVGElement[];
|
||||
scale?: PDFExportScale;
|
||||
pageProps?: PDFPageProperties;
|
||||
filename: string;
|
||||
}): Promise<void>;
|
||||
|
||||
/**
|
||||
* Creates an SVG representation of the current view.
|
||||
*/
|
||||
function createViewSVG(props : {
|
||||
withBackground?: boolean;
|
||||
theme?: "light" | "dark";
|
||||
frameRendering?: FrameRenderingOptions;
|
||||
padding?: number;
|
||||
selectedOnly?: boolean;
|
||||
skipInliningFonts?: boolean;
|
||||
embedScene?: boolean;
|
||||
}): Promise<SVGSVGElement>;
|
||||
|
||||
/**
|
||||
* If set, this callback is triggered when a image is being saved in Excalidraw.
|
||||
* You can use this callback to customize the naming and path of pasted images to avoid
|
||||
* default names like "Pasted image 123147170.png" being saved in the attachments folder,
|
||||
* and instead use more meaningful names based on the Excalidraw file or other criteria,
|
||||
* plus save the image in a different folder.
|
||||
*
|
||||
* If the function returns null or undefined, the normal Excalidraw operation will continue
|
||||
* with the excalidraw generated name and default path.
|
||||
* If a filepath is returned, that will be used. Include the full Vault filepath and filename
|
||||
* with the file extension.
|
||||
* The currentImageName is the name of the image generated by excalidraw or provided during paste.
|
||||
*/
|
||||
function onImageFilePathHook: (data: {
|
||||
currentImageName: string;
|
||||
drawingFilePath: string;
|
||||
}) => string = null;
|
||||
${String.fromCharCode(96,96,96)}
|
||||
`,
|
||||
};
|
||||
|
||||
@@ -5,7 +5,7 @@ import { t } from "src/lang/helpers";
|
||||
export interface PDFExportSettings {
|
||||
pageSize: PageSize;
|
||||
pageOrientation: PageOrientation;
|
||||
fitToPage: boolean;
|
||||
fitToPage: number;
|
||||
paperColor: "white" | "scene" | "custom";
|
||||
customPaperColor: string;
|
||||
alignment: PDFPageAlignment;
|
||||
@@ -21,6 +21,10 @@ export class PDFExportSettingsComponent {
|
||||
if (!update) this.update = () => {};
|
||||
}
|
||||
|
||||
isOrientationAndTilingVisible() {
|
||||
return !(this.settings.pageSize === "HD Screen" || this.settings.pageSize === "MATCH IMAGE");
|
||||
}
|
||||
|
||||
render() {
|
||||
const pageSizeOptions: Record<string, string> = Object.keys(STANDARD_PAGE_SIZES)
|
||||
.reduce((acc, key) => ({
|
||||
@@ -28,6 +32,8 @@ export class PDFExportSettingsComponent {
|
||||
[key]: key
|
||||
}), {});
|
||||
|
||||
let div: HTMLDivElement;
|
||||
|
||||
new Setting(this.contentEl)
|
||||
.setName(t("EXPORTDIALOG_PAGE_SIZE"))
|
||||
.addDropdown(dropdown =>
|
||||
@@ -36,11 +42,15 @@ export class PDFExportSettingsComponent {
|
||||
.setValue(this.settings.pageSize)
|
||||
.onChange(value => {
|
||||
this.settings.pageSize = value as PageSize;
|
||||
div.style.display = this.isOrientationAndTilingVisible() ? "block" : "none";
|
||||
this.update();
|
||||
})
|
||||
);
|
||||
|
||||
new Setting(this.contentEl)
|
||||
div = this.contentEl.createDiv();
|
||||
div.style.display = this.isOrientationAndTilingVisible() ? "block" : "none";
|
||||
|
||||
new Setting(div)
|
||||
.setName(t("EXPORTDIALOG_PAGE_ORIENTATION"))
|
||||
.addDropdown(dropdown =>
|
||||
dropdown
|
||||
@@ -54,18 +64,26 @@ export class PDFExportSettingsComponent {
|
||||
this.update();
|
||||
})
|
||||
);
|
||||
|
||||
new Setting(this.contentEl)
|
||||
|
||||
new Setting(div)
|
||||
.setName(t("EXPORTDIALOG_PDF_FIT_TO_PAGE"))
|
||||
.addDropdown(dropdown =>
|
||||
dropdown
|
||||
.addOptions({
|
||||
"scale": t("EXPORTDIALOG_PDF_SCALE_OPTION"),
|
||||
"fit": t("EXPORTDIALOG_PDF_FIT_OPTION"),
|
||||
"scale": t("EXPORTDIALOG_PDF_SCALE_OPTION")
|
||||
"fit-2": t("EXPORTDIALOG_PDF_FIT_2_OPTION"),
|
||||
"fit-4": t("EXPORTDIALOG_PDF_FIT_4_OPTION"),
|
||||
"fit-6": t("EXPORTDIALOG_PDF_FIT_6_OPTION"),
|
||||
"fit-8": t("EXPORTDIALOG_PDF_FIT_8_OPTION"),
|
||||
"fit-12": t("EXPORTDIALOG_PDF_FIT_12_OPTION"),
|
||||
"fit-16": t("EXPORTDIALOG_PDF_FIT_16_OPTION")
|
||||
})
|
||||
.setValue(this.settings.fitToPage ? "fit" : "scale")
|
||||
.setValue(this.settings.fitToPage === 1 ? "fit" :
|
||||
(typeof this.settings.fitToPage === "number" ? `fit-${this.settings.fitToPage}` : "scale"))
|
||||
.onChange(value => {
|
||||
this.settings.fitToPage = value === "fit";
|
||||
this.settings.fitToPage = value === "scale" ? 0 :
|
||||
(value === "fit" ? 1 : parseInt(value.split("-")[1]));
|
||||
this.update();
|
||||
})
|
||||
);
|
||||
@@ -121,6 +139,8 @@ export class PDFExportSettingsComponent {
|
||||
dropdown
|
||||
.addOptions({
|
||||
"center": t("EXPORTDIALOG_PDF_ALIGN_CENTER"),
|
||||
"center-left": t("EXPORTDIALOG_PDF_ALIGN_CENTER_LEFT"),
|
||||
"center-right": t("EXPORTDIALOG_PDF_ALIGN_CENTER_RIGHT"),
|
||||
"top-left": t("EXPORTDIALOG_PDF_ALIGN_TOP_LEFT"),
|
||||
"top-center": t("EXPORTDIALOG_PDF_ALIGN_TOP_CENTER"),
|
||||
"top-right": t("EXPORTDIALOG_PDF_ALIGN_TOP_RIGHT"),
|
||||
|
||||
@@ -13,7 +13,7 @@ import ExcalidrawView from "../../view/ExcalidrawView";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { escapeRegExp, getLinkParts, sleep } from "../../utils/utils";
|
||||
import { getLeaf, openLeaf } from "../../utils/obsidianUtils";
|
||||
import { checkAndCreateFolder, splitFolderAndFilename } from "src/utils/fileUtils";
|
||||
import { createOrOverwriteFile } from "src/utils/fileUtils";
|
||||
import { KeyEvent, isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { ExcalidrawElement, getEA } from "src/core";
|
||||
@@ -22,8 +22,7 @@ import { MAX_IMAGE_SIZE, REG_LINKINDEX_INVALIDCHARS } from "src/constants/consta
|
||||
import { REGEX_LINK, REGEX_TAGS } from "../ExcalidrawData";
|
||||
import { ScriptEngine } from "../Scripts";
|
||||
import { openExternalLink, openTagSearch, parseObsidianLink } from "src/utils/excalidrawViewUtils";
|
||||
|
||||
export type ButtonDefinition = { caption: string; tooltip?:string; action: Function };
|
||||
import { ButtonDefinition } from "src/types/promptTypes";
|
||||
|
||||
export class Prompt extends Modal {
|
||||
private promptEl: HTMLInputElement;
|
||||
@@ -98,6 +97,9 @@ export class GenericInputPrompt extends Modal {
|
||||
private selectionUpdateTimer: number = 0;
|
||||
private customComponents: (container: HTMLElement) => void;
|
||||
private blockPointerInputOutsideModal: boolean = false;
|
||||
private controlsOnTop: boolean = false;
|
||||
private draggable: boolean = false;
|
||||
private cleanupDragListeners: (() => void) | null = null;
|
||||
|
||||
public static Prompt(
|
||||
view: ExcalidrawView,
|
||||
@@ -111,6 +113,8 @@ export class GenericInputPrompt extends Modal {
|
||||
displayEditorButtons?: boolean,
|
||||
customComponents?: (container: HTMLElement) => void,
|
||||
blockPointerInputOutsideModal?: boolean,
|
||||
controlsOnTop?: boolean,
|
||||
draggable?: boolean,
|
||||
): Promise<string> {
|
||||
const newPromptModal = new GenericInputPrompt(
|
||||
view,
|
||||
@@ -124,6 +128,8 @@ export class GenericInputPrompt extends Modal {
|
||||
displayEditorButtons,
|
||||
customComponents,
|
||||
blockPointerInputOutsideModal,
|
||||
controlsOnTop,
|
||||
draggable,
|
||||
);
|
||||
return newPromptModal.waitForClose;
|
||||
}
|
||||
@@ -140,6 +146,8 @@ export class GenericInputPrompt extends Modal {
|
||||
displayEditorButtons?: boolean,
|
||||
customComponents?: (container: HTMLElement) => void,
|
||||
blockPointerInputOutsideModal?: boolean,
|
||||
controlsOnTop?: boolean,
|
||||
draggable?: boolean,
|
||||
) {
|
||||
super(app);
|
||||
this.view = view;
|
||||
@@ -151,6 +159,8 @@ export class GenericInputPrompt extends Modal {
|
||||
this.displayEditorButtons = this.lines > 1 ? (displayEditorButtons ?? false) : false;
|
||||
this.customComponents = customComponents;
|
||||
this.blockPointerInputOutsideModal = blockPointerInputOutsideModal ?? false;
|
||||
this.controlsOnTop = controlsOnTop ?? false;
|
||||
this.draggable = draggable ?? false;
|
||||
|
||||
this.waitForClose = new Promise<string>((resolve, reject) => {
|
||||
this.resolvePromise = resolve;
|
||||
@@ -173,13 +183,29 @@ export class GenericInputPrompt extends Modal {
|
||||
this.titleEl.textContent = this.header;
|
||||
|
||||
const mainContentContainer: HTMLDivElement = this.contentEl.createDiv();
|
||||
this.inputComponent = this.createInputField(
|
||||
mainContentContainer,
|
||||
this.placeholder,
|
||||
this.input
|
||||
);
|
||||
this.customComponents?.(mainContentContainer);
|
||||
this.createButtonBar(mainContentContainer);
|
||||
|
||||
// Conditionally order elements based on controlsOnTop flag
|
||||
if (this.controlsOnTop) {
|
||||
// Create button bar first
|
||||
this.customComponents?.(mainContentContainer);
|
||||
this.createButtonBar(mainContentContainer);
|
||||
|
||||
// Then add input field and custom components
|
||||
this.inputComponent = this.createInputField(
|
||||
mainContentContainer,
|
||||
this.placeholder,
|
||||
this.input
|
||||
);
|
||||
} else {
|
||||
// Original order: input field, custom components, then buttons
|
||||
this.inputComponent = this.createInputField(
|
||||
mainContentContainer,
|
||||
this.placeholder,
|
||||
this.input
|
||||
);
|
||||
this.customComponents?.(mainContentContainer);
|
||||
this.createButtonBar(mainContentContainer);
|
||||
}
|
||||
}
|
||||
|
||||
protected createInputField(
|
||||
@@ -240,12 +266,8 @@ export class GenericInputPrompt extends Modal {
|
||||
|
||||
private createButtonBar(mainContentContainer: HTMLDivElement) {
|
||||
const buttonBarContainer: HTMLDivElement = mainContentContainer.createDiv();
|
||||
buttonBarContainer.style.display = "flex";
|
||||
buttonBarContainer.style.justifyContent = "space-between";
|
||||
buttonBarContainer.style.marginTop = "1rem";
|
||||
|
||||
buttonBarContainer.addClass(`excalidraw-prompt-buttonbar-${this.controlsOnTop ? "top" : "bottom"}`);
|
||||
const editorButtonContainer: HTMLDivElement = buttonBarContainer.createDiv();
|
||||
|
||||
const actionButtonContainer: HTMLDivElement = buttonBarContainer.createDiv();
|
||||
|
||||
if (this.buttons && this.buttons.length > 0) {
|
||||
@@ -279,6 +301,7 @@ export class GenericInputPrompt extends Modal {
|
||||
this.createButton(editorButtonContainer, "⏎", ()=>this.insertStringBtnClickCallback("\n"), t("PROMPT_BUTTON_INSERT_LINE"), "0");
|
||||
this.createButton(editorButtonContainer, "⌫", this.delBtnClickCallback.bind(this), "Delete");
|
||||
this.createButton(editorButtonContainer, "⎵", ()=>this.insertStringBtnClickCallback(" "), t("PROMPT_BUTTON_INSERT_SPACE"));
|
||||
this.createButton(editorButtonContainer, "§", this.specialCharsBtnClickCallback.bind(this), t("PROMPT_BUTTON_SPECIAL_CHARS"));
|
||||
if(this.view) {
|
||||
this.createButton(editorButtonContainer, "🔗", this.linkBtnClickCallback.bind(this), t("PROMPT_BUTTON_INSERT_LINK"));
|
||||
}
|
||||
@@ -384,16 +407,209 @@ export class GenericInputPrompt extends Modal {
|
||||
);
|
||||
}
|
||||
|
||||
private specialCharsBtnClickCallback = (evt: MouseEvent) => {
|
||||
this.view.ownerWindow.clearTimeout(this.selectionUpdateTimer);
|
||||
|
||||
// Remove any existing popup
|
||||
const existingPopup = document.querySelector('.excalidraw-special-chars-popup');
|
||||
if (existingPopup) {
|
||||
existingPopup.remove();
|
||||
return;
|
||||
}
|
||||
|
||||
// Create popup element
|
||||
const popup = document.createElement('div');
|
||||
popup.className = 'excalidraw-special-chars-popup';
|
||||
popup.style.position = 'absolute';
|
||||
popup.style.zIndex = '1000';
|
||||
popup.style.background = 'var(--background-primary)';
|
||||
popup.style.border = '1px solid var(--background-modifier-border)';
|
||||
popup.style.borderRadius = '4px';
|
||||
popup.style.padding = '4px';
|
||||
popup.style.boxShadow = '0 2px 8px var(--background-modifier-box-shadow)';
|
||||
popup.style.display = 'flex';
|
||||
popup.style.flexWrap = 'wrap';
|
||||
popup.style.maxWidth = '200px';
|
||||
|
||||
// Position near the button
|
||||
const rect = (evt.target as HTMLElement).getBoundingClientRect();
|
||||
popup.style.top = `${rect.bottom + 5}px`;
|
||||
popup.style.left = `${rect.left}px`;
|
||||
|
||||
// Special characters to include
|
||||
const specialChars = [',', '.', ':', ';', '!', '?', '"', '{', '}', '[', ']', '(', ')'];
|
||||
|
||||
// Add character buttons
|
||||
specialChars.forEach(char => {
|
||||
const charButton = document.createElement('button');
|
||||
charButton.textContent = char;
|
||||
charButton.style.margin = '2px';
|
||||
charButton.style.width = '28px';
|
||||
charButton.style.height = '28px';
|
||||
charButton.style.cursor = 'pointer';
|
||||
charButton.style.background = 'var(--interactive-normal)';
|
||||
charButton.style.border = 'none';
|
||||
charButton.style.borderRadius = '4px';
|
||||
|
||||
charButton.addEventListener('click', () => {
|
||||
this.insertStringBtnClickCallback(char);
|
||||
popup.remove();
|
||||
});
|
||||
|
||||
popup.appendChild(charButton);
|
||||
});
|
||||
|
||||
// Add click outside listener to close popup
|
||||
const closePopupListener = (e: MouseEvent) => {
|
||||
if (!popup.contains(e.target as Node) &&
|
||||
(evt.target as HTMLElement) !== e.target) {
|
||||
popup.remove();
|
||||
document.removeEventListener('click', closePopupListener);
|
||||
}
|
||||
};
|
||||
|
||||
// Add to document and set up listeners
|
||||
document.body.appendChild(popup);
|
||||
setTimeout(() => {
|
||||
document.addEventListener('click', closePopupListener);
|
||||
}, 10);
|
||||
}
|
||||
|
||||
onOpen() {
|
||||
super.onOpen();
|
||||
this.inputComponent.inputEl.focus();
|
||||
this.inputComponent.inputEl.select();
|
||||
|
||||
if (this.draggable) {
|
||||
this.makeModalDraggable();
|
||||
}
|
||||
}
|
||||
|
||||
private makeModalDraggable() {
|
||||
let isDragging = false;
|
||||
let startX: number, startY: number, initialX: number, initialY: number;
|
||||
let activeElement: HTMLElement | null = null;
|
||||
let cursorPosition: { start: number; end: number } | null = null;
|
||||
|
||||
const modalEl = this.modalEl;
|
||||
const header = modalEl.querySelector('.modal-titlebar') || modalEl.querySelector('.modal-title') || modalEl;
|
||||
(header as HTMLElement).style.cursor = 'move';
|
||||
|
||||
// Track focus changes to store the last focused interactive element
|
||||
const onFocusIn = (e: FocusEvent) => {
|
||||
const target = e.target as HTMLElement;
|
||||
if (target && (target.tagName === 'SELECT' || target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.tagName === 'BUTTON')) {
|
||||
activeElement = target;
|
||||
// Store cursor position for input/textarea elements (but not for number inputs)
|
||||
if (target.tagName === 'TEXTAREA' ||
|
||||
(target.tagName === 'INPUT' && (target as HTMLInputElement).type !== 'number')) {
|
||||
const inputEl = target as HTMLInputElement | HTMLTextAreaElement;
|
||||
cursorPosition = {
|
||||
start: inputEl.selectionStart || 0,
|
||||
end: inputEl.selectionEnd || 0
|
||||
};
|
||||
} else {
|
||||
cursorPosition = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const onPointerDown = (e: PointerEvent) => {
|
||||
const target = e.target as HTMLElement;
|
||||
|
||||
// Don't allow dragging if clicking on interactive controls
|
||||
if (target.tagName === 'INPUT' ||
|
||||
target.tagName === 'TEXTAREA' ||
|
||||
target.tagName === 'BUTTON' ||
|
||||
target.tagName === 'SELECT' ||
|
||||
target.closest('button') ||
|
||||
target.closest('input') ||
|
||||
target.closest('textarea') ||
|
||||
target.closest('select')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Allow dragging from header or modal content areas
|
||||
if (!header.contains(target) && !modalEl.querySelector('.modal-content')?.contains(target)) {
|
||||
return;
|
||||
}
|
||||
|
||||
isDragging = true;
|
||||
startX = e.clientX;
|
||||
startY = e.clientY;
|
||||
const rect = modalEl.getBoundingClientRect();
|
||||
initialX = rect.left;
|
||||
initialY = rect.top;
|
||||
|
||||
modalEl.style.position = 'absolute';
|
||||
modalEl.style.margin = '0';
|
||||
modalEl.style.left = `${initialX}px`;
|
||||
modalEl.style.top = `${initialY}px`;
|
||||
};
|
||||
|
||||
const onPointerMove = (e: PointerEvent) => {
|
||||
if (!isDragging) return;
|
||||
|
||||
const dx = e.clientX - startX;
|
||||
const dy = e.clientY - startY;
|
||||
|
||||
modalEl.style.left = `${initialX + dx}px`;
|
||||
modalEl.style.top = `${initialY + dy}px`;
|
||||
};
|
||||
|
||||
const onPointerUp = () => {
|
||||
if (!isDragging) return;
|
||||
isDragging = false;
|
||||
|
||||
// Restore focus and cursor position
|
||||
if (activeElement && activeElement.isConnected) {
|
||||
// Use setTimeout to ensure the pointer event is fully processed
|
||||
setTimeout(() => {
|
||||
activeElement.focus();
|
||||
|
||||
// Restore cursor position for input/textarea elements (but not for number inputs)
|
||||
if (cursorPosition &&
|
||||
(activeElement.tagName === 'TEXTAREA' ||
|
||||
(activeElement.tagName === 'INPUT' && (activeElement as HTMLInputElement).type !== 'number'))) {
|
||||
const inputEl = activeElement as HTMLInputElement | HTMLTextAreaElement;
|
||||
inputEl.setSelectionRange(cursorPosition.start, cursorPosition.end);
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
};
|
||||
|
||||
// Initialize activeElement with the main input field
|
||||
activeElement = this.inputComponent.inputEl;
|
||||
cursorPosition = {
|
||||
start: this.inputComponent.inputEl.selectionStart || 0,
|
||||
end: this.inputComponent.inputEl.selectionEnd || 0
|
||||
};
|
||||
|
||||
// Set up event listeners
|
||||
modalEl.addEventListener('focusin', onFocusIn);
|
||||
modalEl.addEventListener('pointerdown', onPointerDown);
|
||||
document.addEventListener('pointermove', onPointerMove);
|
||||
document.addEventListener('pointerup', onPointerUp);
|
||||
|
||||
// Store cleanup function for use in onClose
|
||||
this.cleanupDragListeners = () => {
|
||||
modalEl.removeEventListener('focusin', onFocusIn);
|
||||
modalEl.removeEventListener('pointerdown', onPointerDown);
|
||||
document.removeEventListener('pointermove', onPointerMove);
|
||||
document.removeEventListener('pointerup', onPointerUp);
|
||||
};
|
||||
}
|
||||
|
||||
onClose() {
|
||||
super.onClose();
|
||||
this.resolveInput();
|
||||
this.removeInputListener();
|
||||
|
||||
// Clean up drag listeners to prevent memory leaks
|
||||
if (this.cleanupDragListeners) {
|
||||
this.cleanupDragListeners();
|
||||
this.cleanupDragListeners = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -576,10 +792,7 @@ export class NewFileActions extends Modal {
|
||||
if (!this.path.match(/\.md$/)) {
|
||||
this.path = `${this.path}.md`;
|
||||
}
|
||||
const folderpath = splitFolderAndFilename(this.path).folderpath;
|
||||
checkAndCreateFolder(folderpath);
|
||||
const f = await this.app.vault.create(this.path, data);
|
||||
return f;
|
||||
return await createOrOverwriteFile(this.app, this.path, data);
|
||||
};
|
||||
|
||||
if(this.sourceElement) {
|
||||
@@ -641,17 +854,30 @@ export class NewFileActions extends Modal {
|
||||
}
|
||||
}
|
||||
|
||||
export class ConfirmationPrompt extends Modal {
|
||||
public waitForClose: Promise<boolean>;
|
||||
private resolvePromise: (value: boolean) => void;
|
||||
export class MultiOptionConfirmationPrompt extends Modal {
|
||||
public waitForClose: Promise<any>;
|
||||
private resolvePromise: (value: any) => void;
|
||||
private rejectPromise: (reason?: any) => void;
|
||||
private didConfirm: boolean = false;
|
||||
private selectedValue: any = null;
|
||||
private readonly message: string;
|
||||
private readonly buttons: Map<string, any>;
|
||||
private ctaButtonLabel: string = null;
|
||||
|
||||
constructor(private plugin: ExcalidrawPlugin, message: string) {
|
||||
constructor(private plugin: ExcalidrawPlugin, message: string, buttons?: Map<string, any>, ctaButtonLabel?: string) {
|
||||
super(plugin.app);
|
||||
this.message = message;
|
||||
this.waitForClose = new Promise<boolean>((resolve, reject) => {
|
||||
if (!buttons || buttons.size === 0) {
|
||||
buttons = new Map<string, any>([
|
||||
[t("PROMPT_BUTTON_CANCEL"), null],
|
||||
[t("PROMPT_BUTTON_OK"), true],
|
||||
]);
|
||||
if( !ctaButtonLabel) {
|
||||
ctaButtonLabel = t("PROMPT_BUTTON_OK");
|
||||
}
|
||||
}
|
||||
this.ctaButtonLabel = ctaButtonLabel;
|
||||
this.buttons = buttons;
|
||||
this.waitForClose = new Promise<any>((resolve, reject) => {
|
||||
this.resolvePromise = resolve;
|
||||
this.rejectPromise = reject;
|
||||
});
|
||||
@@ -671,14 +897,35 @@ export class ConfirmationPrompt extends Modal {
|
||||
const buttonContainer = this.contentEl.createDiv();
|
||||
buttonContainer.style.display = "flex";
|
||||
buttonContainer.style.justifyContent = "flex-end";
|
||||
buttonContainer.style.flexWrap = "wrap";
|
||||
|
||||
// Convert Map to Array for easier iteration
|
||||
const buttonEntries = Array.from(this.buttons.entries());
|
||||
|
||||
const cancelButton = this.createButton(buttonContainer, t("PROMPT_BUTTON_CANCEL"), this.cancelClickCallback.bind(this));
|
||||
cancelButton.buttonEl.style.marginRight = "0.5rem";
|
||||
// Add buttons in reverse order (last button will be on the right)
|
||||
let ctaButton: HTMLButtonElement = null;
|
||||
buttonEntries.reverse().forEach(([buttonText, value], index) => {
|
||||
const button = this.createButton(buttonContainer, buttonText, () => {
|
||||
this.selectedValue = value;
|
||||
this.close();
|
||||
});
|
||||
|
||||
if (buttonText === this.ctaButtonLabel) {
|
||||
ctaButton = button.buttonEl;
|
||||
button.setCta();
|
||||
}
|
||||
|
||||
if (index < buttonEntries.length - 1) {
|
||||
button.buttonEl.style.marginRight = "0.5rem";
|
||||
}
|
||||
});
|
||||
|
||||
const confirmButton = this.createButton(buttonContainer, t("PROMPT_BUTTON_OK"), this.confirmClickCallback.bind(this));
|
||||
confirmButton.buttonEl.style.marginRight = "0";
|
||||
|
||||
cancelButton.buttonEl.focus();
|
||||
// Set focus on the first button (visually last)
|
||||
if(this.ctaButtonLabel) {
|
||||
if (ctaButton) {
|
||||
ctaButton.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private createButton(container: HTMLElement, text: string, callback: (evt: MouseEvent) => void) {
|
||||
@@ -687,16 +934,6 @@ export class ConfirmationPrompt extends Modal {
|
||||
return button;
|
||||
}
|
||||
|
||||
private cancelClickCallback() {
|
||||
this.didConfirm = false;
|
||||
this.close();
|
||||
};
|
||||
|
||||
private confirmClickCallback() {
|
||||
this.didConfirm = true;
|
||||
this.close();
|
||||
};
|
||||
|
||||
onOpen() {
|
||||
super.onOpen();
|
||||
this.contentEl.querySelector("button")?.focus();
|
||||
@@ -704,11 +941,7 @@ export class ConfirmationPrompt extends Modal {
|
||||
|
||||
onClose() {
|
||||
super.onClose();
|
||||
if (!this.didConfirm) {
|
||||
this.resolvePromise(false);
|
||||
} else {
|
||||
this.resolvePromise(true);
|
||||
}
|
||||
this.resolvePromise(this.selectedValue);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,8 +25,10 @@ export class ReleaseNotes extends Modal {
|
||||
async onClose() {
|
||||
this.contentEl.empty();
|
||||
await this.plugin.loadSettings();
|
||||
this.plugin.settings.previousRelease = PLUGIN_VERSION
|
||||
await this.plugin.saveSettings();
|
||||
if(this.plugin.settings.previousRelease !== PLUGIN_VERSION) {
|
||||
this.plugin.settings.previousRelease = PLUGIN_VERSION;
|
||||
await this.plugin.saveSettings();
|
||||
}
|
||||
}
|
||||
|
||||
async createForm() {
|
||||
@@ -39,7 +41,8 @@ export class ReleaseNotes extends Modal {
|
||||
.slice(0, 10)
|
||||
.join("\n\n---\n")
|
||||
: FIRST_RUN;
|
||||
await MarkdownRenderer.renderMarkdown(
|
||||
await MarkdownRenderer.render(
|
||||
this.app,
|
||||
message,
|
||||
this.contentEl,
|
||||
"",
|
||||
|
||||
@@ -1,80 +1,27 @@
|
||||
import { MarkdownRenderer, Modal, Notice, request } from "obsidian";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { errorlog, escapeRegExp } from "../../utils/utils";
|
||||
import { errorlog } from "../../utils/utils";
|
||||
import { log } from "src/utils/debugHelper";
|
||||
import { ContentSearcher } from "../components/ContentSearcher";
|
||||
|
||||
const URL =
|
||||
"https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/index-new.md";
|
||||
|
||||
export class ScriptInstallPrompt extends Modal {
|
||||
private contentDiv: HTMLDivElement;
|
||||
|
||||
constructor(private plugin: ExcalidrawPlugin) {
|
||||
super(plugin.app);
|
||||
// this.titleEl.setText(t("INSTAL_MODAL_TITLE"));
|
||||
}
|
||||
|
||||
async onOpen(): Promise<void> {
|
||||
const searchBarWrapper = document.createElement("div");
|
||||
searchBarWrapper.classList.add('search-bar-wrapper');
|
||||
|
||||
|
||||
const searchBar = document.createElement("input");
|
||||
searchBar.type = "text";
|
||||
searchBar.id = "search-bar";
|
||||
searchBar.placeholder = "Search...";
|
||||
//searchBar.style.width = "calc(100% - 120px)"; // space for the buttons and hit count
|
||||
|
||||
const nextButton = document.createElement("button");
|
||||
nextButton.textContent = "→";
|
||||
nextButton.onclick = () => this.navigateSearchResults("next");
|
||||
|
||||
const prevButton = document.createElement("button");
|
||||
prevButton.textContent = "←";
|
||||
prevButton.onclick = () => this.navigateSearchResults("previous");
|
||||
|
||||
const hitCount = document.createElement("span");
|
||||
hitCount.id = "hit-count";
|
||||
hitCount.classList.add('hit-count');
|
||||
|
||||
searchBarWrapper.appendChild(prevButton);
|
||||
searchBarWrapper.appendChild(nextButton);
|
||||
searchBarWrapper.appendChild(searchBar);
|
||||
searchBarWrapper.appendChild(hitCount);
|
||||
|
||||
this.contentEl.prepend(searchBarWrapper);
|
||||
|
||||
searchBar.addEventListener("input", (e) => {
|
||||
this.clearHighlights();
|
||||
const searchTerm = (e.target as HTMLInputElement).value;
|
||||
|
||||
if (searchTerm && searchTerm.length > 0) {
|
||||
this.highlightSearchTerm(searchTerm);
|
||||
const totalHits = this.contentDiv.querySelectorAll("mark.search-highlight").length;
|
||||
hitCount.textContent = totalHits > 0 ? `1/${totalHits}` : "";
|
||||
setTimeout(()=>this.navigateSearchResults("next"));
|
||||
} else {
|
||||
hitCount.textContent = "";
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
searchBar.addEventListener("keydown", (e) => {
|
||||
// If Ctrl/Cmd + F is pressed, focus on search bar
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === "f") {
|
||||
e.preventDefault();
|
||||
searchBar.focus();
|
||||
}
|
||||
// If Enter is pressed, navigate to next result
|
||||
else if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
this.navigateSearchResults(e.shiftKey ? "previous" : "next");
|
||||
}
|
||||
});
|
||||
|
||||
this.contentEl.classList.add("excalidraw-scriptengine-install");
|
||||
this.contentDiv = document.createElement("div");
|
||||
this.contentEl.appendChild(this.contentDiv);
|
||||
|
||||
new ContentSearcher(this.contentDiv);
|
||||
|
||||
this.containerEl.classList.add("excalidraw-scriptengine-install");
|
||||
try {
|
||||
const source = await request({ url: URL });
|
||||
@@ -111,99 +58,6 @@ export class ScriptInstallPrompt extends Modal {
|
||||
}
|
||||
}
|
||||
|
||||
highlightSearchTerm(searchTerm: string): void {
|
||||
// Create a walker to traverse text nodes
|
||||
const walker = document.createTreeWalker(
|
||||
this.contentDiv,
|
||||
NodeFilter.SHOW_TEXT,
|
||||
{
|
||||
acceptNode: (node: Text) => {
|
||||
return node.nodeValue!.toLowerCase().includes(searchTerm.toLowerCase()) ?
|
||||
NodeFilter.FILTER_ACCEPT :
|
||||
NodeFilter.FILTER_REJECT;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const nodesToReplace: Text[] = [];
|
||||
while (walker.nextNode()) {
|
||||
nodesToReplace.push(walker.currentNode as Text);
|
||||
}
|
||||
|
||||
nodesToReplace.forEach(node => {
|
||||
const nodeContent = node.nodeValue!;
|
||||
const newNode = document.createDocumentFragment();
|
||||
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
const regex = new RegExp(escapeRegExp(searchTerm), 'gi');
|
||||
|
||||
// Iterate over all matches in the text node
|
||||
while ((match = regex.exec(nodeContent)) !== null) {
|
||||
const before = document.createTextNode(nodeContent.slice(lastIndex, match.index));
|
||||
const highlighted = document.createElement('mark');
|
||||
highlighted.className = 'search-highlight';
|
||||
highlighted.textContent = match[0];
|
||||
highlighted.classList.add('search-result');
|
||||
|
||||
newNode.appendChild(before);
|
||||
newNode.appendChild(highlighted);
|
||||
|
||||
lastIndex = regex.lastIndex;
|
||||
}
|
||||
newNode.appendChild(document.createTextNode(nodeContent.slice(lastIndex)));
|
||||
node.replaceWith(newNode);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
clearHighlights(): void {
|
||||
this.contentDiv.querySelectorAll("mark.search-highlight").forEach((el) => {
|
||||
el.outerHTML = el.innerHTML;
|
||||
});
|
||||
}
|
||||
|
||||
navigateSearchResults(direction: "next" | "previous"): void {
|
||||
const highlights: HTMLElement[] = Array.from(
|
||||
this.contentDiv.querySelectorAll("mark.search-highlight")
|
||||
);
|
||||
|
||||
if (highlights.length === 0) return;
|
||||
|
||||
const currentActiveIndex = highlights.findIndex((highlight) =>
|
||||
highlight.classList.contains("active-highlight")
|
||||
);
|
||||
|
||||
if (currentActiveIndex !== -1) {
|
||||
highlights[currentActiveIndex].classList.remove("active-highlight");
|
||||
highlights[currentActiveIndex].style.border = "none";
|
||||
}
|
||||
|
||||
let nextActiveIndex = 0;
|
||||
if (direction === "next") {
|
||||
nextActiveIndex =
|
||||
currentActiveIndex === highlights.length - 1
|
||||
? 0
|
||||
: currentActiveIndex + 1;
|
||||
} else if (direction === "previous") {
|
||||
nextActiveIndex =
|
||||
currentActiveIndex === 0
|
||||
? highlights.length - 1
|
||||
: currentActiveIndex - 1;
|
||||
}
|
||||
|
||||
const nextActiveHighlight = highlights[nextActiveIndex];
|
||||
nextActiveHighlight.classList.add("active-highlight");
|
||||
nextActiveHighlight.scrollIntoView({
|
||||
behavior: "smooth",
|
||||
block: "nearest",
|
||||
});
|
||||
|
||||
// Update the hit count
|
||||
const hitCount = document.getElementById("hit-count");
|
||||
hitCount.textContent = `${nextActiveIndex + 1}/${highlights.length}`;
|
||||
}
|
||||
|
||||
onClose(): void {
|
||||
this.contentEl.empty();
|
||||
}
|
||||
|
||||
@@ -31,6 +31,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
desc: "The ExcalidrawPlugin object",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "FloatingModal",
|
||||
code: null,
|
||||
desc: "A modified version of the Obsidian.Modal class that allows the modal to be dragged around the screen and that does not dim the background.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "elementsDict",
|
||||
code: null,
|
||||
@@ -226,14 +232,14 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
},
|
||||
{
|
||||
field: "createPDF",
|
||||
code: "async createPDF({SVG: SVGSVGElement[], scale?: PDFExportScale, pageProps?: PDFPageProperties}): Promise<ArrayBuffer>",
|
||||
desc: "",
|
||||
after: "Creates a PDF from the provided SVG elements with specified scaling and page properties.\n" +
|
||||
code: "async createPDF({SVG: SVGSVGElement[], scale?: PDFExportScale, pageProps?: PDFPageProperties, filename: string}): Promise<void>",
|
||||
desc: "Creates a PDF from the provided SVG elements with specified scaling and page properties.\n" +
|
||||
"\n" +
|
||||
"@param {Object} params - The parameters for creating the PDF.\n" +
|
||||
"@param {SVGSVGElement[]} params.SVG - An array of SVG elements to be included in the PDF. If multiple SVGs are provided, each will be added to a new page.\n" +
|
||||
"@param {PDFExportScale} [params.scale={ fitToPage: true, zoom: 1 }] - The scaling options for the SVG elements.\n" +
|
||||
"@param {PDFPageProperties} [params.pageProps] - The properties for the PDF pages.\n" +
|
||||
"@param {string} params.filename - The name of the PDF file to be created.\n" +
|
||||
"@returns {Promise<ArrayBuffer>} - A promise that resolves to an ArrayBuffer containing the PDF data.\n" +
|
||||
"\n" +
|
||||
"@typedef {Object} PDFExportScale\n" +
|
||||
@@ -241,13 +247,11 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
"@property {number} [zoom=1] - The zoom level for the SVG. Used only if fitToPage is false. If the SVG does not fit the page, it will be tiled over multiple pages.\n" +
|
||||
"\n" +
|
||||
"@typedef {Object} PDFPageProperties\n" +
|
||||
"@property {{width: number, height: number}} [dimensions] - The dimensions of the PDF pages. Use getPageDimensions to get standard page sizes.\n" +
|
||||
"@property {{width: number, height: number}} [dimensions] - The dimensions of the PDF pages in pixels. Use getPageDimensions to get standard page sizes.\n" +
|
||||
"@property {string} [backgroundColor] - The background color of the PDF pages.\n" +
|
||||
"@property {PDFMargin} margin - The margins of the PDF pages.\n" +
|
||||
"@property {PDFPageAlignment} alignment - The alignment of the SVG on the PDF pages.\n" +
|
||||
"\n" +
|
||||
"@example\n" +
|
||||
"const pdfData = await createPDF({\n" +
|
||||
"@property {PDFMargin} margin - The margins of the PDF pages in pixels.\n" +
|
||||
"@property {PDFPageAlignment} alignment - The alignment of the SVG on the PDF pages.",
|
||||
after: "({\n" +
|
||||
" SVG: [svgElement1, svgElement2],\n" +
|
||||
" scale: { fitToPage: true },\n" +
|
||||
" pageProps: {\n" +
|
||||
@@ -255,30 +259,57 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
" backgroundColor: \"#ffffff\",\n" +
|
||||
" margin: { left: 20, right: 20, top: 20, bottom: 20 },\n" +
|
||||
" alignment: \"center\"\n" +
|
||||
" filename: \"myPDF.pdf\"\n" +
|
||||
" }\n" +
|
||||
"});",
|
||||
},
|
||||
{
|
||||
field: "createViewSVG",
|
||||
code: "async createViewSVG({withBackground?: boolean, theme?: 'light' | 'dark', frameRendering?: FrameRenderingOptions, padding?: number, selectedOnly?: boolean, skipInliningFonts?: boolean, embedScene?: boolean}): Promise<SVGSVGElement>",
|
||||
desc: "Creates an SVG representation of the current view with specified options.\n" +
|
||||
"\n" +
|
||||
"@param {Object} options - The options for creating the SVG.\n" +
|
||||
"@param {boolean} [options.withBackground=true] - Whether to include the background in the SVG.\n" +
|
||||
"@param {\"light\" | \"dark\"} [options.theme] - The theme to use for the SVG.\n" +
|
||||
"@param {FrameRenderingOptions} [options.frameRendering={enabled: true, name: true, outline: true, clip: true}] - The frame rendering options.\n" +
|
||||
"@param {number} [options.padding] - The padding to apply around the SVG.\n" +
|
||||
"@param {boolean} [options.selectedOnly=false] - Whether to include only the selected elements in the SVG.\n" +
|
||||
"@param {boolean} [options.skipInliningFonts=false] - Whether to skip inlining fonts in the SVG.\n" +
|
||||
"@param {boolean} [options.embedScene=false] - Whether to embed the scene in the SVG.\n" +
|
||||
"@returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.\n" +
|
||||
"\n" +
|
||||
"@typedef {Object} FrameRenderingOptions\n" +
|
||||
"@property {boolean} enabled - Whether frame rendering is enabled.\n" +
|
||||
"@property {boolean} name - Whether to include the name in the frame rendering.\n" +
|
||||
"@property {boolean} outline - Whether to include the outline in the frame rendering.\n" +
|
||||
"@property {boolean} clip - Whether to clip the frame rendering.\n",
|
||||
after: "({\n" +
|
||||
" withBackground: true,\n" +
|
||||
" theme: 'light',\n" +
|
||||
" frameRendering: { enabled: true, name: true, outline: true, clip: true },\n" +
|
||||
" padding: 10,\n" +
|
||||
" selectedOnly: false,\n" +
|
||||
" skipInliningFonts: false,\n" +
|
||||
" embedScene: false,\n" +
|
||||
"});",
|
||||
},
|
||||
{
|
||||
field: "getPagePDFDimensions",
|
||||
code: "getPagePDFDimensions(pageSize: PageSize, orientation: PageOrientation): PageDimensions",
|
||||
desc: "Returns the dimensions of a standard page size in points (pt).\n" +
|
||||
desc: "Returns the dimensions of a standard page size in pixels.\n" +
|
||||
"\n" +
|
||||
"@param {PageSize} pageSize - The standard page size. Possible values are \"A0\", \"A1\", \"A2\", \"A3\", \"A4\", \"A5\", \"Letter\", \"Legal\", \"Tabloid\".\n" +
|
||||
"@param {PageOrientation} orientation - The orientation of the page. Possible values are \"portrait\" and \"landscape\".\n" +
|
||||
"@returns {PageDimensions} - An object containing the width and height of the page in points (pt).\n" +
|
||||
"@returns {PageDimensions} - An object containing the width and height of the page in pixels.\n" +
|
||||
"\n" +
|
||||
"@typedef {Object} PageDimensions\n" +
|
||||
"@property {number} width - The width of the page in points (pt).\n" +
|
||||
"@property {number} height - The height of the page in points (pt).\n" +
|
||||
"@property {number} width - The width of the page in pixels.\n" +
|
||||
"@property {number} height - The height of the page in pixels.\n" +
|
||||
"\n" +
|
||||
"@typedef {\"A0\" | \"A1\" | \"A2\" | \"A3\" | \"A4\" | \"A5\" | \"Letter\" | \"Legal\" | \"Tabloid\"} PageSize\n" +
|
||||
"\n" +
|
||||
"@typedef {\"portrait\" | \"landscape\"} PageOrientation\n" +
|
||||
"\n" +
|
||||
"@example\n" +
|
||||
"const dimensions = getPDFPageDimensions(\"A4\", \"portrait\");\n" +
|
||||
"console.log(dimensions); // { width: 595.28, height: 841.89 }",
|
||||
after: "",
|
||||
"@typedef {\"portrait\" | \"landscape\"} PageOrientation",
|
||||
after: "(\"A4\", \"portrait\");",
|
||||
},
|
||||
{
|
||||
field: "createPNG",
|
||||
@@ -550,12 +581,6 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
desc: "Adds elements from elementsDict to the current view\nrepositionToCursor: default is false\nsave: default is true\nnewElementsOnTop: default is false, i.e. the new elements get to the bottom of the stack\nnewElementsOnTop controls whether elements created with ExcalidrawAutomate are added at the bottom of the stack or the top of the stack of elements already in the view\nNote that elements copied to the view with copyViewElementsToEAforEditing retain their position in the stack of elements in the view even if modified using EA",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "onDropHook",
|
||||
code: 'onDropHook(data: {ea: ExcalidrawAutomate, event: React.DragEvent<HTMLDivElement>, draggable: any, type: "file" | "text" | "unknown", payload: {files: TFile[], text: string,}, excalidrawFile: TFile, view: ExcalidrawView, pointerPosition: { x: number, y: number},}): boolean;',
|
||||
desc: "If set Excalidraw will call this function onDrop events.\nA return of true will stop the default onDrop processing in Excalidraw.\n\ndraggable is the Obsidian draggable object\nfiles is the array of dropped files\nexcalidrawFile is the file receiving the drop event\nview is the excalidraw view receiving the drop.\npointerPosition is the pointer position on canvas at the time of drop.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "mostRecentMarkdownSVG",
|
||||
code: "mostRecentMarkdownSVG: SVGSVGElement;",
|
||||
@@ -877,11 +902,17 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
desc: "Sets Excalidraw in the targetView to view-mode",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "splitFolderAndFilename",
|
||||
code: "splitFolderAndFilename(filepath: string): { folderpath: string; filename: string; basename: string; extension: string; }",
|
||||
desc: "Splits a file path into its components.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "viewUpdateScene",
|
||||
code: "viewUpdateScene(scene:{elements?:ExcalidrawElement[],appState?: AppState,files?: BinaryFileData,commitToHistory?: boolean,storeAction?: 'capture' | 'none' | 'update'},restore:boolean=false):void",
|
||||
code: "viewUpdateScene(scene:{elements?:ExcalidrawElement[],appState?: AppState,files?: BinaryFileData,captureUpdate?: 'IMMEDIATELY' | 'NEVER' | 'EVENTUALLY'},restore:boolean=false):void",
|
||||
desc: "Calls the ExcalidrawAPI updateScene function for the targetView. When restore=true, excalidraw will try to correct errors in the scene such as setting default values to missing element properties. " +
|
||||
`Note that commitToHistory has been deprecated in Excalidraw and is no longer used. You should use storeAction instead. See ${hyperlink("https://github.com/excalidraw/excalidraw/pull/7898", "ExcalidrawAPI")} documentation for more information.`,
|
||||
`Use captureUpdate to control undo/redo behavior: 'IMMEDIATELY' for immediate undoable updates (most local changes), 'NEVER' for updates that should never be undoable, or 'EVENTUALLY' for updates that should be undoable as part of an async multi-step process. See the ExcalidrawAPI documentation for more information.`,
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
@@ -907,15 +938,16 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
export const EXCALIDRAW_SCRIPTENGINE_INFO: SuggesterInfo[] = [
|
||||
{
|
||||
field: "inputPrompt",
|
||||
code: "inputPrompt: (header: string, placeholder?: string, value?: string, buttons?: {caption:string, tooltip?:string, action:Function}[], lines?: number, displayEditorButtons?: boolean, customComponents?: (container: HTMLElement) => void, blockPointerInputOutsideModal?: boolean);",
|
||||
code: "inputPrompt: (opts: {header: string, placeholder?: string, value?: string, buttons?: {caption:string, tooltip?:string, action:Function}[], lines?: number, displayEditorButtons?: boolean, customComponents?: (container: HTMLElement) => void, blockPointerInputOutsideModal?: boolean, controlsOnTop?: boolean});",
|
||||
desc:
|
||||
"Opens a prompt that asks for an input.\nReturns a string with the input.\nYou need to await the result of inputPrompt.\n" +
|
||||
"Editor buttons are text editing buttons like delete, enter, allcaps - these are only displayed if lines is greater than 1 \n" +
|
||||
"Custom components are components that you can add to the prompt. These will be displayed between the text input area and the buttons.\n" +
|
||||
"blockPointerInputOutsideModal will block pointer input outside the modal. This is useful if you want to prevent the user accidently closing the modal or interacting with the excalidraw canvas while the prompt is open.\n" +
|
||||
"controlsOnTop when set to true will move all the buttons to the top of the modal, leaving the text area at the bottom. This feature was developed for Scribble Helper script to avoid your palm pressing buttons while scribbling.\n"+
|
||||
"buttons.action(input: string) => string\nThe button action function will receive the actual input string. If action returns null, input will be unchanged. If action returns a string, input will receive that value when the promise is resolved. " +
|
||||
"example:\n<code>let fileType = '';\nconst filename = await utils.inputPrompt (\n 'Filename',\n '',\n '',\n, [\n {\n caption: 'Markdown',\n action: ()=>{fileType='md';return;}\n },\n {\n caption: 'Excalidraw',\n action: ()=>{fileType='ex';return;}\n }\n ]\n);</code>",
|
||||
after: "",
|
||||
after: `({\n header: "",\n placeholder: undefined, //string\n value: undefined, //string\n buttons: [{ //optional, may leave undefined\n caption: "", //string\n tooltip: undefined, //string\n action: (input)=>{} //Function\n }],\n lines: undefined, //number\n displayEditorButtons: undefined, //boolean\n customComponents: undefined, //(container: HTMLElement) => void\n blockPointerInputOutsideModal: undefined, //boolean\n controlsOnTop: undefined, //boolean\n draggable: undefined, //boolean\n});`,
|
||||
},
|
||||
{
|
||||
field: "suggester",
|
||||
@@ -1035,6 +1067,13 @@ export const FRONTMATTER_KEYS_INFO: SuggesterInfo[] = [
|
||||
desc: "If this key is present the file will be opened as a markdown file in the editor",
|
||||
after: ": true",
|
||||
},
|
||||
{
|
||||
field: "embed-md",
|
||||
code: null,
|
||||
desc: "If this key is present, when embedding the ![[image]] into a markdown document, it will be embedded as markdown, not as an image.\n" +
|
||||
"If however you embed ![[image#^as-image]], i.e. you reference the 'as-image' block, then the image will be embedded as an image.",
|
||||
after: ": true",
|
||||
},
|
||||
{
|
||||
field: "autoexport",
|
||||
code: null,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//https://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api
|
||||
//https://img.youtube.com/vi/uZz5MgzWXiM/maxresdefault.jpg
|
||||
|
||||
import { ExcalidrawElement, FileId } from "@zsviczian/excalidraw/types/excalidraw/element/types";
|
||||
import { ExcalidrawElement, FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { BinaryFileData, DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { App, MarkdownRenderer, Notice, TFile } from "obsidian";
|
||||
import {
|
||||
@@ -704,7 +704,7 @@ export class EmbeddedFilesLoader {
|
||||
}
|
||||
if (!excalidrawData.getEquation(id).isLoaded) {
|
||||
const latex = equation.latex;
|
||||
const data = await tex2dataURL(latex, 4, this.plugin.app);
|
||||
const data = await tex2dataURL(latex, 4, this.plugin);
|
||||
if (data) {
|
||||
const fileData = {
|
||||
mimeType: data.mimeType,
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
RoundnessType,
|
||||
ExcalidrawFrameElement,
|
||||
ExcalidrawTextContainer,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/element/types";
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ColorMap, MimeType } from "./EmbeddedFileLoader";
|
||||
import { Editor, Notice, OpenViewState, RequestUrlResponse, TFile, TFolder, WorkspaceLeaf } from "obsidian";
|
||||
import * as obsidian_module from "obsidian";
|
||||
@@ -25,7 +25,6 @@ import {
|
||||
COLOR_NAMES,
|
||||
fileid,
|
||||
GITHUB_RELEASES,
|
||||
determineFocusDistance,
|
||||
getCommonBoundingBox,
|
||||
getLineHeight,
|
||||
getMaximumGroups,
|
||||
@@ -34,7 +33,7 @@ import {
|
||||
mermaidToExcalidraw,
|
||||
refreshTextDimensions,
|
||||
} from "src/constants/constants";
|
||||
import { blobToBase64, checkAndCreateFolder, getDrawingFilename, getExcalidrawEmbeddedFilesFiletree, getListOfTemplateFiles, getNewUniqueFilepath } from "src/utils/fileUtils";
|
||||
import { blobToBase64, checkAndCreateFolder, getDrawingFilename, getExcalidrawEmbeddedFilesFiletree, getListOfTemplateFiles, getNewUniqueFilepath, splitFolderAndFilename } from "src/utils/fileUtils";
|
||||
import {
|
||||
//debug,
|
||||
getImageSize,
|
||||
@@ -42,9 +41,10 @@ import {
|
||||
wrapTextAtCharLength,
|
||||
arrayToMap,
|
||||
addAppendUpdateCustomData,
|
||||
getSVG,
|
||||
} from "src/utils/utils";
|
||||
import { getAttachmentsFolderAndFilePath, getExcalidrawViews, getLeaf, getNewOrAdjacentLeaf, isObsidianThemeDark, mergeMarkdownFiles, openLeaf } from "src/utils/obsidianUtils";
|
||||
import { AppState, BinaryFileData, DataURL, ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { AppState, BinaryFileData, DataURL, ExcalidrawImperativeAPI, SceneData } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { EmbeddedFile, EmbeddedFilesLoader } from "./EmbeddedFileLoader";
|
||||
import { tex2dataURL } from "./LaTeX";
|
||||
import { NewFileActions } from "src/shared/Dialogs/Prompt";
|
||||
@@ -68,7 +68,7 @@ import {ConversionResult, svgToExcalidraw} from "src/shared/svgToExcalidraw/pars
|
||||
import { ROUNDNESS } from "src/constants/constants";
|
||||
import { ClipboardData } from "@zsviczian/excalidraw/types/excalidraw/clipboard";
|
||||
import { emulateKeysForLinkClick, PaneTarget } from "src/utils/modifierkeyHelper";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import PolyBool from "polybooljs";
|
||||
import { EmbeddableMDCustomProps } from "./Dialogs/EmbeddableSettings";
|
||||
import {
|
||||
@@ -80,10 +80,14 @@ import { EXCALIDRAW_AUTOMATE_INFO, EXCALIDRAW_SCRIPTENGINE_INFO } from "./Dialog
|
||||
import { addBackOfTheNoteCard } from "../utils/excalidrawViewUtils";
|
||||
import { log } from "../utils/debugHelper";
|
||||
import { ExcalidrawLib } from "../types/excalidrawLib";
|
||||
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/types";
|
||||
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/src/types";
|
||||
import { AddImageOptions, ImageInfo, SVGColorInfo } from "src/types/excalidrawAutomateTypes";
|
||||
import { _measureText, cloneElement, createPNG, createSVG, errorMessage, filterColorMap, getEmbeddedFileForImageElment, getFontFamily, getLineBox, getTemplate, isColorStringTransparent, isSVGColorInfo, mergeColorMapIntoSVGColorInfo, normalizeLinePoints, repositionElementsToCursor, svgColorInfoToColorMap, updateOrAddSVGColorInfo, verifyMinimumPluginVersion } from "src/utils/excalidrawAutomateUtils";
|
||||
import { exportToPDF, getMarginValue, getPageDimensions, PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFPageProperties } from "src/utils/exportUtils";
|
||||
import { FrameRenderingOptions } from "src/types/utilTypes";
|
||||
import { CaptureUpdateAction } from "src/constants/constants";
|
||||
import { AutoexportConfig } from "src/types/excalidrawViewTypes";
|
||||
import { FloatingModal } from "./Dialogs/FloatingModal";
|
||||
|
||||
extendPlugins([
|
||||
HarmonyPlugin,
|
||||
@@ -166,6 +170,15 @@ export class ExcalidrawAutomate {
|
||||
return obsidian_module;
|
||||
};
|
||||
|
||||
/**
|
||||
* This is a modified version of the Obsidian.Modal class
|
||||
* that allows the modal to be dragged around the screen
|
||||
* and that does not dim the background.
|
||||
*/
|
||||
get FloatingModal() {
|
||||
return FloatingModal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the laser pointer settings from the plugin.
|
||||
* @returns {Object} The laser pointer settings.
|
||||
@@ -314,6 +327,19 @@ export class ExcalidrawAutomate {
|
||||
return await checkAndCreateFolder(folderpath);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param filepath - The file path to split into folder and filename.
|
||||
* @returns object containing folderpath, filename, basename, and extension.
|
||||
*/
|
||||
public splitFolderAndFilename(filepath: string) : {
|
||||
folderpath: string;
|
||||
filename: string;
|
||||
basename: string;
|
||||
extension: string;
|
||||
} {
|
||||
return splitFolderAndFilename(filepath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a unique filepath by appending a number if file already exists.
|
||||
* @param {string} filename - Base filename.
|
||||
@@ -885,7 +911,7 @@ export class ExcalidrawAutomate {
|
||||
Object.keys(this.imagesDict).forEach((key: FileId)=> {
|
||||
const item = this.imagesDict[key];
|
||||
if(item.latex) {
|
||||
outString += `${key}: $$${item.latex}$$\n\n`;
|
||||
outString += `${key}: $$${item.latex.trim()}$$\n\n`;
|
||||
} else {
|
||||
if(item.file) {
|
||||
if(item.file instanceof TFile) {
|
||||
@@ -932,19 +958,19 @@ export class ExcalidrawAutomate {
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the dimensions of a standard page size in points (pt).
|
||||
* Returns the dimensions of a standard page size in pixels.
|
||||
*
|
||||
* @param {PageSize} pageSize - The standard page size. Possible values are "A0", "A1", "A2", "A3", "A4", "A5", "Letter", "Legal", "Tabloid".
|
||||
* @param {PageOrientation} orientation - The orientation of the page. Possible values are "portrait" and "landscape".
|
||||
* @returns {PageDimensions} - An object containing the width and height of the page in points (pt).
|
||||
* @returns {PageDimensions} - An object containing the width and height of the page in pixels.
|
||||
*
|
||||
* @typedef {Object} PageDimensions
|
||||
* @property {number} width - The width of the page in points (pt).
|
||||
* @property {number} height - The height of the page in points (pt).
|
||||
* @property {number} width - The width of the page in pixels.
|
||||
* @property {number} height - The height of the page in pixels.
|
||||
*
|
||||
* @example
|
||||
* const dimensions = getPageDimensions("A4", "portrait");
|
||||
* console.log(dimensions); // { width: 595.28, height: 841.89 }
|
||||
* console.log(dimensions); // { width: 794.56, height: 1122.56 }
|
||||
*/
|
||||
getPagePDFDimensions(pageSize: PageSize, orientation: PageOrientation): PageDimensions {
|
||||
return getPageDimensions(pageSize, orientation);
|
||||
@@ -955,31 +981,34 @@ export class ExcalidrawAutomate {
|
||||
*
|
||||
* @param {Object} params - The parameters for creating the PDF.
|
||||
* @param {SVGSVGElement[]} params.SVG - An array of SVG elements to be included in the PDF.
|
||||
* @param {PDFExportScale} [params.scale={ fitToPage: true, zoom: 1 }] - The scaling options for the SVG elements.
|
||||
* @param {PDFExportScale} [params.scale={ fitToPage: 1, zoom: 1 }] - The scaling options for the SVG elements.
|
||||
* @param {PDFPageProperties} [params.pageProps] - The properties for the PDF pages.
|
||||
* @returns {Promise<ArrayBuffer>} - A promise that resolves to an ArrayBuffer containing the PDF data.
|
||||
*
|
||||
* @example
|
||||
* const pdfData = await createToPDF({
|
||||
* SVG: [svgElement1, svgElement2],
|
||||
* scale: { fitToPage: true },
|
||||
* scale: { fitToPage: 1 },
|
||||
* pageProps: {
|
||||
* dimensions: { width: 595.28, height: 841.89 },
|
||||
* dimensions: { width: 794.56, height: 1122.56 },
|
||||
* backgroundColor: "#ffffff",
|
||||
* margin: { left: 20, right: 20, top: 20, bottom: 20 },
|
||||
* alignment: "center"
|
||||
* alignment: "center",
|
||||
* }
|
||||
* filename: "example.pdf",
|
||||
* });
|
||||
*/
|
||||
async createPDF({
|
||||
SVG,
|
||||
scale = { fitToPage: true, zoom: 1 },
|
||||
scale = { fitToPage: 1, zoom: 1 },
|
||||
pageProps,
|
||||
filename,
|
||||
}: {
|
||||
SVG: SVGSVGElement[];
|
||||
scale?: PDFExportScale;
|
||||
pageProps?: PDFPageProperties;
|
||||
}): Promise<ArrayBuffer> {
|
||||
filename: string;
|
||||
}): Promise<void> {
|
||||
if(!pageProps) {
|
||||
pageProps = {
|
||||
alignment: this.plugin.settings.pdfSettings.alignment,
|
||||
@@ -997,7 +1026,69 @@ export class ExcalidrawAutomate {
|
||||
pageProps.backgroundColor = "#ffffff";
|
||||
}
|
||||
|
||||
return await exportToPDF({SVG, scale, pageProps});
|
||||
await exportToPDF({SVG, scale, pageProps, filename});
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an SVG representation of the current view.
|
||||
*
|
||||
* @param {Object} options - The options for creating the SVG.
|
||||
* @param {boolean} [options.withBackground=true] - Whether to include the background in the SVG.
|
||||
* @param {"light" | "dark"} [options.theme] - The theme to use for the SVG.
|
||||
* @param {FrameRenderingOptions} [options.frameRendering={enabled: true, name: true, outline: true, clip: true}] - The frame rendering options.
|
||||
* @param {number} [options.padding] - The padding to apply around the SVG.
|
||||
* @param {boolean} [options.selectedOnly=false] - Whether to include only the selected elements in the SVG.
|
||||
* @param {boolean} [options.skipInliningFonts=false] - Whether to skip inlining fonts in the SVG.
|
||||
* @param {boolean} [options.embedScene=false] - Whether to embed the scene in the SVG.
|
||||
* @returns {Promise<SVGSVGElement>} A promise that resolves to the SVG element.
|
||||
*/
|
||||
async createViewSVG({
|
||||
withBackground = true,
|
||||
theme,
|
||||
frameRendering = {enabled: true, name: true, outline: true, clip: true},
|
||||
padding,
|
||||
selectedOnly = false,
|
||||
skipInliningFonts = false,
|
||||
embedScene = false,
|
||||
} : {
|
||||
withBackground?: boolean,
|
||||
theme?: "light" | "dark",
|
||||
frameRendering?: FrameRenderingOptions,
|
||||
padding?: number,
|
||||
selectedOnly?: boolean,
|
||||
skipInliningFonts?: boolean,
|
||||
embedScene?: boolean,
|
||||
}): Promise<SVGSVGElement> {
|
||||
if(!this.targetView || !this.targetView.file || !this.targetView._loaded) {
|
||||
console.log("No view loaded");
|
||||
return;
|
||||
}
|
||||
const view = this.targetView;
|
||||
const scene = this.targetView.getScene(selectedOnly);
|
||||
|
||||
const exportSettings: ExportSettings = {
|
||||
withBackground: view.getViewExportWithBackground(withBackground),
|
||||
withTheme: true,
|
||||
isMask: isMaskFile(this.plugin, view.file),
|
||||
skipInliningFonts,
|
||||
frameRendering,
|
||||
};
|
||||
|
||||
return await getSVG(
|
||||
{
|
||||
...scene,
|
||||
...{
|
||||
appState: {
|
||||
...scene.appState,
|
||||
theme: view.getViewExportTheme(theme),
|
||||
exportEmbedScene: view.getViewExportEmbedScene(embedScene),
|
||||
},
|
||||
},
|
||||
},
|
||||
exportSettings,
|
||||
view.getViewExportPadding(padding),
|
||||
view.file,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1027,13 +1118,14 @@ export class ExcalidrawAutomate {
|
||||
? "light"
|
||||
: undefined;
|
||||
}
|
||||
if (theme && !exportSettings) {
|
||||
if (!exportSettings) {
|
||||
exportSettings = {
|
||||
withBackground: this.plugin.settings.exportWithBackground,
|
||||
withTheme: true,
|
||||
isMask: false,
|
||||
skipInliningFonts: !embedFont,
|
||||
};
|
||||
}
|
||||
}
|
||||
if (!loader) {
|
||||
loader = new EmbeddedFilesLoader(
|
||||
this.plugin,
|
||||
@@ -1585,7 +1677,8 @@ export class ExcalidrawAutomate {
|
||||
arrayToMap(this.getElements()),
|
||||
originalText,
|
||||
);
|
||||
if(dimensions) {
|
||||
|
||||
if(dimensions && !formatting?.width) {
|
||||
textElement.width = dimensions.width;
|
||||
textElement.height = dimensions.height;
|
||||
textElement.x = dimensions.x;
|
||||
@@ -1645,29 +1738,18 @@ export class ExcalidrawAutomate {
|
||||
id = id ?? nanoid();
|
||||
const startPoint = points[0] as GlobalPoint;
|
||||
const endPoint = points[points.length - 1] as GlobalPoint;
|
||||
const elementsMap = arrayToMap(this.getElements());
|
||||
this.elementsDict[id] = {
|
||||
points: normalizeLinePoints(points),
|
||||
lastCommittedPoint: null,
|
||||
startBinding: {
|
||||
elementId: formatting?.startObjectId,
|
||||
focus: formatting?.startObjectId
|
||||
? determineFocusDistance(
|
||||
this.getElement(formatting?.startObjectId) as ExcalidrawBindableElement,
|
||||
endPoint,
|
||||
startPoint,
|
||||
)
|
||||
: 0.1,
|
||||
focus: 0.1,
|
||||
gap: GAP,
|
||||
},
|
||||
endBinding: {
|
||||
elementId: formatting?.endObjectId,
|
||||
focus: formatting?.endObjectId
|
||||
? determineFocusDistance(
|
||||
this.getElement(formatting?.endObjectId) as ExcalidrawBindableElement,
|
||||
startPoint,
|
||||
endPoint,
|
||||
)
|
||||
: 0.1,
|
||||
focus: 0.1,
|
||||
gap: GAP,
|
||||
},
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/388
|
||||
@@ -1846,7 +1928,7 @@ export class ExcalidrawAutomate {
|
||||
*/
|
||||
async addLaTex(topX: number, topY: number, tex: string): Promise<string> {
|
||||
const id = nanoid();
|
||||
const image = await tex2dataURL(tex, 4, this.plugin.app);
|
||||
const image = await tex2dataURL(tex, 4, this.plugin);
|
||||
if (!image) {
|
||||
return null;
|
||||
}
|
||||
@@ -1888,7 +1970,7 @@ export class ExcalidrawAutomate {
|
||||
created: number;
|
||||
size: { height: number; width: number };
|
||||
}> {
|
||||
return await tex2dataURL(tex,scale, this.plugin.app);
|
||||
return await tex2dataURL(tex,scale, this.plugin);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -2094,7 +2176,7 @@ export class ExcalidrawAutomate {
|
||||
};
|
||||
targetView: ExcalidrawView = null; //the view currently edited
|
||||
/**
|
||||
* Sets the target view for EA. All the view operations and the access to Excalidraw API will be performend on this view.
|
||||
* Sets the target view for EA. All the view operations and the access to Excalidraw API will be performed on this view.
|
||||
* If view is null or undefined, the function will first try setView("active"), then setView("first").
|
||||
* @param {ExcalidrawView | "first" | "active"} [view] - The view to set as target.
|
||||
* @returns {ExcalidrawView} The target view.
|
||||
@@ -2169,7 +2251,7 @@ export class ExcalidrawAutomate {
|
||||
this.targetView.updateScene({
|
||||
elements: el.filter((e: ExcalidrawElement) => !ids.includes(e.id)),
|
||||
appState: st,
|
||||
storeAction: "capture",
|
||||
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
|
||||
});
|
||||
//this.targetView.save();
|
||||
return true;
|
||||
@@ -2496,7 +2578,7 @@ export class ExcalidrawAutomate {
|
||||
appState: {
|
||||
viewModeEnabled: !isFullscreen,
|
||||
},
|
||||
storeAction: "update",
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
});
|
||||
this.targetView.toolsPanelRef?.current?.setExcalidrawViewMode(!isFullscreen);
|
||||
}
|
||||
@@ -2518,7 +2600,7 @@ export class ExcalidrawAutomate {
|
||||
return;
|
||||
}
|
||||
const view = this.targetView as ExcalidrawView;
|
||||
view.updateScene({appState:{viewModeEnabled: enabled}, storeAction: "update"});
|
||||
view.updateScene({appState:{viewModeEnabled: enabled}, captureUpdate: CaptureUpdateAction.NEVER});
|
||||
view.toolsPanelRef?.current?.setExcalidrawViewMode(enabled);
|
||||
}
|
||||
|
||||
@@ -2528,17 +2610,19 @@ export class ExcalidrawAutomate {
|
||||
* @param {ExcalidrawElement[]} [scene.elements] - Array of elements in the scene.
|
||||
* @param {AppState} [scene.appState] - The app state of the scene.
|
||||
* @param {BinaryFileData} [scene.files] - The files in the scene.
|
||||
* @param {boolean} [scene.commitToHistory] - Whether to commit the scene to history.
|
||||
* @param {"capture" | "none" | "update"} [scene.storeAction] - The store action for the scene.
|
||||
* @param {boolean} [scene.commitToHistory] - Whether to commit the scene to history. @deprecated Use scene.storageOption instead
|
||||
* @param {"capture" | "none" | "update"} [scene.storeAction] - The store action for the scene. @deprecated Use scene.storageOption instead
|
||||
* @param {"IMMEDIATELY" | "NEVER" | "EVENTUALLY"} [scene.captureUpdate] - The capture update action for the scene.
|
||||
* @param {boolean} [restore=false] - Whether to restore legacy elements in the scene.
|
||||
*/
|
||||
viewUpdateScene (
|
||||
scene: {
|
||||
elements?: ExcalidrawElement[],
|
||||
appState?: AppState,
|
||||
appState?: AppState | {},
|
||||
files?: BinaryFileData,
|
||||
commitToHistory?: boolean,
|
||||
storeAction?: "capture" | "none" | "update",
|
||||
captureUpdate?: SceneData["captureUpdate"],
|
||||
},
|
||||
restore: boolean = false,
|
||||
):void {
|
||||
@@ -2555,6 +2639,7 @@ export class ExcalidrawAutomate {
|
||||
appState: scene.appState,
|
||||
files: scene.files,
|
||||
storeAction: scene.storeAction,
|
||||
captureUpdate: scene.captureUpdate,
|
||||
},restore);
|
||||
}
|
||||
|
||||
@@ -2740,6 +2825,119 @@ export class ExcalidrawAutomate {
|
||||
pointerPosition: { x: number; y: number }; //the pointer position on canvas
|
||||
}) => boolean = null;
|
||||
|
||||
/**
|
||||
* If set, this callback is triggered when a image is being saved in Excalidraw.
|
||||
* You can use this callback to customize the naming and path of pasted images to avoid
|
||||
* default names like "Pasted image 123147170.png" being saved in the attachments folder,
|
||||
* and instead use more meaningful names based on the Excalidraw file or other criteria,
|
||||
* plus save the image in a different folder.
|
||||
*
|
||||
* If the function returns null or undefined, the normal Excalidraw operation will continue
|
||||
* with the excalidraw generated name and default path.
|
||||
* If a filepath is returned, that will be used. Include the full Vault filepath and filename
|
||||
* with the file extension.
|
||||
* The currentImageName is the name of the image generated by excalidraw or provided during paste.
|
||||
*
|
||||
* @param data - An object containing the following properties:
|
||||
* @property {string} [currentImageName] - Default name for the image.
|
||||
* @property {string} drawingFilePath - The file path of the Excalidraw file where the image is being used.
|
||||
*
|
||||
* @returns {string} - The new filepath for the image including full vault path and extension.
|
||||
*
|
||||
* Example usage:
|
||||
* ```
|
||||
* onImageFilePathHook: (data) => {
|
||||
* const { currentImageName, drawingFilePath } = data;
|
||||
* // Generate a new filepath based on the drawing file name and other criteria
|
||||
* const ext = currentImageName.split('.').pop();
|
||||
* return `${drawingFileName} - ${currentImageName || 'image'}.${ext}`;
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
onImageFilePathHook: (data: {
|
||||
currentImageName: string; // Excalidraw generated name of the image, or the name received from the file system.
|
||||
drawingFilePath: string; // The full filepath of the Excalidraw file where the image is being used.
|
||||
}) => string | null = null;
|
||||
|
||||
/**
|
||||
* If set, this callback is triggered when the Excalidraw image is being exported to
|
||||
* .svg, .png, or .excalidraw.
|
||||
* You can use this callback to customize the naming and path of the images. This allows
|
||||
* you to place images into an assets folder.
|
||||
*
|
||||
* If the function returns null or undefined, the normal Excalidraw operation will continue
|
||||
* with the currentImageName and in the same folder as the Excalidraw file
|
||||
* If a filepath is returned, that will be used. Include the full Vault filepath and filename
|
||||
* with the file extension.
|
||||
* If the new folder path does not exist, excalidraw will create it - you don't need to worry about that.
|
||||
* ⚠️⚠️If an image already exists on the path, that will be overwritten. When returning
|
||||
* your own image path, you must take care of unique filenames (if that is a requirement) ⚠️⚠️
|
||||
* The current image name is the name generated by Excalidraw:
|
||||
* - my-drawing.png
|
||||
* - my-drawing.svg
|
||||
* - my-drawing.excalidraw
|
||||
* - my-drawing.dark.svg
|
||||
* - my-drawing.light.svg
|
||||
* - my-drawing.dark.png
|
||||
* - my-drawing.light.png
|
||||
*
|
||||
* @param data - An object containing the following properties:
|
||||
* @property {string} exportFilepath - Default export filepath for the image.
|
||||
* @property {string} exportExtension - The file extension of the export (e.g., .dark.svg, .png, .excalidraw).
|
||||
* @property {string} excalidrawFile - TFile: The Excalidraw file being exported.
|
||||
* @property {string} oldExcalidrawPath - If action === "move" The old path of the Excalidraw file, else undefined
|
||||
* @property {string} action - The action being performed: "export", "move", or "delete". move and delete reference the change to the Excalidraw file.
|
||||
*
|
||||
* @returns {string} - The new filepath for the image including full vault path and extension.
|
||||
*
|
||||
* Example usage:
|
||||
* ```
|
||||
* onImageFilePathHook: (data) => {
|
||||
* const { currentImageName, drawingFilePath, frontmatter } = data;
|
||||
* // Generate a new filepath based on the drawing file name and other criteria
|
||||
* const ext = currentImageName.split('.').pop();
|
||||
* if(frontmatter && frontmatter["my-custom-field"]) {
|
||||
* }
|
||||
* return `${drawingFileName} - ${currentImageName || 'image'}.${ext}`;
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
onImageExportPathHook: (data: {
|
||||
exportFilepath: string; // Default export filepath for the image.
|
||||
exportExtension: string; // The file extension of the export (e.g., .dark.svg, .png, .excalidraw).
|
||||
excalidrawFile: TFile; // The Excalidraw file being exported.
|
||||
oldExcalidrawPath? : string; // The old path of the Excalidraw file, if it was moved/renamed.
|
||||
action: "export" | "move" | "delete";
|
||||
}) => string | null = null;
|
||||
|
||||
/**
|
||||
* Excalidraw supports auto-export of Excalidraw files to .png, .svg, and .excalidraw formats.
|
||||
*
|
||||
* Auto-export of Excalidraw files can be controlled at multiple levels.
|
||||
* 1) In plugin settings where you can set up default auto-export applicable to all your Excalidraw files.
|
||||
* 2) However, if you do not want to auto-export every file, you can also control auto-export
|
||||
* at the file level using the 'excalidraw-autoexport' frontmatter property.
|
||||
* 3) This hook gives you an additional layer of control over the auto-export process.
|
||||
*
|
||||
* This hook is triggered when an Excalidraw file is being saved.
|
||||
*
|
||||
* interface AutoexportConfig {
|
||||
* png: boolean; // Whether to auto-export to PNG
|
||||
* svg: boolean; // Whether to auto-export to SVG
|
||||
* excalidraw: boolean; // Whether to auto-export to Excalidraw format
|
||||
* theme: "light" | "dark" | "both"; // The theme to use for the export
|
||||
* }
|
||||
*
|
||||
* @param {Object} data - The data for the hook.
|
||||
* @param {AutoexportConfig} data.autoexportConfig - The current autoexport configuration.
|
||||
* @param {TFile} data.excalidrawFile - The Excalidraw file being auto-exported.
|
||||
* @returns {AutoexportConfig | null} - Return a modified AutoexportConfig to override the export behavior, or null to use the default.
|
||||
*/
|
||||
onTriggerAutoexportHook: (data: {
|
||||
autoexportConfig: AutoexportConfig;
|
||||
excalidrawFile: TFile; // The Excalidraw file being auto-exported
|
||||
}) => AutoexportConfig | null = null;
|
||||
|
||||
/**
|
||||
* if set, this callback is triggered, when an Excalidraw file is opened
|
||||
* You can use this callback in case you want to do something additional when the file is opened.
|
||||
@@ -3206,7 +3404,7 @@ export class ExcalidrawAutomate {
|
||||
elements.splice(newZIndex, 0, elements.splice(oldZIndex, 1)[0]);
|
||||
this.targetView.updateScene({
|
||||
elements,
|
||||
storeAction: "capture",
|
||||
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
loadSceneFonts,
|
||||
} from "../constants/constants";
|
||||
import ExcalidrawPlugin from "../core/main";
|
||||
import { TextMode } from "../view/ExcalidrawView";
|
||||
import ExcalidrawView, { TextMode } from "../view/ExcalidrawView";
|
||||
import {
|
||||
addAppendUpdateCustomData,
|
||||
compress,
|
||||
@@ -44,15 +44,15 @@ import {
|
||||
ExcalidrawImageElement,
|
||||
ExcalidrawTextElement,
|
||||
FileId,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/element/types";
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { BinaryFiles, DataURL, SceneData } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { EmbeddedFile, MimeType } from "./EmbeddedFileLoader";
|
||||
import { ConfirmationPrompt } from "./Dialogs/Prompt";
|
||||
import { MultiOptionConfirmationPrompt } from "./Dialogs/Prompt";
|
||||
import { getMermaidImageElements, getMermaidText, shouldRenderMermaid } from "../utils/mermaidUtils";
|
||||
import { DEBUGGING, debug } from "../utils/debugHelper";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { updateElementIdsInScene } from "../utils/excalidrawSceneUtils";
|
||||
import { getNewUniqueFilepath } from "../utils/fileUtils";
|
||||
import { importFileToVault } from "../utils/fileUtils";
|
||||
import { t } from "../lang/helpers";
|
||||
import { displayFontMessage } from "../utils/excalidrawViewUtils";
|
||||
import { getPDFRect } from "../utils/PDFUtils";
|
||||
@@ -480,7 +480,7 @@ export class ExcalidrawData {
|
||||
selectedElementIds: {[key:string]:boolean} = {}; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/609
|
||||
|
||||
constructor(
|
||||
private plugin: ExcalidrawPlugin,
|
||||
private plugin: ExcalidrawPlugin, private view?: ExcalidrawView,
|
||||
) {
|
||||
this.app = this.plugin.app;
|
||||
this.files = new Map<FileId, EmbeddedFile>();
|
||||
@@ -792,7 +792,7 @@ export class ExcalidrawData {
|
||||
|
||||
//once off migration of legacy scenes
|
||||
if(this.scene?.elements?.some((el:any)=>el.type==="iframe" && !el.customData)) {
|
||||
const prompt = new ConfirmationPrompt(
|
||||
const prompt = new MultiOptionConfirmationPrompt(
|
||||
this.plugin,
|
||||
"This file contains embedded frames " +
|
||||
"which will be migrated to a newer version for compatibility with " +
|
||||
@@ -1461,7 +1461,7 @@ export class ExcalidrawData {
|
||||
: "";
|
||||
if (this.equations.size > 0) {
|
||||
for (const key of this.equations.keys()) {
|
||||
outString += `${key}: $$${this.equations.get(key).latex}$$\n\n`;
|
||||
outString += `${key}: $$${this.equations.get(key).latex.trim()}$$\n\n`;
|
||||
}
|
||||
}
|
||||
if (this.files.size > 0) {
|
||||
@@ -1546,26 +1546,15 @@ export class ExcalidrawData {
|
||||
}
|
||||
}
|
||||
|
||||
const x = await getAttachmentsFolderAndFilePath(this.app, this.file.path, fname);
|
||||
const filepath = getNewUniqueFilepath(this.app.vault,fname,x.folder);
|
||||
|
||||
/*
|
||||
const filepath = (
|
||||
await getAttachmentsFolderAndFilePath(this.app, this.file.path, fname)
|
||||
).filepath;*/
|
||||
|
||||
const arrayBuffer = await getBinaryFileFromDataURL(dataURL);
|
||||
if(!arrayBuffer) return null;
|
||||
|
||||
const file = await this.app.vault.createBinary(
|
||||
filepath,
|
||||
arrayBuffer,
|
||||
);
|
||||
const file = await importFileToVault(this.app, fname, arrayBuffer, this.file, this.view);
|
||||
|
||||
const embeddedFile = new EmbeddedFile(
|
||||
this.plugin,
|
||||
this.file.path,
|
||||
filepath,
|
||||
file.path,
|
||||
);
|
||||
|
||||
embeddedFile.setImage({
|
||||
|
||||
@@ -382,6 +382,25 @@ class ImageCache {
|
||||
store.put(data, filepath);
|
||||
}
|
||||
|
||||
public async removeBAKFromCache(filepath: string): Promise<void> {
|
||||
if (!this.isReady()) {
|
||||
return; // Database not initialized yet
|
||||
}
|
||||
|
||||
const transaction = this.db.transaction(this.backupStoreName, "readwrite");
|
||||
const store = transaction.objectStore(this.backupStoreName);
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const request = store.delete(filepath);
|
||||
request.onsuccess = () => {
|
||||
resolve();
|
||||
};
|
||||
request.onerror = () => {
|
||||
reject(new Error(`Failed to remove backup file with key: ${filepath}`));
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
public async clearImageCache(): Promise<void> {
|
||||
if (!this.isReady()) {
|
||||
return; // Database not initialized yet
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import ExcalidrawView from "../view/ExcalidrawView";
|
||||
import { FileData, MimeType } from "./EmbeddedFileLoader";
|
||||
import { FileId } from "@zsviczian/excalidraw/types/excalidraw/element/types";
|
||||
import { App } from "obsidian";
|
||||
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
|
||||
declare const loadMathjaxToSVG: Function;
|
||||
let mathjaxLoaded = false;
|
||||
@@ -52,7 +52,7 @@ export const updateEquation = async (
|
||||
export async function tex2dataURL(
|
||||
tex: string,
|
||||
scale: number = 4,
|
||||
app: App,
|
||||
plugin: ExcalidrawPlugin,
|
||||
): Promise<{
|
||||
mimeType: MimeType;
|
||||
fileId: FileId;
|
||||
@@ -61,7 +61,7 @@ export async function tex2dataURL(
|
||||
size: { height: number; width: number };
|
||||
}> {
|
||||
await loadMathJax();
|
||||
return tex2dataURLExternal(tex, scale, app);
|
||||
return tex2dataURLExternal(tex, scale, plugin);
|
||||
}
|
||||
|
||||
export const clearMathJaxVariables = () => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import {Notice, requestUrl} from "obsidian"
|
||||
import ExcalidrawPlugin from "../../core/main"
|
||||
import ExcalidrawView, { ExportSettings } from "../../view/ExcalidrawView"
|
||||
import FrontmatterEditor from "src/shared/Frontmatter";
|
||||
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/excalidraw/element/types";
|
||||
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { EmbeddedFilesLoader } from "../EmbeddedFileLoader";
|
||||
import { blobToBase64 } from "src/utils/fileUtils";
|
||||
import { getEA } from "src/core";
|
||||
@@ -114,7 +114,7 @@ export default class Taskbone {
|
||||
if(addToFrontmatter) {
|
||||
fe.setKey("taskbone-ocr",text);
|
||||
view.data = fe.data;
|
||||
view.save(false);
|
||||
view.save(false, true, true);
|
||||
}
|
||||
window.navigator.clipboard.writeText(text);
|
||||
new Notice(`I placed the recognized text onto the system clipboard${addToFrontmatter?" and to document properties":""}.`);
|
||||
|
||||
@@ -8,13 +8,14 @@ import {
|
||||
import { PLUGIN_ID } from "../constants/constants";
|
||||
import ExcalidrawView from "../view/ExcalidrawView";
|
||||
import ExcalidrawPlugin from "../core/main";
|
||||
import { ButtonDefinition, GenericInputPrompt, GenericSuggester } from "./Dialogs/Prompt";
|
||||
import { GenericInputPrompt, GenericSuggester } from "./Dialogs/Prompt";
|
||||
import { getIMGFilename } from "../utils/fileUtils";
|
||||
import { splitFolderAndFilename } from "../utils/fileUtils";
|
||||
import { getEA } from "src/core";
|
||||
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
|
||||
import { WeakArray } from "./WeakArray";
|
||||
import { getExcalidrawViews } from "../utils/obsidianUtils";
|
||||
import { ButtonDefinition, InputPromptOptions } from "src/types/promptTypes";
|
||||
|
||||
export type ScriptIconMap = {
|
||||
[key: string]: { name: string; group: string; svgString: string };
|
||||
@@ -190,7 +191,7 @@ export class ScriptEngine {
|
||||
...this.scriptIconMap,
|
||||
};
|
||||
const splitname = splitFolderAndFilename(name)
|
||||
this.scriptIconMap[scriptPath] = { name:splitname.filename, group: splitname.folderpath === "/" ? "" : splitname.folderpath, svgString };
|
||||
this.scriptIconMap[scriptPath] = { name:splitname.filename, group: splitname.folderpath, svgString };
|
||||
this.updateToolPannels();
|
||||
}
|
||||
|
||||
@@ -271,7 +272,7 @@ export class ScriptEngine {
|
||||
//try {
|
||||
result = await new AsyncFunction("ea", "utils", script)(ea, {
|
||||
inputPrompt: (
|
||||
header: string,
|
||||
header: string | InputPromptOptions,
|
||||
placeholder?: string,
|
||||
value?: string,
|
||||
buttons?: ButtonDefinition[],
|
||||
@@ -279,8 +280,23 @@ export class ScriptEngine {
|
||||
displayEditorButtons?: boolean,
|
||||
customComponents?: (container: HTMLElement) => void,
|
||||
blockPointerInputOutsideModal?: boolean,
|
||||
) =>
|
||||
ScriptEngine.inputPrompt(
|
||||
controlsOnTop?: boolean,
|
||||
draggable?: boolean,
|
||||
) => {
|
||||
if (typeof header === "object") {
|
||||
const options = header as InputPromptOptions;
|
||||
header = options.header;
|
||||
placeholder = options.placeholder;
|
||||
value = options.value;
|
||||
buttons = options.buttons;
|
||||
lines = options.lines;
|
||||
displayEditorButtons = options.displayEditorButtons;
|
||||
customComponents = options.customComponents;
|
||||
blockPointerInputOutsideModal = options.blockPointerInputOutsideModal;
|
||||
controlsOnTop = options.controlsOnTop;
|
||||
draggable = options.draggable;
|
||||
}
|
||||
return ScriptEngine.inputPrompt(
|
||||
view,
|
||||
this.plugin,
|
||||
this.app,
|
||||
@@ -292,7 +308,10 @@ export class ScriptEngine {
|
||||
displayEditorButtons,
|
||||
customComponents,
|
||||
blockPointerInputOutsideModal,
|
||||
),
|
||||
controlsOnTop,
|
||||
draggable
|
||||
);
|
||||
},
|
||||
suggester: (
|
||||
displayItems: string[],
|
||||
items: any[],
|
||||
@@ -336,6 +355,8 @@ export class ScriptEngine {
|
||||
displayEditorButtons?: boolean,
|
||||
customComponents?: (container: HTMLElement) => void,
|
||||
blockPointerInputOutsideModal?: boolean,
|
||||
controlsOnTop?: boolean,
|
||||
draggable: boolean = false,
|
||||
) {
|
||||
try {
|
||||
return await GenericInputPrompt.Prompt(
|
||||
@@ -350,6 +371,8 @@ export class ScriptEngine {
|
||||
displayEditorButtons,
|
||||
customComponents,
|
||||
blockPointerInputOutsideModal,
|
||||
controlsOnTop,
|
||||
draggable
|
||||
);
|
||||
} catch {
|
||||
return undefined;
|
||||
|
||||
@@ -11,7 +11,7 @@ function createWorkerBlob(jsCode:string) {
|
||||
const workerCode = `
|
||||
var LZString=function(){var r=String.fromCharCode,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$",e={};function t(r,o){if(!e[r]){e[r]={};for(var n=0;n<r.length;n++)e[r][r.charAt(n)]=n}return e[r][o]}var i={compressToBase64:function(r){if(null==r)return"";var n=i._compress(r,6,function(r){return o.charAt(r)});switch(n.length%4){default:case 0:return n;case 1:return n+"===";case 2:return n+"==";case 3:return n+"="}},decompressFromBase64:function(r){return null==r?"":""==r?null:i._decompress(r.length,32,function(n){return t(o,r.charAt(n))})},compressToUTF16:function(o){return null==o?"":i._compress(o,15,function(o){return r(o+32)})+" "},decompressFromUTF16:function(r){return null==r?"":""==r?null:i._decompress(r.length,16384,function(o){return r.charCodeAt(o)-32})},compressToUint8Array:function(r){for(var o=i.compress(r),n=new Uint8Array(2*o.length),e=0,t=o.length;e<t;e++){var s=o.charCodeAt(e);n[2*e]=s>>>8,n[2*e+1]=s%256}return n},decompressFromUint8Array:function(o){if(null==o)return i.decompress(o);for(var n=new Array(o.length/2),e=0,t=n.length;e<t;e++)n[e]=256*o[2*e]+o[2*e+1];var s=[];return n.forEach(function(o){s.push(r(o))}),i.decompress(s.join(""))},compressToEncodedURIComponent:function(r){return null==r?"":i._compress(r,6,function(r){return n.charAt(r)})},decompressFromEncodedURIComponent:function(r){return null==r?"":""==r?null:(r=r.replace(/ /g,"+"),i._decompress(r.length,32,function(o){return t(n,r.charAt(o))}))},compress:function(o){return i._compress(o,16,function(o){return r(o)})},_compress:function(r,o,n){if(null==r)return"";var e,t,i,s={},u={},a="",p="",c="",l=2,f=3,h=2,d=[],m=0,v=0;for(i=0;i<r.length;i+=1)if(a=r.charAt(i),Object.prototype.hasOwnProperty.call(s,a)||(s[a]=f++,u[a]=!0),p=c+a,Object.prototype.hasOwnProperty.call(s,p))c=p;else{if(Object.prototype.hasOwnProperty.call(u,c)){if(c.charCodeAt(0)<256){for(e=0;e<h;e++)m<<=1,v==o-1?(v=0,d.push(n(m)),m=0):v++;for(t=c.charCodeAt(0),e=0;e<8;e++)m=m<<1|1&t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t>>=1}else{for(t=1,e=0;e<h;e++)m=m<<1|t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t=0;for(t=c.charCodeAt(0),e=0;e<16;e++)m=m<<1|1&t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t>>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[c]}else for(t=s[c],e=0;e<h;e++)m=m<<1|1&t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t>>=1;0==--l&&(l=Math.pow(2,h),h++),s[p]=f++,c=String(a)}if(""!==c){if(Object.prototype.hasOwnProperty.call(u,c)){if(c.charCodeAt(0)<256){for(e=0;e<h;e++)m<<=1,v==o-1?(v=0,d.push(n(m)),m=0):v++;for(t=c.charCodeAt(0),e=0;e<8;e++)m=m<<1|1&t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t>>=1}else{for(t=1,e=0;e<h;e++)m=m<<1|t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t=0;for(t=c.charCodeAt(0),e=0;e<16;e++)m=m<<1|1&t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t>>=1}0==--l&&(l=Math.pow(2,h),h++),delete u[c]}else for(t=s[c],e=0;e<h;e++)m=m<<1|1&t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t>>=1;0==--l&&(l=Math.pow(2,h),h++)}for(t=2,e=0;e<h;e++)m=m<<1|1&t,v==o-1?(v=0,d.push(n(m)),m=0):v++,t>>=1;for(;;){if(m<<=1,v==o-1){d.push(n(m));break}v++}return d.join("")},decompress:function(r){return null==r?"":""==r?null:i._decompress(r.length,32768,function(o){return r.charCodeAt(o)})},_decompress:function(o,n,e){var t,i,s,u,a,p,c,l=[],f=4,h=4,d=3,m="",v=[],g={val:e(0),position:n,index:1};for(t=0;t<3;t+=1)l[t]=t;for(s=0,a=Math.pow(2,2),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;switch(s){case 0:for(s=0,a=Math.pow(2,8),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;c=r(s);break;case 1:for(s=0,a=Math.pow(2,16),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;c=r(s);break;case 2:return""}for(l[3]=c,i=c,v.push(c);;){if(g.index>o)return"";for(s=0,a=Math.pow(2,d),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;switch(c=s){case 0:for(s=0,a=Math.pow(2,8),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;l[h++]=r(s),c=h-1,f--;break;case 1:for(s=0,a=Math.pow(2,16),p=1;p!=a;)u=g.val&g.position,g.position>>=1,0==g.position&&(g.position=n,g.val=e(g.index++)),s|=(u>0?1:0)*p,p<<=1;l[h++]=r(s),c=h-1,f--;break;case 2:return v.join("")}if(0==f&&(f=Math.pow(2,d),d++),l[c])m=l[c];else{if(c!==h)return null;m=i+i.charAt(0)}v.push(m),l[h++]=i+m.charAt(0),i=m,0==--f&&(f=Math.pow(2,d),d++)}}};return i}();"function"==typeof define&&define.amd?define(function(){return LZString}):"undefined"!=typeof module&&null!=module?module.exports=LZString:"undefined"!=typeof angular&&null!=angular&&angular.module("LZString",[]).factory("LZString",function(){return LZString});
|
||||
self.onmessage = function(e) {
|
||||
const { data, action } = e.data;
|
||||
const { data, action, messageId } = e.data;
|
||||
try {
|
||||
switch (action) {
|
||||
case 'compress':
|
||||
@@ -22,7 +22,7 @@ self.onmessage = function(e) {
|
||||
for (let i = 0; i < compressed.length; i += chunkSize) {
|
||||
result += compressed.slice(i, i + chunkSize) + '\\n\\n';
|
||||
}
|
||||
self.postMessage({ compressed: result.trim() });
|
||||
self.postMessage({ messageId, compressed: result.trim() });
|
||||
break;
|
||||
case 'decompress':
|
||||
if (!data) throw new Error("No input string provided for decompression.");
|
||||
@@ -35,14 +35,13 @@ self.onmessage = function(e) {
|
||||
}
|
||||
}
|
||||
const decompressed = LZString.decompressFromBase64(cleanedData);
|
||||
self.postMessage({ decompressed });
|
||||
self.postMessage({ messageId, decompressed });
|
||||
break;
|
||||
default:
|
||||
throw new Error("Unknown action.");
|
||||
}
|
||||
} catch (error) {
|
||||
// Post the error message back to the main thread
|
||||
self.postMessage({ error: error.message });
|
||||
self.postMessage({ messageId, error: error.message });
|
||||
}
|
||||
};
|
||||
`;
|
||||
@@ -55,27 +54,48 @@ export function initCompressionWorker() {
|
||||
}
|
||||
}
|
||||
|
||||
export async function runCompressionWorker(data:string, action: 'compress' | 'decompress'): Promise<string> {
|
||||
let messageCounter = 0;
|
||||
const pendingOperations = new Map<number, {
|
||||
resolve: (value: string) => void,
|
||||
reject: (reason: Error) => void
|
||||
}>();
|
||||
|
||||
export async function runCompressionWorker(data: string, action: 'compress' | 'decompress'): Promise<string> {
|
||||
const messageId = messageCounter++;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
worker.onmessage = function(e) {
|
||||
const { compressed, decompressed, error } = e.data;
|
||||
|
||||
if (error) {
|
||||
reject(new Error(error));
|
||||
} else if (compressed || decompressed) {
|
||||
resolve(compressed || decompressed);
|
||||
} else {
|
||||
reject(new Error('Unexpected response from worker'));
|
||||
}
|
||||
};
|
||||
// Store the promise handlers
|
||||
pendingOperations.set(messageId, { resolve, reject });
|
||||
|
||||
// Set up the worker's error handler
|
||||
worker.onerror = function(error) {
|
||||
reject(new Error(error.message));
|
||||
};
|
||||
// Set up worker message handler if not already set
|
||||
if (!worker.onmessage) {
|
||||
worker.onmessage = function(e) {
|
||||
const { messageId, compressed, decompressed, error } = e.data;
|
||||
const handlers = pendingOperations.get(messageId);
|
||||
|
||||
if (handlers) {
|
||||
if (error) {
|
||||
handlers.reject(new Error(error));
|
||||
} else if (compressed || decompressed) {
|
||||
handlers.resolve(compressed || decompressed);
|
||||
} else {
|
||||
handlers.reject(new Error('Unexpected response from worker'));
|
||||
}
|
||||
pendingOperations.delete(messageId);
|
||||
}
|
||||
};
|
||||
|
||||
// Post the message to the worker
|
||||
worker.postMessage({ data, action });
|
||||
worker.onerror = function(error) {
|
||||
// Handle any pending operations in case of worker error
|
||||
for (const [id, handlers] of pendingOperations) {
|
||||
handlers.reject(new Error(error.message));
|
||||
pendingOperations.delete(id);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Post message with ID
|
||||
worker.postMessage({ messageId, data, action });
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
306
src/shared/components/ContentSearcher.ts
Normal file
@@ -0,0 +1,306 @@
|
||||
import { t } from "src/lang/helpers";
|
||||
import { escapeRegExp } from "../../utils/utils";
|
||||
// @ts-ignore
|
||||
import { getIcon, htmlToMarkdown, Notice } from "obsidian";
|
||||
|
||||
export class ContentSearcher {
|
||||
private contentDiv: HTMLElement;
|
||||
private searchBar: HTMLInputElement;
|
||||
private prevButton: HTMLButtonElement;
|
||||
private nextButton: HTMLButtonElement;
|
||||
private exportMarkdown: HTMLButtonElement;
|
||||
private showHideButton: HTMLButtonElement;
|
||||
private customElemenentContainer: HTMLDivElement;
|
||||
private inputContainer: HTMLDivElement;
|
||||
private customElement: HTMLElement;
|
||||
private hitCount: HTMLSpanElement;
|
||||
private searchBarWrapper: HTMLDivElement;
|
||||
|
||||
constructor(contentDiv: HTMLElement, customElement?: HTMLElement) {
|
||||
this.contentDiv = contentDiv;
|
||||
this.customElement = customElement;
|
||||
this.createSearchElements();
|
||||
this.setupEventListeners();
|
||||
contentDiv.prepend(this.getSearchBarWrapper());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates search UI elements styled like Obsidian's native search
|
||||
*/
|
||||
private createSearchElements(): void {
|
||||
this.searchBarWrapper = createDiv("excalidraw-search document-search-container");
|
||||
const documentSearch = createDiv("document-search");
|
||||
this.inputContainer = createDiv("search-input-container document-search-input");
|
||||
this.searchBar = createEl("input",{type: "text", placeholder: "Find..."});
|
||||
this.hitCount = createDiv("document-search-count");
|
||||
|
||||
this.inputContainer.appendChild(this.searchBar);
|
||||
this.inputContainer.appendChild(this.hitCount);
|
||||
const buttonContainer = createDiv("document-search-buttons");
|
||||
|
||||
this.prevButton = createEl("button", {
|
||||
cls: ["clickable-icon", "document-search-button"],
|
||||
attr: {
|
||||
"aria-label": t("SEARCH_PREVIOUS"),
|
||||
"data-tooltip-position": "top",
|
||||
},
|
||||
type: "button",
|
||||
});
|
||||
this.prevButton.innerHTML = getIcon("arrow-up").outerHTML;
|
||||
|
||||
this.nextButton = createEl("button", {
|
||||
cls: ["clickable-icon", "document-search-button"],
|
||||
attr: {
|
||||
"aria-label": t("SEARCH_NEXT"),
|
||||
"data-tooltip-position": "top",
|
||||
},
|
||||
type: "button",
|
||||
});
|
||||
this.nextButton.innerHTML = getIcon("arrow-down").outerHTML;
|
||||
|
||||
this.exportMarkdown = createEl("button", {
|
||||
cls: ["clickable-icon", "document-search-button"],
|
||||
attr: {
|
||||
"aria-label": t("SEARCH_COPY_TO_CLIPBOARD_ARIA"),
|
||||
"data-tooltip-position": "top",
|
||||
},
|
||||
type: "button",
|
||||
});
|
||||
this.exportMarkdown.innerHTML = getIcon("clipboard-copy").outerHTML;
|
||||
|
||||
this.showHideButton = createEl("button", {
|
||||
cls: ["clickable-icon", "document-search-button", "search-visible"],
|
||||
attr: {
|
||||
"aria-label": t("SEARCH_SHOWHIDE_ARIA"),
|
||||
"data-tooltip-position": "top",
|
||||
},
|
||||
type: "button",
|
||||
});
|
||||
this.showHideButton.innerHTML = getIcon("minimize-2").outerHTML;
|
||||
|
||||
buttonContainer.appendChild(this.prevButton);
|
||||
buttonContainer.appendChild(this.nextButton);
|
||||
buttonContainer.appendChild(this.exportMarkdown);
|
||||
buttonContainer.appendChild(this.showHideButton);
|
||||
|
||||
documentSearch.appendChild(this.inputContainer);
|
||||
documentSearch.appendChild(buttonContainer);
|
||||
|
||||
this.searchBarWrapper.appendChild(documentSearch);
|
||||
|
||||
this.customElemenentContainer = createDiv();
|
||||
if(this.customElement) {
|
||||
this.customElemenentContainer.appendChild(this.customElement);
|
||||
this.searchBarWrapper.appendChild(this.customElemenentContainer)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach event listeners to search elements
|
||||
*/
|
||||
private setupEventListeners(): void {
|
||||
this.nextButton.onclick = () => this.navigateSearchResults("next");
|
||||
this.prevButton.onclick = () => this.navigateSearchResults("previous");
|
||||
this.exportMarkdown.onclick = () => {
|
||||
// Get the full HTML content first
|
||||
const fullHtml = this.contentDiv.outerHTML;
|
||||
|
||||
// Find the index of the first <hr> element
|
||||
const startIndex = fullHtml.indexOf('<hr');
|
||||
|
||||
// Extract HTML from the first <hr> element onwards
|
||||
const html = startIndex > -1 ? fullHtml.substring(startIndex) : fullHtml;
|
||||
|
||||
function replaceHeading(html:string,level:number):string {
|
||||
const re = new RegExp(`<summary class="excalidraw-setting-h${level}">([^<]+)<\/summary>`,"g");
|
||||
return html.replaceAll(re,`<summary class="excalidraw-setting-h${level}"><h${level}>$1</h${level}></summary>`);
|
||||
}
|
||||
|
||||
let x = replaceHeading(html,1);
|
||||
x = replaceHeading(x,2);
|
||||
x = replaceHeading(x,3);
|
||||
x = replaceHeading(x,4);
|
||||
x = x.replaceAll(/<div class="setting-item-name">([^<]+)<\/div>/g,"<h5>$1</h5>");
|
||||
|
||||
const md = htmlToMarkdown(x);
|
||||
window.navigator.clipboard.writeText(md);
|
||||
new Notice(t("SEARCH_COPIED_TO_CLIPBOARD"));
|
||||
};
|
||||
this.showHideButton.onclick = () => {
|
||||
const setOpacity = (value:string|null) => {
|
||||
this.inputContainer.style.opacity = value;
|
||||
this.prevButton.style.opacity = value;
|
||||
this.nextButton.style.opacity = value;
|
||||
this.exportMarkdown.style.opacity = value;
|
||||
this.customElemenentContainer.style.opacity = value;
|
||||
}
|
||||
if(this.showHideButton.hasClass("search-visible")) {
|
||||
this.showHideButton.removeClass("search-visible");
|
||||
this.showHideButton.addClass("search-hidden");
|
||||
this.searchBarWrapper.style.backgroundColor = "transparent";
|
||||
setOpacity("0");
|
||||
this.showHideButton.innerHTML = getIcon("maximize-2").outerHTML;
|
||||
} else {
|
||||
this.showHideButton.removeClass("search-hidden");
|
||||
this.showHideButton.addClass("search-visible");
|
||||
this.searchBarWrapper.style.backgroundColor = null;
|
||||
setOpacity(null);
|
||||
this.showHideButton.innerHTML = getIcon("minimize-2").outerHTML;
|
||||
}
|
||||
}
|
||||
|
||||
this.searchBar.addEventListener("input", (e) => {
|
||||
this.clearHighlights();
|
||||
const searchTerm = (e.target as HTMLInputElement).value;
|
||||
|
||||
if (searchTerm && searchTerm.length > 0) {
|
||||
this.highlightSearchTerm(searchTerm);
|
||||
const totalHits = this.contentDiv.querySelectorAll("mark.search-highlight").length;
|
||||
this.hitCount.textContent = totalHits > 0 ? `1 / ${totalHits}` : "";
|
||||
setTimeout(() => this.navigateSearchResults("next"));
|
||||
} else {
|
||||
this.hitCount.textContent = "";
|
||||
}
|
||||
});
|
||||
|
||||
this.searchBar.addEventListener("keydown", (e) => {
|
||||
// If Ctrl/Cmd + F is pressed, focus on search bar
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === "f") {
|
||||
e.preventDefault();
|
||||
this.searchBar.focus();
|
||||
}
|
||||
// If Enter is pressed, navigate to next result
|
||||
else if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
this.navigateSearchResults(e.shiftKey ? "previous" : "next");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the search bar wrapper element to add to the DOM
|
||||
*/
|
||||
public getSearchBarWrapper(): HTMLElement {
|
||||
return this.searchBarWrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Highlight all instances of the search term in the content
|
||||
*/
|
||||
public highlightSearchTerm(searchTerm: string): void {
|
||||
// Create a walker to traverse text nodes
|
||||
const walker = document.createTreeWalker(
|
||||
this.contentDiv,
|
||||
NodeFilter.SHOW_TEXT,
|
||||
{
|
||||
acceptNode: (node: Text) => {
|
||||
return node.nodeValue!.toLowerCase().includes(searchTerm.toLowerCase()) ?
|
||||
NodeFilter.FILTER_ACCEPT :
|
||||
NodeFilter.FILTER_REJECT;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const nodesToReplace: Text[] = [];
|
||||
while (walker.nextNode()) {
|
||||
nodesToReplace.push(walker.currentNode as Text);
|
||||
}
|
||||
|
||||
nodesToReplace.forEach(node => {
|
||||
const nodeContent = node.nodeValue!;
|
||||
const newNode = document.createDocumentFragment();
|
||||
|
||||
let lastIndex = 0;
|
||||
let match;
|
||||
const regex = new RegExp(escapeRegExp(searchTerm), 'gi');
|
||||
|
||||
// Iterate over all matches in the text node
|
||||
while ((match = regex.exec(nodeContent)) !== null) {
|
||||
const before = document.createTextNode(nodeContent.slice(lastIndex, match.index));
|
||||
const highlighted = document.createElement('mark');
|
||||
highlighted.className = 'search-highlight';
|
||||
highlighted.textContent = match[0];
|
||||
highlighted.classList.add('search-result');
|
||||
|
||||
newNode.appendChild(before);
|
||||
newNode.appendChild(highlighted);
|
||||
|
||||
lastIndex = regex.lastIndex;
|
||||
}
|
||||
newNode.appendChild(document.createTextNode(nodeContent.slice(lastIndex)));
|
||||
node.replaceWith(newNode);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all search highlights
|
||||
*/
|
||||
public clearHighlights(): void {
|
||||
this.contentDiv.querySelectorAll("mark.search-highlight").forEach((el) => {
|
||||
el.outerHTML = el.innerHTML;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to next or previous search result
|
||||
*/
|
||||
public navigateSearchResults(direction: "next" | "previous"): void {
|
||||
const highlights: HTMLElement[] = Array.from(
|
||||
this.contentDiv.querySelectorAll("mark.search-highlight")
|
||||
);
|
||||
|
||||
if (highlights.length === 0) return;
|
||||
|
||||
const currentActiveIndex = highlights.findIndex((highlight) =>
|
||||
highlight.classList.contains("active-highlight")
|
||||
);
|
||||
|
||||
if (currentActiveIndex !== -1) {
|
||||
highlights[currentActiveIndex].classList.remove("active-highlight");
|
||||
highlights[currentActiveIndex].style.border = "none";
|
||||
}
|
||||
|
||||
let nextActiveIndex = 0;
|
||||
if (direction === "next") {
|
||||
nextActiveIndex =
|
||||
currentActiveIndex === highlights.length - 1
|
||||
? 0
|
||||
: currentActiveIndex + 1;
|
||||
} else if (direction === "previous") {
|
||||
nextActiveIndex =
|
||||
currentActiveIndex === 0
|
||||
? highlights.length - 1
|
||||
: currentActiveIndex - 1;
|
||||
}
|
||||
|
||||
const nextActiveHighlight = highlights[nextActiveIndex];
|
||||
nextActiveHighlight.classList.add("active-highlight");
|
||||
|
||||
// Expand all parent details elements
|
||||
this.expandParentDetails(nextActiveHighlight);
|
||||
|
||||
// Use setTimeout to ensure DOM has time to update after expanding details
|
||||
setTimeout(() => {
|
||||
nextActiveHighlight.scrollIntoView({
|
||||
behavior: "smooth",
|
||||
block: "nearest",
|
||||
});
|
||||
}, 100);
|
||||
|
||||
// Update the hit count
|
||||
this.hitCount.textContent = `${nextActiveIndex + 1} / ${highlights.length}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expand all parent <details> elements to make the element visible
|
||||
*/
|
||||
private expandParentDetails(element: HTMLElement): void {
|
||||
let parent = element.parentElement;
|
||||
while (parent) {
|
||||
if (parent.tagName === "DETAILS") {
|
||||
parent.setAttribute("open", "");
|
||||
}
|
||||
parent = parent.parentElement;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { randomId, randomInteger } from "../utils";
|
||||
|
||||
import { ExcalidrawLinearElement, FillStyle, GroupId, RoundnessType, StrokeStyle } from "@zsviczian/excalidraw/types/excalidraw/element/types";
|
||||
import { ExcalidrawLinearElement, FillStyle, GroupId, RoundnessType, StrokeStyle } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
|
||||
export type Point = [number, number];
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ExcalidrawElement, ExcalidrawLinearElement, ExcalidrawTextElement, FillStyle, GroupId, RoundnessType, StrokeStyle } from "@zsviczian/excalidraw/types/excalidraw/element/types";
|
||||
import { ExcalidrawElement, ExcalidrawLinearElement, ExcalidrawTextElement, FillStyle, GroupId, RoundnessType, StrokeStyle } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
|
||||
export type PathCommand = {
|
||||
type: string;
|
||||
|
||||
29
src/types/excalidrawLib.d.ts
vendored
@@ -1,11 +1,11 @@
|
||||
import { RestoredDataState } from "@zsviczian/excalidraw/types/excalidraw/data/restore";
|
||||
import { ImportedDataState } from "@zsviczian/excalidraw/types/excalidraw/data/types";
|
||||
import { BoundingBox } from "@zsviczian/excalidraw/types/excalidraw/element/bounds";
|
||||
import { ElementsMap, ExcalidrawBindableElement, ExcalidrawElement, ExcalidrawFrameElement, ExcalidrawFrameLikeElement, ExcalidrawTextContainer, ExcalidrawTextElement, FontFamilyValues, FontString, NonDeleted, NonDeletedExcalidrawElement, Theme } from "@zsviczian/excalidraw/types/excalidraw/element/types";
|
||||
import { FontMetadata } from "@zsviczian/excalidraw/types/excalidraw/fonts/FontMetadata";
|
||||
import { BoundingBox } from "@zsviczian/excalidraw/types/element/src";
|
||||
import { ElementsMap, ExcalidrawBindableElement, ExcalidrawElement, ExcalidrawFrameElement, ExcalidrawFrameLikeElement, ExcalidrawTextContainer, ExcalidrawTextElement, FontFamilyValues, FontString, NonDeleted, NonDeletedExcalidrawElement, OrderedExcalidrawElement, Theme } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { FontMetadata } from "@zsviczian/excalidraw/types/common/src";
|
||||
import { AppState, BinaryFiles, DataURL, GenerateDiagramToCode, Zoom } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/excalidraw/utility-types";
|
||||
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/src/types";
|
||||
|
||||
interface MermaidConfig {
|
||||
/**
|
||||
@@ -52,7 +52,7 @@ type EmbeddedLink =
|
||||
declare namespace ExcalidrawLib {
|
||||
type ElementUpdate<TElement extends ExcalidrawElement> = Omit<
|
||||
Partial<TElement>,
|
||||
"id" | "version" | "versionNonce"
|
||||
"id" | "updated"
|
||||
>;
|
||||
|
||||
type ExportOpts = {
|
||||
@@ -106,12 +106,6 @@ declare namespace ExcalidrawLib {
|
||||
},
|
||||
): { x: number; y: number };
|
||||
|
||||
function determineFocusDistance(
|
||||
element: ExcalidrawBindableElement,
|
||||
a: GlobalPoint,
|
||||
b: GlobalPoint,
|
||||
): number;
|
||||
|
||||
function intersectElementWithLine(
|
||||
element: ExcalidrawBindableElement,
|
||||
a: GlobalPoint,
|
||||
@@ -146,6 +140,15 @@ declare namespace ExcalidrawLib {
|
||||
elementsMap: ElementsMap,
|
||||
): ExcalidrawElement[][];
|
||||
|
||||
function getFontMetrics(fontFamily: ExcalidrawTextElement["fontFamily"], fontSize?:number): {
|
||||
unitsPerEm: number,
|
||||
ascender: number,
|
||||
descender: number,
|
||||
lineHeight: number,
|
||||
baseline: number,
|
||||
fontString: string
|
||||
}
|
||||
|
||||
function measureText(
|
||||
text: string,
|
||||
font: FontString,
|
||||
@@ -221,5 +224,7 @@ declare namespace ExcalidrawLib {
|
||||
function safelyParseJSON (json: string): Record<string, any> | null;
|
||||
function loadSceneFonts(elements: NonDeletedExcalidrawElement[]): Promise<void>;
|
||||
function loadMermaid(): Promise<any>;
|
||||
function syncInvalidIndices(elements: readonly ExcalidrawElement[]): OrderedExcalidrawElement[];
|
||||
function syncMovedIndices(elements: readonly ExcalidrawElement[], movedElements: ElementsMap): OrderedExcalidrawElement[];
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// src/types/ExcalidrawViewTypes.ts
|
||||
|
||||
import { WorkspaceLeaf } from "obsidian";
|
||||
import { FileId } from "@zsviczian/excalidraw/types/excalidraw/element/types";
|
||||
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ObsidianCanvasNode } from "../view/managers/CanvasNodeFactory";
|
||||
|
||||
export type Position = { x: number; y: number };
|
||||
@@ -22,11 +22,19 @@ export interface EmbeddableLeafRef {
|
||||
editNode?: Function;
|
||||
}
|
||||
|
||||
export interface AutoexportConfig {
|
||||
png: boolean; // Whether to auto-export to PNG
|
||||
svg: boolean; // Whether to auto-export to SVG
|
||||
excalidraw: boolean; // Whether to auto-export to Excalidraw format
|
||||
theme: "light" | "dark" | "both"; // The theme to use for the export
|
||||
}
|
||||
|
||||
export interface ViewSemaphores {
|
||||
warnAboutLinearElementLinkClick: boolean;
|
||||
//flag to prevent overwriting the changes the user makes in an embeddable view editing the back side of the drawing
|
||||
embeddableIsEditingSelf: boolean;
|
||||
popoutUnload: boolean; //the unloaded Excalidraw view was the last leaf in the popout window
|
||||
viewloaded: boolean; //onLayoutReady in view.onload has completed.
|
||||
viewunload: boolean;
|
||||
//first time initialization of the view
|
||||
scriptsReady: boolean;
|
||||
|
||||
14
src/types/promptTypes.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
export type ButtonDefinition = { caption: string; tooltip?:string; action: Function };
|
||||
|
||||
export interface InputPromptOptions {
|
||||
header: string,
|
||||
placeholder?: string,
|
||||
value?: string,
|
||||
buttons?: ButtonDefinition[],
|
||||
lines?: number,
|
||||
displayEditorButtons?: boolean,
|
||||
customComponents?: (container: HTMLElement) => void,
|
||||
blockPointerInputOutsideModal?: boolean,
|
||||
controlsOnTop?: boolean,
|
||||
draggable?: boolean,
|
||||
}
|
||||
1
src/types/types.d.ts
vendored
@@ -18,6 +18,7 @@ export type GridSettings = {
|
||||
DYNAMIC_COLOR: boolean; // Whether the grid color is dynamic
|
||||
COLOR: string; // The grid color (in hex format)
|
||||
OPACITY: number; // The grid opacity (hex value between "00" and "FF")
|
||||
GRID_DIRECTION: {horizontal: boolean, vertical: boolean}; // Whether the grid is horizontal or vertical
|
||||
};
|
||||
|
||||
export type DeviceType = {
|
||||
|
||||
@@ -17,4 +17,11 @@ export enum PreviewImageType {
|
||||
PNG = "PNG",
|
||||
SVGIMG = "SVGIMG",
|
||||
SVG = "SVG"
|
||||
}
|
||||
|
||||
export interface FrameRenderingOptions {
|
||||
enabled: boolean;
|
||||
name: boolean;
|
||||
outline: boolean;
|
||||
clip: boolean;
|
||||
}
|
||||