Compare commits

..
14 Commits
31 changed files with 11590 additions and 9828 deletions

No files matched your search

+96
View File
@@ -0,0 +1,96 @@
# Contributing to Obsidian Excalidraw Plugin
First off, thank you for considering contributing to the Obsidian Excalidraw plugin! This project integrates a heavily customized Excalidraw fork into Obsidian.
Because this is not a generic React canvas app, but rather a deeply integrated Obsidian plugin with popout window support, mobile compatibility constraints, and performance optimizations, please read the following guidelines carefully before making any changes.
## 💬 Discuss First
Before spending your valuable time writing code for a new feature or significant refactor, please **open an issue** to discuss it first. This ensures your idea aligns with the project's roadmap and architecture, and helps prevent wasted effort or complex merge conflicts later.
## 🚀 Getting Started
1. Fork the repository and clone it locally.
2. Run `npm install` in the root directory to install the main dependencies.
*(Note: The `MathjaxToSVG` sub-component has its own separate dependencies. You do not need to install them manually; the first time you run `npm run build`, it will take care of this automatically).*
3. To test your changes locally, we recommend symlinking your cloned repository folder into a test Obsidian vault's `.obsidian/plugins/obsidian-excalidraw-plugin` directory. (Using a community plugin like [Obsidian Hot Reload](https://github.com/pjeby/hot-reload) will make local development much faster).
## 🛠️ Build and Lint Commands
- **Build the project:** Run `npm run build`
*(Note: Our Rollup build is non-trivial as it merges CSS, handles MathjaxToSVG dependencies, and embeds runtime payloads. Run this command frequently to validate your changes).*
- **Run ESLint:** Run `npm run code`
- **Fix ESLint Warnings:** Run `node ./scripts/fix-eslint-warnings.mjs`
## 🧪 Testing
At this time, the project **has no automated tests**. As a contributor, you are responsible for testing your changes thoroughly.
Because Obsidian runs across a variety of environments, please manually test your changes on as many of the following platforms as possible to avoid breaking the plugin for other users:
- Desktop: Mac, Windows, Linux
- Mobile: Android, iOS (Test on both Phones and Tablets)
## 🏗️ Architecture & Sub-components
This project consists of multiple sub-components and non-standard integrations to support Obsidian-specific features.
### 1. React & Package Manager
Because the plugin must support Obsidian's native popout windows, React and Excalidraw cannot be loaded as simple global singletons.
- References to React and ReactDOM are handled via `PackageManager.ts` (`src/core/managers/PackageManager.ts`).
- They are loaded to Obsidian popout windows separately during runtime. Do not introduce direct `ReactDOM.createRoot()` or similar global React calls outside of this package manager model.
### 2. MathjaxToSVG
LaTeX support is provided by the `MathjaxToSVG` library, which is packaged as a separate sub-component (located in the `MathjaxToSVG/` folder).
- It is compressed using `LZString` during build time.
- It is decompressed and executed dynamically during runtime only when needed, maintaining optimal Obsidian startup times.
### 3. Excalidraw Fork Guidelines
This plugin relies on a custom Excalidraw component fork: [`zsviczian/excalidraw`](https://github.com/zsviczian/excalidraw/).
If you must submit a PR to the Excalidraw fork, **keep changes to the absolute minimum**. Compounding changes to the fork make merging upstream updates from `excalidraw/excalidraw` exponentially harder.
- **Resist the temptation:** Do not implement features in the fork if they can be achieved using plugin wrappers, monkey patches, or API integrations within the main Obsidian plugin repo.
- **Use ringfenced areas:** Place changes in files clearly marked for the fork whenever possible:
- `packages/excalidraw/obsidianUtils.ts`
- `packages/common/src/commonObsidianUtils.ts`
- `packages/excalidraw/css/obsidianStylingOverrides.css`
- **Mark your changes explicitly:** Add a comment with your initials and the Issue or PR ID to easily identify custom additions during merge conflicts.
```ts
private shouldRenderAllEmbeddables: boolean = false; //zsviczian
```
- **Use dedicated functions:** If your code extension doesn't fit neatly into the ringfenced files, extract it into a dedicated new function rather than putting huge chunks of logic inline.
```ts
//mfuria #329. Right-click pan support when enabled via host plugin setting
if (
isPanWithRightMouseEnabled() &&
event.pointerType === "mouse" &&
event.button === POINTER_BUTTON.SECONDARY &&
!this.state.editingTextElement
) {
// prevent native context menu
const onContextMenu = (e: MouseEvent) => {
e.preventDefault();
};
window.addEventListener('contextmenu', onContextMenu, { once: true });
// Start right-click panning
this.startRightClickPanning(event);
return;
}
//mfuria #329. start right-click panning
private startRightClickPanning(event) { ... }
```
## 🌍 Localization & User-Facing Text
- **No hardcoded strings:** There should be no hardcoded English strings directly in the UI components or logic.
- **Language files:** All strings must be added to the localization files located in `src/lang/locale/`.
- **Translations:** At a minimum, you must add your new keys and strings to `en.ts`. However, it is highly appreciated if you can provide translated strings for all of our actively maintained translations (`es.ts`, `ru.ts`, `zh-cn.ts`, `zh-tw.ts`) using a translation tool.
## 📦 Pull Requests & Versioning
- **Do NOT bump versions:** Please do not bump the version numbers in `manifest.json`, `manifest-beta.json`, or `package.json` in your Pull Requests. Version bumping and release coordination are handled exclusively by the maintainer during the final GitHub Release workflow.
- **Release Notes:** If you are adding a feature or fixing a bug that users need to know about, please document it in `src/shared/Dialogs/Messages.ts` under the upcoming version key.
Once again, thank you for contributing to the plugin!
@@ -7,7 +7,7 @@
/* ************************************** */
type MutableElementMapEntry = Mutable<ExcalidrawElement> & Record<string, unknown>;
import { PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFPageProperties, ExportSettings } from "src/types/exportUtilTypes";
import { FrameRenderingOptions } from "src/types/utilTypes";
import { FrameRenderingOptions, PaneTarget } from "src/types/utilTypes";
import { AutoexportConfig } from "src/types/excalidrawViewTypes";
import { FloatingModal } from "./Dialogs/FloatingModal";
import { ExcalidrawSidepanelTab } from "src/view/sidepanel/SidepanelTab";
@@ -1122,8 +1122,9 @@ export declare class ExcalidrawAutomate {
* Zooms the target view to fit the specified elements.
* @param {boolean} selectElements - Whether to select the elements after zooming.
* @param {ExcalidrawElement[]} elements - Array of elements to zoom to.
* @param {number} [margin=0.05] - The margin around the elements when zooming.
*/
viewZoomToElements(selectElements: boolean, elements: ExcalidrawElement[]): void;
viewZoomToElements(selectElements: boolean, elements: ExcalidrawElement[], margin?: number): void;
/**
* Adds elements from elementsDict to the current view.
* @param {boolean} [repositionToCursor=false] - Whether to reposition the elements to the cursor.
@@ -1524,6 +1525,15 @@ export declare class ExcalidrawAutomate {
* @returns {ExcalidrawElement} The cloned element with a new ID.
*/
cloneElement(element: ExcalidrawElement): ExcalidrawElement;
/**
* Clones an array of Excalidraw elements or a clipboard string.
* Ensures that relationships (containers, bound elements, groups, bindings)
* are correctly remapped to the newly generated IDs.
*
* @param {ExcalidrawElement[] | string} elementsOrClipboard - The elements array or Excalidraw clipboard string.
* @returns {ExcalidrawElement[]} An array of cloned elements with new IDs and updated relationships.
*/
cloneElements(elementsOrClipboard: ExcalidrawElement[] | string): ExcalidrawElement[];
/**
* Moves the specified element to a specific position in the z-index.
* * Operates directly on the Excalidraw Scene in targetView, not through ExcalidrawAutomate elements.
@@ -1797,6 +1807,7 @@ export interface FrameRenderingOptions {
outline: boolean;
clip: boolean;
}
export type PaneTarget = "active-pane" | "new-pane" | "popout-window" | "new-tab" | "md-properties";
/* ************************************ */
/* lib/types/exportUtilTypes.d.ts */
@@ -3491,7 +3502,6 @@ declare class App extends React.Component<AppProps, AppState> {
y: number;
};
allowMobileMode: boolean;
animationFrameHandler: AnimationFrameHandler;
laserTrails: LaserTrails;
eraserTrail: EraserTrail;
lassoTrail: LassoTrail;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
<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-book-heart-icon lucide-book-heart"><path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20"/><path d="M8.62 9.8A2.25 2.25 0 1 1 12 6.836a2.25 2.25 0 1 1 3.38 2.966l-2.626 2.856a.998.998 0 0 1-1.507 0z"/></svg>

After

Width:  |  Height:  |  Size: 451 B

File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1 +1 @@
[{"fname":"Mindmap connector.md","mtime":1658686599427},{"fname":"Mindmap connector.svg","mtime":1658686599427},{"fname":"Add Connector Point.md","mtime":1735420748564},{"fname":"Add Connector Point.svg","mtime":1645944722000},{"fname":"Add Link to Existing File and Open.md","mtime":1647807918345},{"fname":"Add Link to Existing File and Open.svg","mtime":1645964261000},{"fname":"Add Link to New Page and Open.md","mtime":1654168862138},{"fname":"Add Link to New Page and Open.svg","mtime":1645960639000},{"fname":"Add Next Step in Process.md","mtime":1688304760357},{"fname":"Add Next Step in Process.svg","mtime":1645960639000},{"fname":"Box Each Selected Groups.md","mtime":1645305706000},{"fname":"Box Each Selected Groups.svg","mtime":1645967510000},{"fname":"Box Selected Elements.md","mtime":1645305706000},{"fname":"Box Selected Elements.svg","mtime":1645960639000},{"fname":"Change shape of selected elements.md","mtime":1652701169236},{"fname":"Change shape of selected elements.svg","mtime":1645960775000},{"fname":"Connect elements.md","mtime":1645305706000},{"fname":"Connect elements.svg","mtime":1645960639000},{"fname":"Convert freedraw to line.md","mtime":1645305706000},{"fname":"Convert freedraw to line.svg","mtime":1645960639000},{"fname":"Convert selected text elements to sticky notes.md","mtime":1670169501383},{"fname":"Convert selected text elements to sticky notes.svg","mtime":1645960639000},{"fname":"Convert text to link with folder and alias.md","mtime":1641639819000},{"fname":"Convert text to link with folder and alias.svg","mtime":1645960639000},{"fname":"Copy Selected Element Styles to Global.md","mtime":1642232088000},{"fname":"Copy Selected Element Styles to Global.svg","mtime":1645960639000},{"fname":"Create new markdown file and embed into active drawing.md","mtime":1640866935000},{"fname":"Create new markdown file and embed into active drawing.svg","mtime":1645960639000},{"fname":"Darken background color.md","mtime":1663059051059},{"fname":"Darken background color.svg","mtime":1645960639000},{"fname":"Elbow connectors.md","mtime":1671126911490},{"fname":"Elbow connectors.svg","mtime":1645960639000},{"fname":"Expand rectangles horizontally keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles horizontally keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles horizontally.md","mtime":1644950235000},{"fname":"Expand rectangles horizontally.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles vertically keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically.md","mtime":1658686599427},{"fname":"Expand rectangles vertically.svg","mtime":1645967510000},{"fname":"Fixed horizontal distance between centers.md","mtime":1646743234000},{"fname":"Fixed horizontal distance between centers.svg","mtime":1645960639000},{"fname":"Fixed inner distance.md","mtime":1646743234000},{"fname":"Fixed inner distance.svg","mtime":1645960639000},{"fname":"Fixed spacing.md","mtime":1646743234000},{"fname":"Fixed spacing.svg","mtime":1645967510000},{"fname":"Fixed vertical distance between centers.md","mtime":1646743234000},{"fname":"Fixed vertical distance between centers.svg","mtime":1645967510000},{"fname":"Fixed vertical distance.md","mtime":1646743234000},{"fname":"Fixed vertical distance.svg","mtime":1645967510000},{"fname":"Lighten background color.md","mtime":1663059051059},{"fname":"Lighten background color.svg","mtime":1645959546000},{"fname":"Modify background color opacity.md","mtime":1644924415000},{"fname":"Modify background color opacity.svg","mtime":1645944722000},{"fname":"Normalize Selected Arrows.md","mtime":1670403743278},{"fname":"Normalize Selected Arrows.svg","mtime":1645960639000},{"fname":"Organic Line.md","mtime":1672920172531},{"fname":"Organic Line.svg","mtime":1645964261000},{"fname":"Organic Line Legacy.md","mtime":1690607372668},{"fname":"Organic Line Legacy.svg","mtime":1690607372668},{"fname":"README.md","mtime":1645175700000},{"fname":"Repeat Elements.md","mtime":1663059051059},{"fname":"Repeat Elements.svg","mtime":1645960639000},{"fname":"Reverse arrows.md","mtime":1645305706000},{"fname":"Reverse arrows.svg","mtime":1645960639000},{"fname":"Scribble Helper.md","mtime":1767536720161},{"fname":"Scribble Helper.svg","mtime":1645944722000},{"fname":"Select Elements of Type.md","mtime":1643464321000},{"fname":"Select Elements of Type.svg","mtime":1645960639000},{"fname":"Set Dimensions.md","mtime":1645305706000},{"fname":"Set Dimensions.svg","mtime":1645944722000},{"fname":"Set Font Family.md","mtime":1645305706000},{"fname":"Set Font Family.svg","mtime":1645944722000},{"fname":"Set Grid.md","mtime":1693725826368},{"fname":"Set Grid.svg","mtime":1645960639000},{"fname":"Set Link Alias.md","mtime":1645305706000},{"fname":"Set Link Alias.svg","mtime":1645960639000},{"fname":"Set Stroke Width of Selected Elements.md","mtime":1748189277Line truncated
[{"fname":"Mindmap connector.md","mtime":1658686599427},{"fname":"Mindmap connector.svg","mtime":1658686599427},{"fname":"Add Connector Point.md","mtime":1735420748564},{"fname":"Add Connector Point.svg","mtime":1645944722000},{"fname":"Add Link to Existing File and Open.md","mtime":1647807918345},{"fname":"Add Link to Existing File and Open.svg","mtime":1645964261000},{"fname":"Add Link to New Page and Open.md","mtime":1654168862138},{"fname":"Add Link to New Page and Open.svg","mtime":1645960639000},{"fname":"Add Next Step in Process.md","mtime":1688304760357},{"fname":"Add Next Step in Process.svg","mtime":1645960639000},{"fname":"Box Each Selected Groups.md","mtime":1645305706000},{"fname":"Box Each Selected Groups.svg","mtime":1645967510000},{"fname":"Box Selected Elements.md","mtime":1645305706000},{"fname":"Box Selected Elements.svg","mtime":1645960639000},{"fname":"Change shape of selected elements.md","mtime":1652701169236},{"fname":"Change shape of selected elements.svg","mtime":1645960775000},{"fname":"Connect elements.md","mtime":1645305706000},{"fname":"Connect elements.svg","mtime":1645960639000},{"fname":"Convert freedraw to line.md","mtime":1645305706000},{"fname":"Convert freedraw to line.svg","mtime":1645960639000},{"fname":"Convert selected text elements to sticky notes.md","mtime":1670169501383},{"fname":"Convert selected text elements to sticky notes.svg","mtime":1645960639000},{"fname":"Convert text to link with folder and alias.md","mtime":1641639819000},{"fname":"Convert text to link with folder and alias.svg","mtime":1645960639000},{"fname":"Copy Selected Element Styles to Global.md","mtime":1642232088000},{"fname":"Copy Selected Element Styles to Global.svg","mtime":1645960639000},{"fname":"Create new markdown file and embed into active drawing.md","mtime":1640866935000},{"fname":"Create new markdown file and embed into active drawing.svg","mtime":1645960639000},{"fname":"Darken background color.md","mtime":1663059051059},{"fname":"Darken background color.svg","mtime":1645960639000},{"fname":"Elbow connectors.md","mtime":1671126911490},{"fname":"Elbow connectors.svg","mtime":1645960639000},{"fname":"Expand rectangles horizontally keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles horizontally keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles horizontally.md","mtime":1644950235000},{"fname":"Expand rectangles horizontally.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles vertically keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically.md","mtime":1658686599427},{"fname":"Expand rectangles vertically.svg","mtime":1645967510000},{"fname":"Fixed horizontal distance between centers.md","mtime":1646743234000},{"fname":"Fixed horizontal distance between centers.svg","mtime":1645960639000},{"fname":"Fixed inner distance.md","mtime":1646743234000},{"fname":"Fixed inner distance.svg","mtime":1645960639000},{"fname":"Fixed spacing.md","mtime":1646743234000},{"fname":"Fixed spacing.svg","mtime":1645967510000},{"fname":"Fixed vertical distance between centers.md","mtime":1646743234000},{"fname":"Fixed vertical distance between centers.svg","mtime":1645967510000},{"fname":"Fixed vertical distance.md","mtime":1646743234000},{"fname":"Fixed vertical distance.svg","mtime":1645967510000},{"fname":"Lighten background color.md","mtime":1663059051059},{"fname":"Lighten background color.svg","mtime":1645959546000},{"fname":"Modify background color opacity.md","mtime":1644924415000},{"fname":"Modify background color opacity.svg","mtime":1645944722000},{"fname":"Normalize Selected Arrows.md","mtime":1670403743278},{"fname":"Normalize Selected Arrows.svg","mtime":1645960639000},{"fname":"Organic Line.md","mtime":1672920172531},{"fname":"Organic Line.svg","mtime":1645964261000},{"fname":"Organic Line Legacy.md","mtime":1690607372668},{"fname":"Organic Line Legacy.svg","mtime":1690607372668},{"fname":"README.md","mtime":1645175700000},{"fname":"Repeat Elements.md","mtime":1663059051059},{"fname":"Repeat Elements.svg","mtime":1645960639000},{"fname":"Reverse arrows.md","mtime":1645305706000},{"fname":"Reverse arrows.svg","mtime":1645960639000},{"fname":"Scribble Helper.md","mtime":1767536720161},{"fname":"Scribble Helper.svg","mtime":1645944722000},{"fname":"Select Elements of Type.md","mtime":1643464321000},{"fname":"Select Elements of Type.svg","mtime":1645960639000},{"fname":"Set Dimensions.md","mtime":1645305706000},{"fname":"Set Dimensions.svg","mtime":1645944722000},{"fname":"Set Font Family.md","mtime":1645305706000},{"fname":"Set Font Family.svg","mtime":1645944722000},{"fname":"Set Grid.md","mtime":1693725826368},{"fname":"Set Grid.svg","mtime":1645960639000},{"fname":"Set Link Alias.md","mtime":1645305706000},{"fname":"Set Link Alias.svg","mtime":1645960639000},{"fname":"Set Stroke Width of Selected Elements.md","mtime":1748189277Line truncated
+9
View File
@@ -73,6 +73,7 @@ These are the scripts I use most often. I tried to order them by importance, but
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20freedraw%20to%20line.svg"/></div>|[[#Convert freedraw to line]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Crop%20Vintage%20Mask.svg"/></div>|[[#Crop Vintage Mask]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20Builder.svg"/></div>|[[#Mindmap Builder]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Capture%20Note.svg"/></div>|[[#Capture Note]]|
## Layout and Organization
**Keywords**: Design, Placement, Arrangement, Structure, Formatting, Alignment
@@ -153,6 +154,7 @@ These are the scripts I use most often. I tried to order them by importance, but
| | |
|----|-----|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Capture%20Note.svg"/></div>|[[#Capture Note]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20Existing%20File%20and%20Open.svg"/></div>|[[#Add Link to Existing File and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Link%20to%20New%20Page%20and%20Open.svg"/></div>|[[#Add Link to New Page and Open]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20text%20to%20link%20with%20folder%20and%20alias.svg"/></div>|[[#Convert text to link with folder and alias]]|
@@ -262,6 +264,13 @@ 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/Box%20Selected%20Elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script will add an encapsulating box around the currently selected elements in Excalidraw.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-box-elements.jpg'></td></tr></table>
## Capture Note
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Capture%20Note.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://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Capture%20Note.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">This script implements the unified "Capture Note" workflow, allowing users to select or search for note titles, automatically resolve their template and folder rules, and contextually back-embed visual frames or markdown sections.<br><a href="https://www.youtube.com/watch?v=y3sDfH30ApU" target="_blank"><img src ="https://i.ytimg.com/vi/y3sDfH30ApU/maxresdefault.jpg" style="width:560px;"></a></td></tr></table>
## Change shape of selected elements
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Change%20shape%20of%20selected%20elements.md
+2 -1
View File
@@ -330,6 +330,7 @@ function slider(contentEl, action, min, max, step, invert) {
}
let debounceColorPicker = true;
let dirty = false;
function renderSidepanel(contentEl) {
contentEl.empty();
@@ -354,7 +355,7 @@ function renderSidepanel(contentEl) {
}
const { width, height } = ea.getExcalidrawAPI().getAppState();
if(allElements.length === 0) {
contentEl.createEl("p", {
text: "Select at least one rectangle, ellipse, diamond, line, arrow, freedraw, text or SVG image element",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.23.6",
"version": "2.23.8",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.23.6",
"version": "2.23.8",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+4 -4
View File
@@ -11,7 +11,7 @@
"dependencies": {
"@popperjs/core": "^2.11.8",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.0-92",
"@zsviczian/excalidraw": "0.18.0-94",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -5173,9 +5173,9 @@
"license": "MIT"
},
"node_modules/@zsviczian/excalidraw": {
"version": "0.18.0-92",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.0-92.tgz",
"integrity": "sha512-DoC9PlM5+lr9C98guv9j6GVajyq92n05qbCxv7IfBhEmGoBvZWuv7zSf3a8SgE4guWAwVvCThdj11rzdSnhgIw==",
"version": "0.18.0-94",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.0-94.tgz",
"integrity": "sha512-FN62+BVyFJvzTG8cYrAlGRDA0J6v1aL6+g1bUJotaEuMvkWWzbEiyz8B9hNh4l4ofYS0iI9wtUgps7JxpvbEig==",
"license": "MIT",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
+1 -1
View File
@@ -32,7 +32,7 @@
"dependencies": {
"@popperjs/core": "^2.11.8",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.0-92",
"@zsviczian/excalidraw": "0.18.0-94",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
+8 -8
View File
@@ -1,6 +1,6 @@
const path = require("path");
const fs = require("fs/promises");
const { minify } = require("uglify-js");
const { minify } = require("terser");
const LZString = require("lz-string");
const CHUNK_SIZE = 256;
@@ -62,7 +62,7 @@ const mmbSource = \`
`;
const FOOTER_TAIL = `\`;
const script = ea.decompressFromBase64(mmbSource.replaceAll("\\n", "").trim())
const script = ea.decompressFromBase64(mmbSource.replace(/[\\s\\r\\n]+/g, ""));
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
await new AsyncFunction("ea", "utils", "VERSION", script)(ea, utils, VERSION);
`;
@@ -87,8 +87,8 @@ function wrapAsyncIIFE(body) {
return `(async()=>{\n${body}\n})()`;
}
function minifyCode(source) {
const result = minify(source, {
async function minifyCode(source) {
const result = await minify(source, {
compress: { passes: 3 },
mangle: true,
output: { ascii_only: true }
@@ -102,9 +102,9 @@ function minifyCode(source) {
}
function unwrapAsyncIIFE(minified) {
const match = minified.match(/^\(async\(\)=>\{([\s\S]*)\}\)\(\);?$/);
const match = minified.match(/^\(async\s*\(\)\s*=>\s*\{([\s\S]*)\}\)\(\);?$/);
if (!match) {
throw new Error("Unable to strip async IIFE wrapper from minified output");
throw new Error("Unable to strip async IIFE wrapper from minified output:\n" + minified.substring(0, 100) + "...");
}
return match[1];
}
@@ -121,7 +121,7 @@ async function generate() {
const raw = await fs.readFile(sourcePath, "utf8");
const body = stripHeader(raw).trim();
const wrapped = wrapAsyncIIFE(body);
const minified = minifyCode(wrapped);
const minified = await minifyCode(wrapped);
const unwrapped = unwrapAsyncIIFE(minified);
const compressed = compressBase64(unwrapped);
const formatted = formatCompressed(compressed);
@@ -134,4 +134,4 @@ async function generate() {
generate().catch((err) => {
console.error(err);
process.exitCode = 1;
});
});
+13 -29
View File
@@ -59,6 +59,15 @@ For a reference, follow the implementation pattern used in the "Printable Layout
// ea.createSidepanelTab("My Script", false, true);\`
- A dedicated section "sidepanelTabTypes.d.ts" in this document lists the \`ExcalidrawSidepanelTab\` function signatures.
#### **0. External Documentation & Resources**
To keep this training file concise, large external type definitions are not included. If you need to look up Obsidian APIs or Excalidraw internals, refer to the following resources:
- **Obsidian API Type Definitions:** https://github.com/obsidianmd/obsidian-api/blob/master/obsidian.d.ts
- **Obsidian Developer Docs:** https://docs.obsidian.md/Home (Community site with API and CSS documentation/examples)
- **Obsidian Developer Forum:** https://forum.obsidian.md/c/developers-api/14
- **ExcalidrawAutomate Implementation:** If the provided API documentation is unclear, consult the source directly: https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/src/shared/ExcalidrawAutomate.ts
- **Excalidraw Core Fork:** For doubts regarding core Excalidraw functionality, consult the fork used by the plugin: https://github.com/zsviczian/excalidraw
#### **1. The Core Workflow: Handling Element Immutability**
* **Central Rule:** Elements in the Excalidraw scene are immutable and should never be modified directly. Always use the ExcalidrawAutomate (EA) "workbench" pattern for modifications.
@@ -114,6 +123,8 @@ For a reference, follow the implementation pattern used in the "Printable Layout
* To temporarily hide an element, set \`element.opacity = 0\`. It's good practice to store the original opacity in \`customData\` so it can be restored. It is also recommended to lock hidden elements so they do not get accidentally selected or moved around.
* To permanently remove an element from the scene, set \`element.isDeleted = true\`.
* **Image Handling:** When dealing with image elements, use \`ea.getViewFileForImageElement(imageElement)\` to get the corresponding \`TFile\` from the Obsidian vault. This is necessary for any logic that needs to read or manipulate the source image file.
* **Break the code into helper functions:** Avoid creating large monolithic blocks of code in your scripts. Instead, break your code into smaller, reusable helper functions. This improves readability and maintainability. For example, if you have a block of code that creates a specific type of element with certain styles, consider creating a helper function like \`createStyledRect(x, y, width, height)\` that encapsulates that logic.
* **Separate out constants and language strings to the top of the file:** Avoid hard coded values and strings embedded in the code. Instead the script file should start with a set of constants and language strings. Consistently collect these at the top of the file to make it easier to find and modify them later. This also makes it easier for translators to localize the script by providing a clear section for all user-facing text.
#### **9. Text Element**
* There are three text properties.
@@ -246,9 +257,9 @@ Two files follow. First the template startup script with documenation comments,
const EXCALIDRAW_STARTUP_TEMPLATE = "src/constants/assets/startupScript.md";
const EXCALIDRAW_STARTUP_EXAMPLE = "docs/AITrainingData/ExcalidrawStartupExample.md";
const ADDITIONAL_TYPE_DEFS_FOR_AI_TRAINING = [
/*const ADDITIONAL_TYPE_DEFS_FOR_AI_TRAINING = [
"node_modules/obsidian/obsidian.d.ts",
];
];*/
const TYPE_DEF_WHITELIST = [
"lib/shared/ExcalidrawAutomate.d.ts",
@@ -366,30 +377,6 @@ function buildTypeDefMarkdown() {
return body;
}
/**
* Build additional type defs used only in AI_TRAINING_OUT (e.g. obsidian.d.ts).
*/
function buildAdditionalTypeDefsMarkdown() {
const entries = ADDITIONAL_TYPE_DEFS_FOR_AI_TRAINING.map((rel) => ({
rel,
abs: path.join(ROOT, ...rel.split('/')),
}));
let body = '```js\n';
for (const { rel, abs } of entries) {
if (!fs.existsSync(abs)) {
console.warn('[script-library] Additional type def missing:', rel);
continue;
}
let content = fs.readFileSync(abs, 'utf8');
content = stripTopImports(content);
body += makeSectionHeader(rel);
body += content.trimEnd() + '\n\n';
}
body += '```\n';
return body;
}
// NEW: Resolve module specifiers from types/excalidraw/index.d.ts to absolute .d.ts paths
function resolveExcalModulePath(spec, excalIndexAbs) {
const baseTypesRoot = path.join(ROOT, 'node_modules', '@zsviczian', 'excalidraw', 'types');
@@ -600,7 +587,6 @@ function main() {
const typeDefContent = fs.existsSync(TYPE_DEF_OUT)
? fs.readFileSync(TYPE_DEF_OUT, 'utf8')
: (TYPE_DEF_INTRO + '\n' + buildTypeDefMarkdown());
const additionalTypeDefs = buildAdditionalTypeDefsMarkdown();
const scriptLibContent = fs.existsSync(SCRIPT_LIBRARY_OUT)
? fs.readFileSync(SCRIPT_LIBRARY_OUT, 'utf8')
: '';
@@ -634,8 +620,6 @@ function main() {
'\n---\n\n' +
typeDefContent.trim() +
'\n\n---\n\n' +
additionalTypeDefs +
'\n\n---\n\n' +
excalidrawLibFunctionsSection +
'\n---\n\n' +
scriptLibContent.trim() +
+1 -1
View File
@@ -1066,7 +1066,7 @@ export const stringToSVG = (svg: string) => {
}
const className = sanitizedSvg.getAttribute("class") ?? "";
if (!/(?:^|\s)(?:lucide|skip)(?:\s|$)/.test(className)) {
if (!/(?:^|\s)(?:lucide|skip)(?:\s|-|$)/.test(className)) {
applyDefaultSvgTheme(sanitizedSvg);
}
+79 -21
View File
@@ -303,53 +303,111 @@ export const AUDIO_TYPES = [
];
export const CODE_TYPES = ["json", "css", "js"];
export const FRONTMATTER_KEYS: {
[key: string]: { name: string; type: string; depricated?: boolean };
} = {
plugin: { name: "excalidraw-plugin", type: "text" },
export const FRONTMATTER_KEYS = {
plugin: { name: "excalidraw-plugin", type: "text", depricated: false },
"export-transparent": {
name: "excalidraw-export-transparent",
type: "checkbox",
depricated: false,
},
mask: { name: "excalidraw-mask", type: "checkbox", depricated: false },
"export-dark": {
name: "excalidraw-export-dark",
type: "checkbox",
depricated: false,
},
mask: { name: "excalidraw-mask", type: "checkbox" },
"export-dark": { name: "excalidraw-export-dark", type: "checkbox" },
"export-svgpadding": {
name: "excalidraw-export-svgpadding",
type: "number",
depricated: true,
},
"export-padding": { name: "excalidraw-export-padding", type: "number" },
"export-pngscale": { name: "excalidraw-export-pngscale", type: "number" },
"export-padding": {
name: "excalidraw-export-padding",
type: "number",
depricated: false,
},
"export-pngscale": {
name: "excalidraw-export-pngscale",
type: "number",
depricated: false,
},
"export-embed-scene": {
name: "excalidraw-export-embed-scene",
type: "checkbox",
depricated: false,
},
"export-internal-links": {
name: "excalidraw-export-internal-links",
type: "checkbox",
depricated: false,
},
"link-prefix": {
name: "excalidraw-link-prefix",
type: "text",
depricated: false,
},
"url-prefix": {
name: "excalidraw-url-prefix",
type: "text",
depricated: false,
},
"link-brackets": {
name: "excalidraw-link-brackets",
type: "checkbox",
depricated: false,
},
"onload-script": {
name: "excalidraw-onload-script",
type: "text",
depricated: false,
},
"link-prefix": { name: "excalidraw-link-prefix", type: "text" },
"url-prefix": { name: "excalidraw-url-prefix", type: "text" },
"link-brackets": { name: "excalidraw-link-brackets", type: "checkbox" },
"onload-script": { name: "excalidraw-onload-script", type: "text" },
"linkbutton-opacity": {
name: "excalidraw-linkbutton-opacity",
type: "number",
depricated: false,
},
"default-mode": {
name: "excalidraw-default-mode",
type: "text",
depricated: false,
},
font: { name: "excalidraw-font", type: "text", depricated: false },
"font-color": {
name: "excalidraw-font-color",
type: "text",
depricated: false,
},
"border-color": {
name: "excalidraw-border-color",
type: "text",
depricated: false,
},
"md-css": { name: "excalidraw-css", type: "text", depricated: false },
autoexport: {
name: "excalidraw-autoexport",
type: "text",
depricated: false,
},
"default-mode": { name: "excalidraw-default-mode", type: "text" },
font: { name: "excalidraw-font", type: "text" },
"font-color": { name: "excalidraw-font-color", type: "text" },
"border-color": { name: "excalidraw-border-color", type: "text" },
"md-css": { name: "excalidraw-css", type: "text" },
autoexport: { name: "excalidraw-autoexport", type: "text" },
"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" },
"embeddable-theme": {
name: "excalidraw-embeddable-theme",
type: "text",
depricated: false,
},
"open-as-markdown": {
name: "excalidraw-open-md",
type: "checkbox",
depricated: false,
},
"embed-as-markdown": {
name: "excalidraw-embed-md",
type: "checkbox",
depricated: false,
},
};
export const CaptureUpdateAction = {
+10 -9
View File
@@ -91,11 +91,10 @@ import { FieldSuggester } from "../shared/Suggesters/FieldSuggester";
import { ReleaseNotes } from "../shared/Dialogs/ReleaseNotes";
import { DeviceType, Packages } from "../types/types";
import { RemoteDirectoryInfo } from "../types/githubTypes";
import { PreviewImageType } from "../types/utilTypes";
import { PaneTarget, PreviewImageType } from "../types/utilTypes";
import {
emulateCTRLClickForLinks,
linkClickModifierType,
PaneTarget,
} from "../utils/modifierkeyHelper";
import { imageCache } from "../shared/ImageCache";
import { StylesManager } from "./managers/StylesManager";
@@ -1040,13 +1039,15 @@ export default class ExcalidrawPlugin extends Plugin {
return;
}
const app = this.app;
Object.keys(FRONTMATTER_KEYS).forEach((key) => {
if (FRONTMATTER_KEYS[key].depricated === true) {
return;
}
const { name, type } = FRONTMATTER_KEYS[key];
app.metadataTypeManager.setType(name, type);
});
Object.keys(FRONTMATTER_KEYS).forEach(
(key: keyof typeof FRONTMATTER_KEYS) => {
if (FRONTMATTER_KEYS[key].depricated === true) {
return;
}
const { name, type } = FRONTMATTER_KEYS[key];
app.metadataTypeManager.setType(name, type);
},
);
}
public async initializeFonts() {
+1 -1
View File
@@ -77,7 +77,6 @@ import Taskbone from "../../shared/OCR/Taskbone";
import {
emulateCTRLClickForLinks,
linkClickModifierType,
PaneTarget,
} from "../../utils/modifierkeyHelper";
import { InsertPDFModal } from "../../shared/Dialogs/InsertPDFModal";
import { ExportDialog } from "../../shared/Dialogs/ExportDialog";
@@ -96,6 +95,7 @@ import { showFrameSettings } from "../../shared/Dialogs/FrameSettings";
import { insertImageToView } from "../../utils/excalidrawViewUtils";
import ExcalidrawPlugin from "src/core/main";
import { UIModeSettings } from "src/shared/Dialogs/UIModeSettings";
import { PaneTarget } from "src/types/utilTypes";
declare const PLUGIN_VERSION: string;
+1 -1
View File
@@ -38,7 +38,6 @@ import {
getListOfTemplateFiles,
getNewUniqueFilepath,
} from "src/utils/fileUtils";
import { PaneTarget } from "src/utils/modifierkeyHelper";
import {
getExcalidrawViews,
getNewOrAdjacentLeaf,
@@ -47,6 +46,7 @@ import {
} from "src/utils/obsidianUtils";
import { errorlog, getExportTheme } from "src/utils/utils";
import { imageCache } from "src/shared/ImageCache";
import { PaneTarget } from "src/types/utilTypes";
export class PluginFileManager {
private plugin: ExcalidrawPlugin;
+7 -4
View File
@@ -623,8 +623,8 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
zoomStep: 0.05,
zoomMin: 0.1,
zoomMax: 30,
linkPrefix: "📍",
urlPrefix: "🌐",
linkPrefix: "",
urlPrefix: "",
parseTODO: false,
todo: "☐",
done: "🗹",
@@ -685,7 +685,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
//fixInfinitePreviewLoop: true,
mdSVGwidth: 500,
mdSVGmaxHeight: 800,
mdFont: "Virgil",
mdFont: "Cascadia",
mdFontColor: "Black",
mdBorderColor: "Black",
mdCSS: "",
@@ -3912,9 +3912,12 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setName(t("MD_DEFAULT_FONT_NAME"))
.setDesc(fragWithHTML(t("MD_DEFAULT_FONT_DESC")))
.addDropdown(async (d: DropdownComponent) => {
//I do not know why Lilita One and Nunito do not work. The font string is there, but it is not rendered
d.addOption("Virgil", "Virgil");
d.addOption("Cascadia", "Cascadia");
d.addOption("Assistant", "Assistant");
d.addOption("Excalifont", "Excalifont");
d.addOption("Comic Shanns", "Comic Shanns");
d.addOption("Liberation Sans", "Liberation Sans");
this.app.vault
.getFiles()
.filter(
+43 -2
View File
@@ -17,6 +17,48 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
`,
"2.23.8": `
${getYouTubeDiv("y3sDfH30ApU")}
## New
- Embeddable links now support adding ontology to links, e.g. \`(ontology:: [[file#section]])\` and \`(ontology:: [Video Title](link-to-youtube-video))\`. This allows you to add custom metadata to links that will be picked up as dataview tags and rendered with tools such as ExcaliBrain.
## Fixed
- Regression from security fixes: embed markdown as image failed in some cases
- Plugin settings now includes all available fonts when setting the default font when embedding markdown as image.
## New in ExcalidrawAutomate
- \`ea.zoomToElements()\` now accepts an optional margin parameter to control the amount of whitespace around the zoomed elements. The default margin is 0.05 (5% of the view size), but you can adjust it as needed for your specific use case.
- \`ea.cloneElements()\` function to clone elements with new IDs and updated relationships, useful for duplicating or moving elements without affecting the originals.
\`\`\`ts
/**
* Zooms the target view to fit the specified elements.
* @param {boolean} selectElements - Whether to select the elements after zooming.
* @param {ExcalidrawElement[]} elements - Array of elements to zoom to.
* @param {number} [margin=0.05] - The margin around the elements when zooming.
*/
viewZoomToElements(selectElements: boolean, elements: ExcalidrawElement[], margin: number = 0.05): void;
/**
* Clones an array of Excalidraw elements or a clipboard string.
* Ensures that relationships (containers, bound elements, groups, bindings)
* are correctly remapped to the newly generated IDs.
*
* @param {ExcalidrawElement[] | string} elementsOrClipboard - The elements array or Excalidraw clipboard string.
* @returns {ExcalidrawElement[]} An array of cloned elements with new IDs and updated relationships.
*/
cloneElements(elementsOrClipboard: ExcalidrawElement[] | string): ExcalidrawElement[];
\`\`\`
## Fixed in ExcalidrawAutomate
- \`ea.addImage()\` now supports adding the markdown section of an Excalidraw file as an image.
`,
"2.23.7": `
## Fixed
- Some Excalidraw Script Icons are loaded with extra bold line weight.
- BUG: Color remapping UI for Shade Master script does not appear to work when editing the colors of a nested Excalidraw drawing. [#2779](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2779)
`,
"2.23.6": `
I apologize in advance — there will likely be a few more micro-releases over the coming weeks.
@@ -25,8 +67,7 @@ I'm addressing the Obsidian code scanner findings gradually, and every code chan
If you notice anything broken or behaving unexpectedly, please let me know. I'll do my best to investigate and fix it quickly.
## Fixed
- Links in language files
- Links in language files
`,
"2.23.5": `
${getYouTubeDiv("otIHXat8Roo")}
+7 -1
View File
@@ -839,6 +839,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "Returns a clone of the element with a new element id",
after: "",
},
{
field: "cloneElements",
code: "cloneElements(elementsOrClipboard: ExcalidrawElement[] | string): ExcalidrawElement[];",
desc: "Clones an array of Excalidraw elements or a clipboard string, ensuring that relationships (containers, bound elements, groups, bindings) are correctly remapped to the newly generated IDs.",
after: "",
},
{
field: "moveViewElementToZIndex",
code: "moveViewElementToZIndex(elementId:number, newZIndex:number): void;",
@@ -1239,7 +1245,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
},
{
field: "viewZoomToElements",
code: "viewZoomToElements(selectElements: boolean,elements: ExcalidrawElement[]):void",
code: "viewZoomToElements(selectElements: boolean,elements: ExcalidrawElement[], margin: number = 0.05):void",
desc: "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.",
after: "",
},
+17 -7
View File
@@ -188,6 +188,7 @@ export class EmbeddedFile {
public attemptCounter: number = 0;
public isHyperLink: boolean = false;
public isLocalLink: boolean = false;
public isMarkdownSection: boolean = false;
public hyperlink: DataURL;
public colorMap: ColorMap | null = null;
public pdfPageViewProps: PDFPageViewProps;
@@ -269,6 +270,14 @@ export class EmbeddedFile {
}
} else {
this.filenameparts = getEmbeddedFilenameParts(imgPath);
this.isMarkdownSection =
(this.filenameparts.hasBlockref || this.filenameparts.hasSectionref) &&
!(
this.filenameparts.hasGroupref ||
this.filenameparts.hasArearef ||
this.filenameparts.hasFrameref ||
this.filenameparts.hasClippedFrameref
);
this.filenameparts.filepath = this.file.path;
}
}
@@ -651,6 +660,8 @@ export class EmbeddedFilesLoader {
inFile instanceof EmbeddedFile ? inFile.isHyperLink : false;
const isLocalLink =
inFile instanceof EmbeddedFile ? inFile.isLocalLink : false;
const isMarkdownSection =
inFile instanceof EmbeddedFile ? inFile.isMarkdownSection : false;
const hyperlink = inFile instanceof EmbeddedFile ? inFile.hyperlink : "";
const file: TFile = inFile instanceof EmbeddedFile ? inFile.file : inFile;
if (file && markdownRendererRecursionWatcthdog.has(file)) {
@@ -676,7 +687,10 @@ export class EmbeddedFilesLoader {
let hasSVGwithBitmap = false;
const isExcalidrawFile =
!isHyperLink && !isLocalLink && this.plugin.isExcalidrawFile(file);
!isMarkdownSection &&
!isHyperLink &&
!isLocalLink &&
this.plugin.isExcalidrawFile(file);
const isPDF =
!isHyperLink && !isLocalLink && file.extension.toLowerCase() === "pdf";
@@ -1370,7 +1384,7 @@ export class EmbeddedFilesLoader {
break;
case "Assistant":
case "Helvetica":
fontDef = await getCSSFontDefinition(2);
fontDef = await getCSSFontDefinition(2); //retruns empty string
break;
case "Excalifont":
fontDef = await getCSSFontDefinition(5);
@@ -1396,10 +1410,7 @@ export class EmbeddedFilesLoader {
fontName = font.fontName;
}
if (
fileCache?.frontmatter &&
fileCache.frontmatter[FRONTMATTER_KEYS.banner.name] !== null
) {
if (fileCache?.frontmatter && fileCache.frontmatter.banner !== null) {
text = text.replace(/banner:\s*.*/, ""); //patch https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/814
}
@@ -1656,7 +1667,6 @@ export const generateIdFromFile = async (
// This function is for converting blob:app://obsidian.md image URLs (from Obsidian's image cache) to base64 data URLs.
// fetch is used here because requestUrl does not support blob: URLs, and fetch is the only browser API that can read them directly.
// The canvas fallback is less efficient and should only be used if fetch fails (e.g. in rare browser contexts).
const replaceBlobWithBase64 = async (
divElement: HTMLDivElement,
): Promise<void> => {
+111 -10
View File
@@ -112,10 +112,7 @@ import {
} from "src/shared/svgToExcalidraw/parser";
import { ROUNDNESS } from "src/constants/constants";
import { ClipboardData } from "@zsviczian/excalidraw/types/excalidraw/clipboard";
import {
emulateKeysForLinkClick,
PaneTarget,
} from "src/utils/modifierkeyHelper";
import { emulateKeysForLinkClick } from "src/utils/modifierkeyHelper";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import PolyBool from "polybooljs";
import { EmbeddableMDCustomProps } from "./Dialogs/EmbeddableSettings";
@@ -193,7 +190,7 @@ import {
PDFPageProperties,
ExportSettings,
} from "src/types/exportUtilTypes";
import { FrameRenderingOptions } from "src/types/utilTypes";
import { FrameRenderingOptions, PaneTarget } from "src/types/utilTypes";
import { CaptureUpdateAction } from "src/constants/constants";
import { AutoexportConfig } from "src/types/excalidrawViewTypes";
import { FloatingModal } from "./Dialogs/FloatingModal";
@@ -3467,10 +3464,7 @@ export class ExcalidrawAutomate {
if (!ed.loaded) {
return svgColors;
}
(img
? ed.scene.elements.filter((el: ExcalidrawElement) => el.id === img.id)
: ed.scene.elements
).forEach((el: ExcalidrawElement) => {
ed.scene.elements.forEach((el: ExcalidrawElement) => {
if ("strokeColor" in el) {
updateOrAddSVGColorInfo(svgColors, el.strokeColor, { stroke: true });
}
@@ -3755,16 +3749,18 @@ export class ExcalidrawAutomate {
* Zooms the target view to fit the specified elements.
* @param {boolean} selectElements - Whether to select the elements after zooming.
* @param {ExcalidrawElement[]} elements - Array of elements to zoom to.
* @param {number} [margin=0.05] - The margin around the elements when zooming.
*/
viewZoomToElements(
selectElements: boolean,
elements: ExcalidrawElement[],
margin: number = 0.05,
): void {
if (!this.targetView || !this.targetView?._loaded) {
errorMessage("targetView not set", "viewToggleFullScreen()");
return;
}
this.targetView.zoomToElements(selectElements, elements);
this.targetView.zoomToElements(selectElements, elements, margin);
}
/**
@@ -4549,6 +4545,111 @@ export class ExcalidrawAutomate {
return newEl;
}
/**
* Clones an array of Excalidraw elements or a clipboard string.
* Ensures that relationships (containers, bound elements, groups, bindings)
* are correctly remapped to the newly generated IDs.
*
* @param {ExcalidrawElement[] | string} elementsOrClipboard - The elements array or Excalidraw clipboard string.
* @returns {ExcalidrawElement[]} An array of cloned elements with new IDs and updated relationships.
*/
cloneElements(elementsOrClipboard: ExcalidrawElement[] | string): ExcalidrawElement[] {
let elements: ExcalidrawElement[] = [];
// 1. Parse the input
if (typeof elementsOrClipboard === "string") {
try {
const parsed = JSON.parse(elementsOrClipboard);
if (parsed.type === "excalidraw/clipboard" && Array.isArray(parsed.elements)) {
elements = parsed.elements;
} else if (Array.isArray(parsed)) {
elements = parsed;
} else {
throw new Error("Invalid clipboard string format.");
}
} catch (e) {
console.error("Failed to parse Excalidraw clipboard string:", e);
return [];
}
} else if (Array.isArray(elementsOrClipboard)) {
elements = elementsOrClipboard;
} else {
console.error("Invalid input. Expected array of elements or clipboard string.");
return [];
}
if (!elements || elements.length === 0) return [];
// 2. Create ID mappings
const idMap = new Map<string, string>();
const groupMap = new Map<string, string>();
// Pre-generate new IDs for elements and groups
elements.forEach((el) => {
idMap.set(el.id, nanoid());
if (el.groupIds && Array.isArray(el.groupIds)) {
el.groupIds.forEach((groupId: string) => {
if (!groupMap.has(groupId)) {
groupMap.set(groupId, nanoid());
}
});
}
});
// 3. Clone and remap relationships
const clonedElements: any[] = elements.map((el) => {
// Deep clone the element
const newEl = JSON.parse(JSON.stringify(el));
// Update element ID
newEl.id = idMap.get(el.id)!;
// Remap Group IDs
if (newEl.groupIds && Array.isArray(newEl.groupIds)) {
newEl.groupIds = newEl.groupIds.map((groupId: string) => groupMap.get(groupId) || groupId);
}
// Remap Container ID (e.g., text inside a rectangle)
if (newEl.containerId && idMap.has(newEl.containerId)) {
newEl.containerId = idMap.get(newEl.containerId);
}
// Remap Bound Elements (e.g., the rectangle holding the text, or arrows attached to a shape)
if (newEl.boundElements && Array.isArray(newEl.boundElements)) {
newEl.boundElements = newEl.boundElements.map((bound: { id: string, type: string }) => ({
...bound,
id: idMap.get(bound.id) || bound.id // Fallback to original ID if bound element wasn't cloned
}));
}
// Remap Arrow Start Binding
if (newEl.startBinding && idMap.has(newEl.startBinding.elementId)) {
newEl.startBinding = {
...newEl.startBinding,
elementId: idMap.get(newEl.startBinding.elementId)
};
}
// Remap Arrow End Binding
if (newEl.endBinding && idMap.has(newEl.endBinding.elementId)) {
newEl.endBinding = {
...newEl.endBinding,
elementId: idMap.get(newEl.endBinding.elementId)
};
}
// Remap Frame ID
if (newEl.frameId && idMap.has(newEl.frameId)) {
newEl.frameId = idMap.get(newEl.frameId);
}
return newEl;
});
return clonedElements;
}
/**
* Moves the specified element to a specific position in the z-index.
* * Operates directly on the Excalidraw Scene in targetView, not through ExcalidrawAutomate elements.
+7
View File
@@ -25,3 +25,10 @@ export interface FrameRenderingOptions {
outline: boolean;
clip: boolean;
}
export type PaneTarget =
| "active-pane"
| "new-pane"
| "popout-window"
| "new-tab"
| "md-properties";
+8 -4
View File
@@ -41,11 +41,15 @@ export const createLeaf = (
export const useDefaultExcalidrawFrame = (
element: NonDeletedExcalidrawElement,
) => {
const link = (element.link ?? "").replace(
/^.*?(?=\[\[|https?:\/\/|data:)/,
"",
);
return !(
element.link.startsWith("[") ||
element.link.startsWith("file:") ||
element.link.startsWith("data:")
); // && !element.link.match(TWITTER_REG);
link.startsWith("[") ||
link.startsWith("file:") ||
link.startsWith("data:")
); // && !link.match(TWITTER_REG);
};
export const leafMap = new Map<string, WorkspaceLeaf>();
+1 -6
View File
@@ -2,6 +2,7 @@ import { Modifier } from "obsidian";
import { DEVICE } from "src/constants/constants";
import { t } from "src/lang/helpers";
import { ExcalidrawSettings } from "src/core/settings";
import { PaneTarget } from "src/types/utilTypes";
export {
labelALT,
labelCTRL,
@@ -22,12 +23,6 @@ export type KeyEvent =
| React.PointerEvent
| React.MouseEvent
| ModifierKeys;
export type PaneTarget =
| "active-pane"
| "new-pane"
| "popout-window"
| "new-tab"
| "md-properties";
export type WebBrowserDragAction =
| "link"
| "image-url"
+6 -2
View File
@@ -7887,7 +7887,11 @@ export default class ExcalidrawView
return true;
}
public zoomToElements(selectResult: boolean, elements: ExcalidrawElement[]) {
public zoomToElements(
selectResult: boolean,
elements: ExcalidrawElement[],
margin: number = 0.05,
) {
const api = this.excalidrawAPI;
if (!api) {
return;
@@ -7897,7 +7901,7 @@ export default class ExcalidrawView
if (selectResult) {
api.selectElements(elements, true);
}
api.zoomToFit(elements, zoomLevel, 0.05);
api.zoomToFit(elements, zoomLevel, margin);
}
public getViewElements(): readonly ExcalidrawElement[] {