mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-12-03 06:43:35 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0f7def145d | ||
|
|
a6586803de | ||
|
|
7fe1dc5494 | ||
|
|
b092a09c3b | ||
|
|
e67ed7ff4f | ||
|
|
5ab7311e74 | ||
|
|
dd05339f73 | ||
|
|
ec23f166ab | ||
|
|
42af86ed9f | ||
|
|
8b198a5785 | ||
|
|
739b745e95 | ||
|
|
ccb5590f0c | ||
|
|
524c33a7e5 | ||
|
|
09bb5c5486 | ||
|
|
434f61653d | ||
|
|
613b86e9d0 | ||
|
|
a6cad5010e | ||
|
|
49cf799f66 | ||
|
|
662737436a | ||
|
|
887651a4bc | ||
|
|
c0a40c69a1 | ||
|
|
e69676f461 | ||
|
|
9582758483 | ||
|
|
a227c746a2 | ||
|
|
425d8304d5 | ||
|
|
1ee277c814 | ||
|
|
5a2cbadc9d | ||
|
|
f2d0c8c6b7 | ||
|
|
afecea3e67 | ||
|
|
a3b6acb0a7 | ||
|
|
a7f33f3be0 | ||
|
|
0ec5ad1bbb | ||
|
|
89f2a3beb5 | ||
|
|
88e27a35ef | ||
|
|
ea3103b650 | ||
|
|
59bbbb907d | ||
|
|
488daf0fde | ||
|
|
cf6128433d | ||
|
|
945afffc11 | ||
|
|
fe322f492e | ||
|
|
22eee5e37e | ||
|
|
5bf7271f86 | ||
|
|
1db4654fe2 | ||
|
|
3152ec2c58 | ||
|
|
1bd9a70635 | ||
|
|
4a775d81f4 | ||
|
|
a0630b4719 | ||
|
|
00acbce5f0 | ||
|
|
ea502134fd | ||
|
|
1c5daeafae |
No files matched your search
@@ -21,3 +21,6 @@ yarn.lock
|
||||
.DS_Store
|
||||
.lock
|
||||
.lock
|
||||
|
||||
# Obsidian files
|
||||
Obsidian
|
||||
@@ -676,7 +676,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
|
||||
```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><iframe width="400" height="225" src="https://www.youtube.com/embed/29EWeglRm7" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br><a href='https://youtu.be/29EWeglRm7' target='_blank'>Link to video on YouTube</a><br><br><iframe width="400" height="225" src="https://www.youtube.com/embed/DqDnzCOoYMc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br><a href='https://youtu.be/DqDnzCOoYMc' target='_blank'>Link to video on YouTube</a><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>
|
||||
<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><iframe width="400" height="225" src="https://www.youtube.com/embed/29EWeglRm7s" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br><a href='https://youtu.be/29EWeglRm7s' target='_blank'>Link to video on YouTube</a><br><iframe width="400" height="225" src="https://www.youtube.com/embed/DqDnzCOoYMc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe><br><a href='https://youtu.be/DqDnzCOoYMc' target='_blank'>Link to video on YouTube</a><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
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.15.0",
|
||||
"version": "2.15.2",
|
||||
"minAppVersion": "1.5.7",
|
||||
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.15.0",
|
||||
"version": "2.15.2",
|
||||
"minAppVersion": "1.5.7",
|
||||
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@zsviczian/excalidraw": "0.18.0-33",
|
||||
"@zsviczian/excalidraw": "0.18.0-37",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
|
||||
+1
-1
@@ -101,7 +101,7 @@ if (!isLib) {
|
||||
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/styles.production.css", "utf8")
|
||||
: fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/styles.development.css", "utf8");
|
||||
const plugin_styles = fs.readFileSync("./styles.css", "utf8");
|
||||
const styles = plugin_styles + excalidraw_styles;
|
||||
const styles = excalidraw_styles + plugin_styles;
|
||||
cssnano()
|
||||
.process(styles) // Process the CSS
|
||||
.then(result => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Copy, Crop, Globe, RotateCcw, Scan, Settings, TextSelect } from "lucide-react";
|
||||
import { Bookmark, Camera, Copy, Crop, Globe, RotateCcw, Scan, Settings, TextSelect } from "lucide-react";
|
||||
import * as React from "react";
|
||||
import { PenStyle } from "src/types/penTypes";
|
||||
|
||||
@@ -31,6 +31,8 @@ export const ICONS = {
|
||||
Copy: (<Copy /> ),
|
||||
Globe: (<Globe />),
|
||||
Crop: (<Crop />),
|
||||
Bookmark: (<Bookmark />),
|
||||
Camera: (<Camera />),
|
||||
ZoomToSelectedElement: (<Scan />),
|
||||
Properties: (<Settings />),
|
||||
ZoomToSection: (
|
||||
|
||||
@@ -234,9 +234,10 @@ export const IMAGE_TYPES = ["jpeg", "jpg", "png", "gif", "svg", "webp", "bmp", "
|
||||
export const ANIMATED_IMAGE_TYPES = ["gif", "webp", "apng", "svg"];
|
||||
export const EXPORT_TYPES = ["svg", "dark.svg", "light.svg", "png", "dark.png", "light.png"];
|
||||
export const MAX_IMAGE_SIZE = 500;
|
||||
|
||||
export const VIDEO_TYPES = ["mp4", "webm", "ogv", "mov", "mkv"];
|
||||
export const AUDIO_TYPES = ["mp3", "wav", "m4a", "3gp", "flac", "ogg", "oga", "opus"];
|
||||
export const CARD_WIDTH = 400;
|
||||
export const CARD_HEIGHT = 500;
|
||||
export const VIDEO_TYPES = ["mp4","webm","ogv","mov","mkv","avi","m4v","wmv"];
|
||||
export const AUDIO_TYPES = ["mp3","wav", "m4a", "3gp", "flac", "ogg", "oga", "opus", "aac", "aiff", "aif", "mid", "midi"];
|
||||
export const CODE_TYPES = ["json", "css", "js"];
|
||||
|
||||
export const FRONTMATTER_KEYS:{[key:string]: {name: string, type: string, depricated?:boolean}} = {
|
||||
|
||||
+37
-1
@@ -40,7 +40,7 @@ import {
|
||||
} from "../constants/constants";
|
||||
import { ExcalidrawSettings, DEFAULT_SETTINGS, ExcalidrawSettingTab } from "./settings";
|
||||
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
|
||||
import { initExcalidrawAutomate } from "src/utils/excalidrawAutomateUtils";
|
||||
import { initExcalidrawAutomate, insertLaTeXToView } from "src/utils/excalidrawAutomateUtils";
|
||||
import { around, dedupe } from "monkey-around";
|
||||
import { t } from "../lang/helpers";
|
||||
import {
|
||||
@@ -88,6 +88,8 @@ import { PackageManager } from "./managers/PackageManager";
|
||||
import ExcalidrawView from "../view/ExcalidrawView";
|
||||
import { CommandManager } from "./managers/CommandManager";
|
||||
import { EventManager } from "./managers/EventManager";
|
||||
import { UniversalInsertFileModal } from "src/shared/Dialogs/UniversalInsertFileModal";
|
||||
import en from "src/lang/locale/en";
|
||||
|
||||
declare const PLUGIN_VERSION:string;
|
||||
declare const INITIAL_TIMESTAMP: number;
|
||||
@@ -1077,6 +1079,15 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.eventManager.setDebounceActiveLeafChangeHandler();
|
||||
}
|
||||
|
||||
private getPathForFile(file: File) {
|
||||
let path = "";
|
||||
const { webUtils } = require('electron');
|
||||
if(webUtils && webUtils.getPathForFile) {
|
||||
path = webUtils.getPathForFile(file);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
public registerHotkeyOverrides() {
|
||||
//this is repeated here because the same function is called when settings is closed after hotkeys have changed
|
||||
if (this.popScope) {
|
||||
@@ -1446,4 +1457,29 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
public updateFileCache(file: TFile, frontmatter: FrontMatterCache) {
|
||||
this.fileManager.updateFileCache(file, frontmatter);
|
||||
}
|
||||
|
||||
//used by obsidianUtils in the Excalidraw Pacakge
|
||||
//aweful coding, but does the job
|
||||
public runAction(action: "anyFile" | "LaTeX" | "card") {
|
||||
if(!this.activeExcalidrawView) return;
|
||||
switch (action) {
|
||||
case "anyFile":
|
||||
this.activeExcalidrawView.setCurrentPositionToCenter();
|
||||
const insertFileModal = new UniversalInsertFileModal(this, this.activeExcalidrawView);
|
||||
insertFileModal.open();
|
||||
break;
|
||||
case "LaTeX":
|
||||
insertLaTeXToView(this.activeExcalidrawView, true);
|
||||
break;
|
||||
case "card":
|
||||
this.activeExcalidrawView.insertBackOfTheNoteCard(true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//used by obsidianUtils in the Excalidraw Pacakge
|
||||
//aweful coding, but does the job
|
||||
public getLabel(key: keyof typeof en): string {
|
||||
return t(key);
|
||||
}
|
||||
}
|
||||
@@ -781,20 +781,19 @@ export class CommandManager {
|
||||
checkCallback: (checking:boolean) => this.plugin.forceSaveActiveView(checking),
|
||||
})
|
||||
|
||||
//removing raw mode. Not required. I never use it. Raw mode can still be enabled
|
||||
//via document properties. Only showing command palette action if raw mode is enabled
|
||||
this.addCommand({
|
||||
id: "toggle-lock",
|
||||
name: t("TOGGLE_LOCK"),
|
||||
checkCallback: (checking: boolean) => {
|
||||
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
|
||||
if (checking) {
|
||||
if (
|
||||
Boolean(this.app.workspace.getActiveViewOfType(ExcalidrawView))
|
||||
) {
|
||||
return !(this.app.workspace.getActiveViewOfType(ExcalidrawView))
|
||||
.compatibilityMode;
|
||||
if (view) {
|
||||
return !view.compatibilityMode && view.textMode === TextMode.raw;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
|
||||
if (view && !view.compatibilityMode) {
|
||||
view.changeTextMode(
|
||||
view.textMode === TextMode.parsed ? TextMode.raw : TextMode.parsed,
|
||||
@@ -1281,7 +1280,7 @@ export class CommandManager {
|
||||
if(!excalidrawView.excalidrawAPI) return false;
|
||||
const embeddables = excalidrawView.getViewSelectedElements().filter(el=>el.type==="embeddable");
|
||||
const imageEls = excalidrawView.getViewSelectedElements().filter(el=>el.type==="image");
|
||||
const isPDF = (imageEls.length === 0 && embeddables.length === 1 && excalidrawView.getEmbeddableLeafElementById(embeddables[0].id)?.leaf?.view?.getViewType() === "pdf")
|
||||
const isPDF = (imageEls.length === 0 && embeddables.length === 1 && excalidrawView.getEmbeddableLeafElementById(embeddables[0].id)?.node?.child?.file?.extension === "pdf")
|
||||
const isImage = (imageEls.length === 1 && embeddables.length === 0)
|
||||
|
||||
if(!isPDF && !isImage) {
|
||||
@@ -1290,7 +1289,7 @@ export class CommandManager {
|
||||
return false;
|
||||
}
|
||||
|
||||
const page = isPDF ? getActivePDFPageNumberFromPDFView(excalidrawView.getEmbeddableLeafElementById(embeddables[0].id)?.leaf?.view) : undefined;
|
||||
const page = isPDF ? getActivePDFPageNumberFromPDFView(excalidrawView.getEmbeddableLeafElementById(embeddables[0].id)?.node?.child) : undefined;
|
||||
if(isPDF && !page) {
|
||||
return false;
|
||||
}
|
||||
@@ -1300,8 +1299,8 @@ export class CommandManager {
|
||||
if(isPDF) {
|
||||
const embeddableEl = embeddables[0] as ExcalidrawEmbeddableElement;
|
||||
const ea = new ExcalidrawAutomate(this.plugin,excalidrawView);
|
||||
const view = excalidrawView.getEmbeddableLeafElementById(embeddableEl.id)?.leaf?.view;
|
||||
const pdfFile: TFile = view && (view instanceof FileView) ? view.file : undefined;
|
||||
const view = excalidrawView.getEmbeddableLeafElementById(embeddableEl.id)?.node?.child;
|
||||
const pdfFile: TFile = view?.file;
|
||||
carveOutPDF(ea, embeddableEl, `${pdfFile?.path}#page=${page}`, pdfFile);
|
||||
return;
|
||||
}
|
||||
@@ -1707,15 +1706,19 @@ export class CommandManager {
|
||||
const PDFLink = this.plugin.getLastActivePDFPageLink(view.file);
|
||||
if(!PDFLink) return false;
|
||||
if(checking) return true;
|
||||
const ea = getEA(view);
|
||||
insertImageToView(
|
||||
ea,
|
||||
view.currentPosition,
|
||||
PDFLink,
|
||||
undefined,
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
(async()=>{
|
||||
const ea = getEA(view) as ExcalidrawAutomate;
|
||||
const id = await insertImageToView(
|
||||
ea,
|
||||
view.currentPosition,
|
||||
PDFLink,
|
||||
undefined,
|
||||
undefined,
|
||||
true,
|
||||
);
|
||||
ea.selectElementsInView([id]);
|
||||
ea.destroy()
|
||||
})();
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import ExcalidrawPlugin from "src/core/main";
|
||||
import { CustomMutationObserver } from "src/utils/debugHelper";
|
||||
import { getExcalidrawViews, isObsidianThemeDark } from "src/utils/obsidianUtils";
|
||||
import { App, Notice, TFile } from "obsidian";
|
||||
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
|
||||
export class ObserverManager {
|
||||
private plugin: ExcalidrawPlugin;
|
||||
@@ -183,17 +184,20 @@ export class ObserverManager {
|
||||
//The user clicks settings, or "open another vault", or the command palette
|
||||
const modalContainerObserverFn: MutationCallback = async (m: MutationRecord[]) => {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(modalContainerObserverFn,`ExcalidrawPlugin.modalContainerObserverFn`, m);
|
||||
const view = this.plugin.activeExcalidrawView;
|
||||
if (
|
||||
(m.length !== 1) ||
|
||||
(m[0].type !== "childList") ||
|
||||
(m[0].addedNodes.length !== 1) ||
|
||||
(!this.plugin.activeExcalidrawView) ||
|
||||
this.plugin.activeExcalidrawView?.semaphores?.viewunload ||
|
||||
(!this.plugin.activeExcalidrawView?.isDirty())
|
||||
(!view) ||
|
||||
view.semaphores?.viewunload ||
|
||||
(!view.isDirty())
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.plugin.activeExcalidrawView.save();
|
||||
|
||||
const { errorMessage } = (view.excalidrawAPI as ExcalidrawImperativeAPI).getAppState();
|
||||
if (!errorMessage) this.plugin.activeExcalidrawView.save();
|
||||
};
|
||||
|
||||
this.modalContainerObserver = DEBUGGING
|
||||
|
||||
+18
-1
@@ -98,6 +98,7 @@ export interface ExcalidrawSettings {
|
||||
penModeDoubleTapEraser: boolean;
|
||||
penModeSingleFingerPanning: boolean;
|
||||
penModeCrosshairVisible: boolean;
|
||||
panWithRightMouseButton: boolean; //mfuria #329
|
||||
renderImageInMarkdownReadingMode: boolean,
|
||||
renderImageInHoverPreviewForMDNotes: boolean,
|
||||
renderImageInMarkdownToPDF: boolean,
|
||||
@@ -286,6 +287,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
penModeDoubleTapEraser: true,
|
||||
penModeSingleFingerPanning: true,
|
||||
penModeCrosshairVisible: true,
|
||||
panWithRightMouseButton: false, //mfuria #329
|
||||
renderImageInMarkdownReadingMode: false,
|
||||
renderImageInHoverPreviewForMDNotes: false,
|
||||
renderImageInMarkdownToPDF: false,
|
||||
@@ -1363,9 +1365,24 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
|
||||
detailsEl = displayDetailsEl.createEl("details");
|
||||
detailsEl.createEl("summary", {
|
||||
text: t("ZOOM_HEAD"),
|
||||
text: t("ZOOM_AND_PAN_HEAD"), //mfuria #329
|
||||
cls: "excalidraw-setting-h3",
|
||||
});
|
||||
|
||||
//mfuria #329. Added setting for right-click panning
|
||||
new Setting(detailsEl)
|
||||
.setName(t("PAN_WITH_RIGHT_MOUSE_BUTTON_NAME"))
|
||||
.setDesc(fragWithHTML(t("PAN_WITH_RIGHT_MOUSE_BUTTON_DESC")))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(this.plugin.settings.panWithRightMouseButton)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.panWithRightMouseButton = value;
|
||||
this.applySettingsUpdate(true);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("DEFAULT_PINCHZOOM_NAME"))
|
||||
.setDesc(fragWithHTML(t("DEFAULT_PINCHZOOM_DESC")))
|
||||
|
||||
+41
-1
@@ -138,6 +138,14 @@ export default {
|
||||
"2) Then create an empty drawing in a new pane by CTRL/CMD+clicking the Excalidraw ribbon button,\n" +
|
||||
"3) and paste your work to the new document with CTRL/CMD+V.",
|
||||
ARIA_LABEL_TRAY_MODE: "Tray-mode offers an alternative, more spacious canvas",
|
||||
TRAY_TRAY_MODE: "Toggle tray-mode",
|
||||
TRAY_SCRIPT_LIBRARY: "Script Library",
|
||||
TRAY_SCRIPT_LIBRARY_ARIA: "Explore the Excalidraw Script Library",
|
||||
TRAY_EXPORT: "Export Image...",
|
||||
TRAY_EXPORT_ARIA: "Export image as PNG, SVG, or Excalidraw file",
|
||||
TRAY_SAVE: "Save",
|
||||
TRAY_SWITCH_TO_MD: "Open as Markdown",
|
||||
TRAY_SWITCH_TO_MD_ARIA: "Switch to markdown view",
|
||||
MASK_FILE_NOTICE: "This is a mask file. It is used to crop images and mask out parts of the image. Press and hold notice to open the help video.",
|
||||
INSTALL_SCRIPT_BUTTON: "Install or update Excalidraw Scripts",
|
||||
OPEN_AS_MD: "Open as Markdown",
|
||||
@@ -444,7 +452,9 @@ export default {
|
||||
"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",
|
||||
ZOOM_AND_PAN_HEAD: "Zoom and Pan",
|
||||
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "Right-click drag to pan",
|
||||
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC: "Right-click and drag to pan the canvas (Miro-style). Press 'm' to open the context menu.",
|
||||
DEFAULT_PINCHZOOM_NAME: "Allow pinch zoom in pen mode",
|
||||
DEFAULT_PINCHZOOM_DESC:
|
||||
"Pinch zoom in pen mode when using the freedraw tool is disabled by default to prevent unwanted accidental zooming with your palm.<br>" +
|
||||
@@ -1170,4 +1180,34 @@ export default {
|
||||
|
||||
//exportUtils.ts
|
||||
PDF_EXPORT_DESKTOP_ONLY: "PDF export is only available on desktop",
|
||||
|
||||
//UniversalInsertFileModal.ts
|
||||
UIFM_TITLE: "Insert File From Vault",
|
||||
UIFM_SECTION_HEAD: "Select section heading",
|
||||
UIFM_ANCHOR: "Anchor to 100% of original size",
|
||||
UIFM_ANCHOR_DESC: "This is a pro feature, use it only if you understand how it works. If enabled even if you change the size of the imported image in Excalidraw, the next time you open the drawing this image will pop back to 100% size. This is useful when embedding an atomic Excalidraw idea into another note and preserving relative sizing of text and icons.",
|
||||
UIFM_BTN_EMBEDDABLE: "as Embeddable",
|
||||
UIFM_BTN_PDF: "as Pdf",
|
||||
UIFM_BTN_IMAGE: "as Image",
|
||||
|
||||
//ReleaseNotes.ts
|
||||
RN_WELCOME: "Welcome to Excalidraw",
|
||||
|
||||
//Excalidraw component
|
||||
COMP_IMG: "Image & Files",
|
||||
COMP_IMG_FROM_SYSTEM: "Import from system",
|
||||
COMP_IMG_ANY_FILE: "ANY file from Vault",
|
||||
COMP_IMG_LaTeX: "LaTeX formula",
|
||||
COMP_FRAME: "Frame Actions",
|
||||
COMP_FRAME_HINT: "Toggle Marker Frame. Guide-only frames to define slides/print areas/image references. " +
|
||||
"Hidden in image exports; doesn't contain elements. Hide/show frames via canvas context menu.",
|
||||
|
||||
//CustomEmbeddable.tsx
|
||||
NOTICE_PDF_THEME: "PDF theme overridden.\n" +
|
||||
"Control via this file's 'excalidraw-embeddable-theme' document property (overrides plugin).\n\n" +
|
||||
"Values: dark, light, auto=Excalidraw, default=Obsidian.",
|
||||
|
||||
//EmbeddableActionsMenu.tsx
|
||||
BOOKMARK_PAGE: "Save current position in document",
|
||||
CAPTURE_PAGE: "Capture current page as image",
|
||||
};
|
||||
+50
-2
@@ -58,6 +58,10 @@ export default {
|
||||
NEW_IN_POPOUT_WINDOW_EMBED: "Crear nuevo bosquejo - EN UNA VENTANA EMERGENTE - e incrustar en el documento activo",
|
||||
TOGGLE_LOCK: "Alternar Elemento de Texto entre edición RAW y VISTA PREVIA",
|
||||
DELETE_FILE: "Eliminar imagen o archivo Markdown seleccionado de la Bóveda de Obsidian",
|
||||
MARKER_FRAME_SHOW: "Mostrar Marker Frames(marcos de marcador)",
|
||||
MARKER_FRAME_HIDE: "Ocultar Marker Frames(marcos de marcador)",
|
||||
MARKER_FRAME_TITLE_SHOW: "Mostrar títulos de Marker Frames(marcos de marcador)",
|
||||
MARKER_FRAME_TITLE_HIDE: "Ocultar títulos de Marker Frames(marcos de marcador)",
|
||||
COPY_ELEMENT_LINK: "Copiar [[enlace]] para el/los elemento(s) seleccionado(s)",
|
||||
COPY_DRAWING_LINK: "Copiar ![[enlace incrustado]] de este bosquejo",
|
||||
INSERT_LINK_TO_ELEMENT:
|
||||
@@ -134,6 +138,14 @@ export default {
|
||||
"2) Luego, crea un bosquejo vacío en un nuevo panel haciendo CTRL/CMD+clic en el botón de la barra de Excalidraw,\n" +
|
||||
"3) y pega tu trabajo en el nuevo documento con CTRL/CMD+V.",
|
||||
ARIA_LABEL_TRAY_MODE: "El modo bandeja ofrece un lienzo alternativo y más espacioso",
|
||||
TRAY_TRAY_MODE: "Activar/desactivar modo bandeja",
|
||||
TRAY_SCRIPT_LIBRARY: "Biblioteca de scripts",
|
||||
TRAY_SCRIPT_LIBRARY_ARIA: "Explorar la biblioteca de scripts de Excalidraw",
|
||||
TRAY_EXPORT: "Exportar imagen...",
|
||||
TRAY_EXPORT_ARIA: "Exportar imagen como archivo PNG, SVG o Excalidraw",
|
||||
TRAY_SAVE: "Guardar",
|
||||
TRAY_SWITCH_TO_MD: "Abrir como Markdown",
|
||||
TRAY_SWITCH_TO_MD_ARIA: "Cambiar a vista de Markdown",
|
||||
MASK_FILE_NOTICE: "Este es un archivo de máscara. Se usa para recortar y enmascarar partes de la imagen. Mantén presionado el aviso para abrir el video de ayuda.",
|
||||
INSTALL_SCRIPT_BUTTON: "Instalar o actualizar scripts de Excalidraw",
|
||||
OPEN_AS_MD: "Abrir como Markdown",
|
||||
@@ -178,7 +190,7 @@ export default {
|
||||
WELCOME_COMMAND_PALETTE: 'Escribe "Excalidraw" en la Paleta de Comandos',
|
||||
WELCOME_OBSIDIAN_MENU: "Explora el Menú de Obsidian en la esquina superior derecha",
|
||||
WELCOME_SCRIPT_LIBRARY: "Visita la Librería de Scripts",
|
||||
WELCOME_HELP_MENU: "Encuentra ayuda en el menú_de_hamburguesa",
|
||||
WELCOME_HELP_MENU: "Encuentra ayuda en el menú de la esquina superior izquierda",
|
||||
WELCOME_YOUTUBE_ARIA: "Canal de YouTube de PKM Visual",
|
||||
WELCOME_YOUTUBE_LINK: "Echa un vistazo al canal de YouTube de PKM Visual.",
|
||||
WELCOME_DISCORD_ARIA: "Únete al servidor de Discord",
|
||||
@@ -440,7 +452,9 @@ FILENAME_HEAD: "Nombre de archivo",
|
||||
"entran en conflicto con la configuración de atajos de teclado de Obsidian. Las combinaciones de atajos de teclado que agregues a continuación anularán la configuración de atajos de teclado de Obsidian mientras usas Excalidraw. Por lo tanto, " +
|
||||
`puedes agregar <code>${labelCTRL()}+G</code> si quieres que el comportamiento predeterminado sea Agrupar Objeto en Excalidraw en lugar de abrir la Vista de Gráfico.`,
|
||||
THEME_HEAD: "Tema y estilo",
|
||||
ZOOM_HEAD: "Zoom",
|
||||
ZOOM_AND_PAN_HEAD: "Zoom y panorámica",
|
||||
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "Desplazar el lienzo con el botón derecho del mouse (abrir menú con 'm')",
|
||||
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC: "Cuando está habilitado, puedes desplazar el lienzo haciendo clic derecho y arrastrando. El menú contextual se abrirá con la tecla 'm', a menos que estés editando texto.",
|
||||
DEFAULT_PINCHZOOM_NAME: "Permitir zoom con pellizco en modo lápiz",
|
||||
DEFAULT_PINCHZOOM_DESC:
|
||||
"El zoom con pellizco en modo lápiz, al usar la herramienta de dibujo a mano alzada, está deshabilitado por defecto para evitar zooms accidentales no deseados con la palma de la mano.<br>" +
|
||||
@@ -910,6 +924,10 @@ FILENAME_HEAD: "Nombre de archivo",
|
||||
SCRIPT_EXECUTION_ERROR:
|
||||
"Error de ejecución del script. Por favor, revisa la consola del desarrollador para ver el mensaje de error.",
|
||||
|
||||
//ExcalidrawViewUtils.ts
|
||||
MARKER_FRAME_RENDERING_DISABLED_NOTICE: "Hay marker-frames (marcos de marcador) ocultos en la escena.",
|
||||
//DRAWING_HAS_BACK_OF_THE_CARD: "Hay notas en el reverso de este dibujo.",
|
||||
|
||||
//ExcalidrawData.ts
|
||||
LOAD_FROM_BACKUP: "El archivo de Excalidraw estaba dañado. Cargando desde el archivo de backup(copia de seguridad).",
|
||||
FONT_LOAD_SLOW: "Cargando fuentes...\n\n Esto está tomando más tiempo de lo esperado. Si este retraso ocurre regularmente, puedes descargar las fuentes de forma local en tu Bóveda. \n\n" +
|
||||
@@ -1162,4 +1180,34 @@ FILENAME_HEAD: "Nombre de archivo",
|
||||
|
||||
//exportUtils.ts
|
||||
PDF_EXPORT_DESKTOP_ONLY: "La exportación a PDF solo está disponible en escritorio.",
|
||||
|
||||
//UniversalInsertFileModal.ts
|
||||
UIFM_TITLE: "Insertar archivo desde la bóveda",
|
||||
UIFM_SECTION_HEAD: "Seleccionar encabezado de sección",
|
||||
UIFM_ANCHOR: "Anclar al 100% del tamaño original",
|
||||
UIFM_ANCHOR_DESC: "Esta es una función Pro, úsala solo si entiendes cómo funciona. Si se activa, incluso si cambias el tamaño de la imagen importada en Excalidraw, la próxima vez que abras el dibujo, la imagen volverá al 100% de su tamaño. Esto es útil para incrustar una idea atómica de Excalidraw en otra nota y preservar el tamaño relativo del texto y los íconos.",
|
||||
UIFM_BTN_EMBEDDABLE: "como Incrustable",
|
||||
UIFM_BTN_PDF: "como Pdf",
|
||||
UIFM_BTN_IMAGE: "como Imagen",
|
||||
|
||||
//ReleaseNotes.ts
|
||||
RN_WELCOME: "Bienvenido a Excalidraw",
|
||||
|
||||
//Excalidraw component
|
||||
COMP_IMG: "Imágenes y archivos",
|
||||
COMP_IMG_FROM_SYSTEM: "Importar desde el sistema",
|
||||
COMP_IMG_ANY_FILE: "Cualquier archivo de la bóveda",
|
||||
COMP_IMG_LaTeX: "Fórmula de LaTeX",
|
||||
COMP_FRAME: "Acciones de Frame(marco)",
|
||||
COMP_FRAME_HINT: "Activar/desactivar Marker-Frame (marco de marcador). Marcos de guía para definir diapositivas/áreas de impresión/referencias de imagen. " +
|
||||
"Se ocultan en las exportaciones de imágenes y no contienen elementos. Oculta/muestra los marcos desde el menú contextual del lienzo.",
|
||||
|
||||
//CustomEmbeddable.tsx
|
||||
NOTICE_PDF_THEME: "Sobreescritura de Tema de PDF .\n" +
|
||||
"Controla esto a través de la propiedad de documento 'excalidraw-embeddable-theme' de este archivo (anula la configuración del complemento).\n\n" +
|
||||
"Valores: dark, light, auto=Excalidraw, default=Obsidian.",
|
||||
|
||||
//EmbeddableActionsMenu.tsx
|
||||
BOOKMARK_PAGE: "Guardar posición actual en el documento",
|
||||
CAPTURE_PAGE: "Capturar la página actual como imagen",
|
||||
};
|
||||
@@ -345,7 +345,9 @@ FILENAME_HEAD: "Имя файла",
|
||||
"конфликтуют с настройками горячих клавиш Obsidian. Комбинации горячих клавиш, которые вы добавите ниже, отменят настройки горячих клавиш Obsidian при использовании Excalidraw, таким образом " +
|
||||
`Вы можете добавить <code>${labelCTRL()}+G</code>, если хотите по умолчанию перейти к Группе Объектов в Excalidraw вместо открытия Режима просмотра Графиков.`,
|
||||
THEME_HEAD: "Тема и стиль",
|
||||
ZOOM_HEAD: "Масштабирование",
|
||||
ZOOM_AND_PAN_HEAD: "Масштаб и панорамирование",
|
||||
PAN_WITH_RIGHT_MOUSE_BUTTON_NAME: "Перемещение холста правой кнопкой мыши (открыть меню с 'm')",
|
||||
PAN_WITH_RIGHT_MOUSE_BUTTON_DESC: "Когда этот параметр включен, вы можете перемещать холст, нажимая правую кнопку мыши и перетаскивая. Контекстное меню откроется с помощью клавиши 'm', если только вы не редактируете текст.",
|
||||
DEFAULT_PINCHZOOM_NAME: "Разрешить масштабирование в режиме пера",
|
||||
DEFAULT_PINCHZOOM_DESC:
|
||||
"По умолчанию зуммирование в режиме пера при использовании инструмента «Свободное рисование» отключено, чтобы предотвратить нежелательное случайное масштабирование с помощью ладони.<br>" +
|
||||
|
||||
+563
-523
File diff suppressed because it is too large.
Load diff
+453
-405
File diff suppressed because it is too large.
Load diff
@@ -50,7 +50,7 @@ export class EmbeddableSettings extends Modal {
|
||||
this.zoomValue = element.scale[0];
|
||||
this.isYouTube = isYouTube(this.element.link);
|
||||
this.notExcalidrawIsInternal = this.file && !this.view.plugin.isExcalidrawFile(this.file)
|
||||
this.isMDFile = this.file && this.file.extension === "md"; // && !this.view.plugin.isExcalidrawFile(this.file);
|
||||
this.isMDFile = this.file && this.file.extension.toLowerCase() === "md"; // && !this.view.plugin.isExcalidrawFile(this.file);
|
||||
this.isLocalURI = this.element.link.startsWith("file://");
|
||||
if(isYouTube) this.youtubeStart = getYouTubeStartAt(this.element.link);
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { App, FuzzySuggestModal, TFile } from "obsidian";
|
||||
import { REG_LINKINDEX_INVALIDCHARS } from "../../constants/constants";
|
||||
import { t } from "../../lang/helpers";
|
||||
|
||||
export class InsertCommandDialog extends FuzzySuggestModal<TFile> {
|
||||
|
||||
@@ -17,6 +17,52 @@ I build this plugin in my free time, as a labor of love. Curious about the philo
|
||||
|
||||
<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.15.2":`
|
||||
## Fixed:
|
||||
- Pressing enter on a text element erroneously activated all markdown embeddables in the scene. [discord](https://discord.com/channels/1026825302900494357/1412683408424833045)
|
||||
- After updating to PDF++ 0.40.31, touch scrolling of embedded PDF documents stopped working on mobile devices, and the PDF document appeared with the wrong themes in some cases.
|
||||
- Issue with the Kanban board as an active embeddable on mobile phones is fixed.
|
||||
|
||||
## Fixed in ExcalidrawAutomate
|
||||
- \`getActiveEmbeddableViewOrEditor (view?:ExcalidrawView): {view:any}|{file:TFile, editor:Editor}|{node: ObsidianCanvasNode}|null;\` no returns the node, instead of the empty view from the leaf.
|
||||
`,
|
||||
"2.15.1":`
|
||||
## Fixed
|
||||
- PDF improvements
|
||||
- It was not possible to scroll the embedded PDF. [#9891](https://github.com/excalidraw/excalidraw/pull/9891)
|
||||
- Embedded PDF pages were blurred (pixelated).
|
||||
- Embedded PDF now accurately follows \`excalidraw-embeddable-theme\` document property.
|
||||
- auto: follows Excalidraw theme (regardless of Obsidian theme)
|
||||
- default: follows Obsidian theme (regardless of Excalidraw theme)
|
||||
- dark: always displays the PDF in dark mode (regardless of Excalidraw and Obsidian themes)
|
||||
- light: always displays the PDF in light mode (regardless of Excalidraw and Obsidian themes)
|
||||
- New embeddable-menu buttons:
|
||||
- Snapshot: inserts an image of the current active page to the scene
|
||||
- Bookmark: updates the embed link to the current page
|
||||
- Pasting an oversized image triggered an error and caused Excalidraw to discard the scene. [#2453](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2453), [#9878](https://github.com/excalidraw/excalidraw/issues/9878)
|
||||
- Video with local URI will no longer autoplay when the scene loads
|
||||
- Error creating link to element when element is a sticky note
|
||||
- Area link embeds hide the content of the objects within the area [#2461](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2461)
|
||||
- On Obsidian Mobile 1.9.10, embeddables could cause a black/white screen (no active view) until reselecting the Excalidraw page; [#2460](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2460)
|
||||
- Scrolling of embedded web pages on mobile devices is working again.
|
||||
|
||||
## New
|
||||
- Insert Any File now supports adding Audio files.
|
||||
- New option in settings under "Zoom and Pan". Pan with right mouse button (Miro-style): right-click and drag to pan the canvas. Press 'm' for the context menu (disabled while editing text). 🙏 [@mfuria](https://github.com/mfuria) for making this happen! [#2450](https://github.com/zsviczian/obsidian-excalidraw-plugin/pull/2450), [#329](https://github.com/zsviczian/excalidraw/pull/329)
|
||||
- Insert image in the main toolbar now opens a dropdown menu of options: Insert from system, insert from Vault, insert Card, and insert LaTeX. [#2448](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2448)
|
||||
|
||||
## Deprecated
|
||||
- Removed "Toggle RAW mode" from the Command Palette and the Obsidian Tools menu due to low usage. RAW mode remains available by adding \`excalidraw-plugin: raw\` to the note's YAML frontmatter/document properties.
|
||||
|
||||
## New in ExcalidrawAutomate
|
||||
\`\`\`ts
|
||||
/**
|
||||
* Returns the center position of the current view in Excalidraw coordinates.
|
||||
* @returns {{x:number, y:number}} The center position of the view.
|
||||
*/
|
||||
public getViewCenterPosition(): {x:number, y:number};
|
||||
\`\`\`
|
||||
`,
|
||||
"2.15.0":`
|
||||
<div class="excalidraw-videoWrapper"><div>
|
||||
<iframe src="https://www.youtube.com/embed/DqDnzCOoYMc" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { App, MarkdownRenderer, Modal } from "obsidian";
|
||||
import { isVersionNewerThanOther } from "src/utils/utils";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { FIRST_RUN, RELEASE_NOTES } from "./Messages";
|
||||
import { t } from "src/lang/helpers";
|
||||
|
||||
declare const PLUGIN_VERSION:string;
|
||||
|
||||
@@ -20,7 +21,7 @@ export class ReleaseNotes extends Modal {
|
||||
const { containerEl, contentEl, titleEl, headerEl } = this;
|
||||
//this.contentEl.classList.add("excalidraw-release");
|
||||
containerEl.classList.add("excalidraw-release");
|
||||
titleEl.setText(`Welcome to Excalidraw ${this.version ?? ""}`);
|
||||
titleEl.setText(`${t("RN_WELCOME")} ${this.version ?? ""}`);
|
||||
this.createForm();
|
||||
|
||||
if(headerEl) headerEl.style.pointerEvents = "none"; // Disable pointer events on header to allow clicks through
|
||||
|
||||
@@ -3,10 +3,11 @@ import { t } from "../../lang/helpers";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { getEA } from "src/core";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { MD_EX_SECTIONS } from "src/constants/constants";
|
||||
import { CARD_HEIGHT, CARD_WIDTH, MD_EX_SECTIONS } from "src/constants/constants";
|
||||
import { addBackOfTheNoteCard } from "src/utils/excalidrawViewUtils";
|
||||
|
||||
export class SelectCard extends FuzzySuggestModal<string> {
|
||||
private center: boolean = false;
|
||||
|
||||
constructor(
|
||||
public app: App,
|
||||
@@ -31,7 +32,7 @@ export class SelectCard extends FuzzySuggestModal<string> {
|
||||
this.close();
|
||||
return;
|
||||
}
|
||||
addBackOfTheNoteCard(this.view, item);
|
||||
addBackOfTheNoteCard(this.view, item, true, undefined, undefined, this.center);
|
||||
this.close();
|
||||
}
|
||||
}
|
||||
@@ -48,18 +49,28 @@ export class SelectCard extends FuzzySuggestModal<string> {
|
||||
|
||||
onChooseItem(item: string): void {
|
||||
const ea = getEA(this.view) as ExcalidrawAutomate;
|
||||
let x,y = 0;
|
||||
if(this.center) {
|
||||
const centerPos = ea.getViewCenterPosition();
|
||||
if(centerPos) {
|
||||
x = centerPos.x - (CARD_WIDTH / 2);
|
||||
y = centerPos.y - (CARD_HEIGHT / 2);
|
||||
}
|
||||
}
|
||||
|
||||
const id = ea.addEmbeddable(
|
||||
0,0,400,500,
|
||||
x,y,CARD_WIDTH,CARD_HEIGHT,
|
||||
`[[${this.view.file.path}#${item}]]`
|
||||
);
|
||||
(async () => {
|
||||
await ea.addElementsToView(true, false, true);
|
||||
await ea.addElementsToView(!this.center, false, true);
|
||||
ea.selectElementsInView([id]);
|
||||
ea.destroy();
|
||||
})();
|
||||
}
|
||||
|
||||
public start(): void {
|
||||
public start(center: boolean = false): void {
|
||||
this.center = center;
|
||||
this.emptyStateText = t("EMPTY_SECTION_MESSAGE");
|
||||
this.setPlaceholder(t("SELECT_SECTION_OR_TYPE_NEW"));
|
||||
this.open();
|
||||
|
||||
@@ -819,11 +819,11 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
},
|
||||
{
|
||||
field: "getActiveEmbeddableViewOrEditor",
|
||||
code: "getActiveEmbeddableViewOrEditor(view?: ExcalidrawView);",
|
||||
code: "getActiveEmbeddableViewOrEditor (view?:ExcalidrawView): {view:any}|{file:TFile, editor:Editor}|{node: ObsidianCanvasNode}|null;",
|
||||
desc: "Returns the editor or leaf.view of the currently active embedded obsidian file.<br>" +
|
||||
"If view is not provided, ea.targetView is used.<br>" +
|
||||
"If the embedded file is a markdown document the function will return<br>" +
|
||||
"<code>{file:TFile, editor:Editor}</code> otherwise it will return {view:any}. You can check view type with view.getViewType();",
|
||||
"If the embedded file is an eligible Obsidian canvas node document the function will return<br>" +
|
||||
"<code>{file:TFile, editor:Editor}</code> of {node: ObsidianCanvasNode}, otherwise it will return {view:any}. You can check view type with view.getViewType();",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
@@ -832,6 +832,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
desc: "@returns the last recorded pointer position on the Excalidraw canvas",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "getViewCenterPosition",
|
||||
code: "getViewCenterPosition(): {x: number, y: number};",
|
||||
desc: "@returns the center position of the current view in Excalidraw coordinates",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "getleaf",
|
||||
code: "getLeaf(origo: WorkspaceLeaf, targetPane?: PaneTarget): WorkspaceLeaf;",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ButtonComponent, DropdownComponent, TFile, ToggleComponent } from "obsidian";
|
||||
import { ButtonComponent, DropdownComponent, TFile } from "obsidian";
|
||||
import ExcalidrawView from "../../view/ExcalidrawView";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { Modal, Setting, TextComponent } from "obsidian";
|
||||
@@ -10,6 +10,7 @@ import { InsertPDFModal } from "./InsertPDFModal";
|
||||
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { cleanSectionHeading } from "src/utils/obsidianUtils";
|
||||
import { t } from "src/lang/helpers";
|
||||
|
||||
export class UniversalInsertFileModal extends Modal {
|
||||
private center: { x: number, y: number } = { x: 0, y: 0 };
|
||||
@@ -61,7 +62,7 @@ export class UniversalInsertFileModal extends Modal {
|
||||
|
||||
onOpen(): void {
|
||||
this.containerEl.classList.add("excalidraw-release");
|
||||
this.titleEl.setText(`Insert File From Vault`);
|
||||
this.titleEl.setText(t("UIFM_TITLE"));
|
||||
this.createForm();
|
||||
}
|
||||
|
||||
@@ -155,15 +156,15 @@ export class UniversalInsertFileModal extends Modal {
|
||||
});
|
||||
|
||||
sectionPickerSetting = new Setting(ce)
|
||||
.setName("Select section heading")
|
||||
.setName(t("UIFM_SECTION_HEAD"))
|
||||
.addDropdown(dropdown => {
|
||||
sectionPicker = dropdown;
|
||||
sectionPicker.selectEl.style.width = "100%";
|
||||
})
|
||||
|
||||
sizeToggleSetting = new Setting(ce)
|
||||
.setName("Anchor to 100% of original size")
|
||||
.setDesc("This is a pro feature, use it only if you understand how it works. If enabled even if you change the size of the imported image in Excalidraw, the next time you open the drawing this image will pop back to 100% size. This is useful when embedding an atomic Excalidraw idea into another note and preserving relative sizing of text and icons.")
|
||||
.setName(t("UIFM_ANCHOR"))
|
||||
.setDesc(t("UIFM_ANCHOR_DESC"))
|
||||
.addToggle(toggle => {
|
||||
toggle.setValue(anchorTo100)
|
||||
.onChange((value) => {
|
||||
@@ -174,7 +175,7 @@ export class UniversalInsertFileModal extends Modal {
|
||||
new Setting(ce)
|
||||
.addButton(button => {
|
||||
button
|
||||
.setButtonText("as Embeddable")
|
||||
.setButtonText(t("UIFM_BTN_EMBEDDABLE"))
|
||||
.onClick(async () => {
|
||||
const path = this.app.metadataCache.fileToLinktext(
|
||||
file,
|
||||
@@ -198,7 +199,7 @@ export class UniversalInsertFileModal extends Modal {
|
||||
})
|
||||
.addButton(button => {
|
||||
button
|
||||
.setButtonText("as Pdf")
|
||||
.setButtonText(t("UIFM_BTN_PDF"))
|
||||
.onClick(() => {
|
||||
const insertPDFModal = new InsertPDFModal(this.plugin, this.view);
|
||||
insertPDFModal.open(file);
|
||||
@@ -208,7 +209,7 @@ export class UniversalInsertFileModal extends Modal {
|
||||
})
|
||||
.addButton(button => {
|
||||
button
|
||||
.setButtonText("as Image")
|
||||
.setButtonText(t("UIFM_BTN_IMAGE"))
|
||||
.onClick(async () => {
|
||||
const ea:ExcalidrawAutomate = getEA(this.view);
|
||||
const isMarkdown = file && file.extension === "md" && !ea.isExcalidrawFile(file);
|
||||
|
||||
@@ -201,6 +201,10 @@ export class EmbeddedFile {
|
||||
}
|
||||
}
|
||||
|
||||
get hasSeparateDarkAndLightVersion(): boolean {
|
||||
return this.isSVGwithBitmap || (this.file && this.file.extension.toLowerCase() === "pdf");
|
||||
}
|
||||
|
||||
public resetImage(hostPath: string, imgPath: string) {
|
||||
this.imgInverted = this.img = "";
|
||||
this.mtime = 0;
|
||||
@@ -278,11 +282,12 @@ export class EmbeddedFile {
|
||||
if (this.fileChanged()) {
|
||||
this.imgInverted = this.img = "";
|
||||
}
|
||||
this.isSVGwithBitmap = isSVGwithBitmap;
|
||||
this.mtime = this.isHyperLink || this.isLocalLink ? 0 : this.file.stat.mtime;
|
||||
this.pdfPageViewProps = pdfPageViewProps;
|
||||
this.size = size;
|
||||
this.mimeType = mimeType;
|
||||
switch (isDark && isSVGwithBitmap) {
|
||||
switch (isDark && this.hasSeparateDarkAndLightVersion) {
|
||||
case true:
|
||||
this.imgInverted = imgBase64;
|
||||
break;
|
||||
@@ -290,7 +295,6 @@ export class EmbeddedFile {
|
||||
this.img = imgBase64;
|
||||
break; //bitmaps and SVGs without an embedded bitmap do not need a negative image
|
||||
}
|
||||
this.isSVGwithBitmap = isSVGwithBitmap;
|
||||
}
|
||||
|
||||
public isLoaded(isDark: boolean): boolean {
|
||||
@@ -309,7 +313,7 @@ export class EmbeddedFile {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (this.isSVGwithBitmap && isDark) {
|
||||
if (this.hasSeparateDarkAndLightVersion && isDark) {
|
||||
return this.imgInverted !== "";
|
||||
}
|
||||
return this.img !== "";
|
||||
@@ -319,7 +323,7 @@ export class EmbeddedFile {
|
||||
if (!this.file && !this.isHyperLink && !this.isLocalLink) {
|
||||
return "";
|
||||
}
|
||||
if (isDark && this.isSVGwithBitmap) {
|
||||
if (this.hasSeparateDarkAndLightVersion && isDark) {
|
||||
return this.imgInverted;
|
||||
}
|
||||
return this.img; //images that are not SVGwithBitmap, only the light string is stored, since inverted and non-inverted are ===
|
||||
@@ -675,7 +679,7 @@ export class EmbeddedFilesLoader {
|
||||
};
|
||||
files[batch].push(fileData);
|
||||
}
|
||||
} else if (embeddedFile.isSVGwithBitmap && (depth !== 0 || isThemeChange)) {
|
||||
} else if (embeddedFile.hasSeparateDarkAndLightVersion && (depth !== 0 || isThemeChange)) {
|
||||
//this will reload the image in light/dark mode when switching themes
|
||||
const fileData: FileData = {
|
||||
mimeType: embeddedFile.mimeType,
|
||||
@@ -927,6 +931,26 @@ export class EmbeddedFilesLoader {
|
||||
|
||||
const canvas = await renderPage(pageNum);
|
||||
if(canvas) {
|
||||
// NEW: invert colors for dark theme (keep alpha unchanged)
|
||||
if (this.isDark) {
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (ctx) {
|
||||
try {
|
||||
const img = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||
const data = img.data;
|
||||
for (let i = 0; i < data.length; i += 4) {
|
||||
data[i] = 255 - data[i]; // R
|
||||
data[i + 1] = 255 - data[i+1]; // G
|
||||
data[i + 2] = 255 - data[i+2]; // B
|
||||
// alpha channel (data[i+3]) remains unchanged
|
||||
}
|
||||
ctx.putImageData(img, 0, 0);
|
||||
} catch (e) {
|
||||
// If reading pixel data fails, silently fallback to non-inverted
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result: [DataURL,Size, PDFPageViewProps] = [`data:image/png;base64,${await new Promise((resolve, reject) => {
|
||||
canvas.toBlob(async (blob) => {
|
||||
const dataURL = await blobToBase64(blob);
|
||||
|
||||
@@ -89,6 +89,8 @@ import { FrameRenderingOptions } from "src/types/utilTypes";
|
||||
import { CaptureUpdateAction } from "src/constants/constants";
|
||||
import { AutoexportConfig } from "src/types/excalidrawViewTypes";
|
||||
import { FloatingModal } from "./Dialogs/FloatingModal";
|
||||
import { patchMobileView } from "src/utils/customEmbeddableUtils";
|
||||
import { ObsidianCanvasNode } from "src/view/managers/CanvasNodeFactory";
|
||||
|
||||
extendPlugins([
|
||||
HarmonyPlugin,
|
||||
@@ -475,7 +477,7 @@ export class ExcalidrawAutomate {
|
||||
* @param {ExcalidrawView} [view] - The view to check.
|
||||
* @returns {{view:any}|{file:TFile, editor:Editor}|null} The active embeddable view or editor.
|
||||
*/
|
||||
public getActiveEmbeddableViewOrEditor (view?:ExcalidrawView): {view:any}|{file:TFile, editor:Editor}|null {
|
||||
public getActiveEmbeddableViewOrEditor (view?:ExcalidrawView): {view:any}|{file:TFile, editor:Editor}|{node: ObsidianCanvasNode}|null {
|
||||
if (!this.targetView && !view) {
|
||||
return null;
|
||||
}
|
||||
@@ -485,6 +487,9 @@ export class ExcalidrawAutomate {
|
||||
if(leafOrNode.node && leafOrNode.node.isEditing) {
|
||||
return {file: leafOrNode.node.file, editor: leafOrNode.node.child.editor};
|
||||
}
|
||||
if(leafOrNode.node) {
|
||||
return {node: leafOrNode.node};
|
||||
}
|
||||
if(leafOrNode.leaf && leafOrNode.leaf.view) {
|
||||
return {view: leafOrNode.leaf.view};
|
||||
}
|
||||
@@ -555,6 +560,25 @@ export class ExcalidrawAutomate {
|
||||
return this.targetView.currentPosition;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the center position of the current view in Excalidraw coordinates.
|
||||
* @returns {{x:number, y:number}} The center position of the view.
|
||||
*/
|
||||
public getViewCenterPosition(): {x:number, y:number} {
|
||||
if (!this.targetView || !this.targetView?._loaded) {
|
||||
errorMessage("targetView not set", "getExcalidrawAPI()");
|
||||
return null;
|
||||
}
|
||||
const st = (this.getExcalidrawAPI() as ExcalidrawImperativeAPI).getAppState();
|
||||
if (!st) return null;
|
||||
|
||||
const zoom = st.zoom?.value ?? 1;
|
||||
const x = -st.scrollX + (st.width / 2) / zoom;
|
||||
const y = -st.scrollY + (st.height / 2) / zoom;
|
||||
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Excalidraw API for the current view or the view provided.
|
||||
* @param {ExcalidrawView} [view] - The view to get the API for.
|
||||
@@ -1298,6 +1322,7 @@ export class ExcalidrawAutomate {
|
||||
boundElements: [] as any,
|
||||
link,
|
||||
locked: false,
|
||||
frameId: null as string,
|
||||
...scale ? {scale} : {},
|
||||
};
|
||||
}
|
||||
@@ -1934,10 +1959,12 @@ export class ExcalidrawAutomate {
|
||||
image.size.width,
|
||||
image.size.height,
|
||||
);
|
||||
this.elementsDict[id].fileId = fileId;
|
||||
this.elementsDict[id].scale = [1, 1];
|
||||
const newEl = this.elementsDict[id] as Mutable<ExcalidrawImageElement>;
|
||||
newEl.fileId = fileId;
|
||||
newEl.scale = [1, 1];
|
||||
newEl.crop = null;
|
||||
if(!scale && anchor) {
|
||||
this.elementsDict[id].customData = {isAnchored: true}
|
||||
newEl.customData = {isAnchored: true}
|
||||
};
|
||||
return id;
|
||||
};
|
||||
@@ -2734,8 +2761,11 @@ export class ExcalidrawAutomate {
|
||||
errorMessage("targetView not set", "addElementsToView()");
|
||||
return false;
|
||||
}
|
||||
const elements = this.getElements();
|
||||
return await this.targetView.addElements({
|
||||
const elements = this.getElements();
|
||||
if(elements.some(el=>el.type === "embeddable")) {
|
||||
patchMobileView(this.targetView);
|
||||
}
|
||||
const result = await this.targetView.addElements({
|
||||
newElements: elements,
|
||||
repositionToCursor,
|
||||
save,
|
||||
@@ -2743,6 +2773,7 @@ export class ExcalidrawAutomate {
|
||||
newElementsOnTop,
|
||||
shouldRestoreElements,
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -3046,14 +3077,14 @@ export class ExcalidrawAutomate {
|
||||
* @returns The elements within the area.
|
||||
*/
|
||||
getElementsInArea(
|
||||
elements: NonDeletedExcalidrawElement[],
|
||||
{x, y, width, height}:{
|
||||
x:number; y:number; width:number; height:number;
|
||||
}
|
||||
elements: NonDeletedExcalidrawElement[],
|
||||
element: NonDeletedExcalidrawElement,
|
||||
):ExcalidrawElement[] {
|
||||
const {x, y, width, height, id} = element;
|
||||
return elements
|
||||
.filter(el => {
|
||||
if((el.type==="frame" && el.frameRole==="marker")) return false;
|
||||
if(el.id === id) return true;
|
||||
const {topX, topY, width:w, height:h} = this.getBoundingBox([el]);
|
||||
const elLeft = topX;
|
||||
const elTop = topY;
|
||||
|
||||
@@ -1,9 +1,25 @@
|
||||
import { NonDeletedExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { DEVICE, REG_LINKINDEX_INVALIDCHARS } from "src/constants/constants";
|
||||
import { getParentOfClass } from "./obsidianUtils";
|
||||
import { App, Notice, TFile, WorkspaceLeaf } from "obsidian";
|
||||
import { AUDIO_TYPES, DEVICE, REG_LINKINDEX_INVALIDCHARS, VIDEO_TYPES } from "src/constants/constants";
|
||||
import { ConstructableWorkspaceSplit, getContainerForDocument, getParentOfClass } from "./obsidianUtils";
|
||||
import { App, TFile, WorkspaceLeaf, WorkspaceSplit } from "obsidian";
|
||||
import { getLinkParts } from "./utils";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { ObsidianCanvasNode } from "src/view/managers/CanvasNodeFactory";
|
||||
|
||||
export const createLeaf = (view: ExcalidrawView): {leaf: WorkspaceLeaf, rootSplit: WorkspaceSplit} => {
|
||||
const doc = view.ownerDocument;
|
||||
const rootSplit:WorkspaceSplit = new (WorkspaceSplit as ConstructableWorkspaceSplit)(view.app.workspace, "vertical");
|
||||
rootSplit.getRoot = () => view.app.workspace[doc === document ? 'rootSplit' : 'floatingSplit'];
|
||||
rootSplit.getContainer = () => getContainerForDocument(doc);
|
||||
rootSplit.containerEl.style.width = '100%';
|
||||
rootSplit.containerEl.style.height = '100%';
|
||||
rootSplit.containerEl.style.borderRadius = "var(--embeddable-radius)";
|
||||
view.plugin.setDebounceActiveLeafChangeHandler();
|
||||
return {
|
||||
leaf: view.app.workspace.createLeafInParent(rootSplit, 0),
|
||||
rootSplit,
|
||||
};
|
||||
}
|
||||
|
||||
export const useDefaultExcalidrawFrame = (element: NonDeletedExcalidrawElement) => {
|
||||
return !(element.link.startsWith("[") || element.link.startsWith("file:") || element.link.startsWith("data:")); // && !element.link.match(TWITTER_REG);
|
||||
@@ -13,14 +29,39 @@ export const leafMap = new Map<string, WorkspaceLeaf>();
|
||||
|
||||
//This is definitely not the right solution, feels like sticking plaster
|
||||
//patch disappearing content on mobile
|
||||
export const patchMobileView = (view: ExcalidrawView) => {
|
||||
if(DEVICE.isDesktop) return;
|
||||
//based on obsidian app.js, obsidian is looking for activeEditor, but active editor is in a leaf that is disconnected from root
|
||||
export const patchMobileView = (
|
||||
view: ExcalidrawView,
|
||||
opts?: { keepAlive?: boolean; isActive?: () => boolean }
|
||||
): (() => void) | void => {
|
||||
if (!DEVICE.isPhone) return;
|
||||
console.log("patching mobile view");
|
||||
const parent = getParentOfClass(view.containerEl,"mod-top");
|
||||
if(parent) {
|
||||
if(!parent.hasClass("mod-visible")) {
|
||||
const parent = getParentOfClass(view.containerEl, "mod-top");
|
||||
if (parent) {
|
||||
if (!parent.hasClass("mod-visible")) {
|
||||
parent.addClass("mod-visible");
|
||||
}
|
||||
// create observer here
|
||||
const observer = new MutationObserver(() => {
|
||||
if (opts?.keepAlive && opts?.isActive && !opts.isActive()) {
|
||||
observer.disconnect();
|
||||
return;
|
||||
}
|
||||
if (!parent.hasClass("mod-visible")) {
|
||||
parent.addClass("mod-visible");
|
||||
}
|
||||
});
|
||||
observer.observe(parent, { attributes: true, attributeFilter: ["class"] });
|
||||
|
||||
const cleanup = () => observer.disconnect();
|
||||
|
||||
if (opts?.keepAlive) {
|
||||
// Keep the observer alive until caller cleans up (or callback signals inactive)
|
||||
return cleanup;
|
||||
}
|
||||
// default behavior: disconnect after 500ms
|
||||
window.setTimeout(cleanup, 500);
|
||||
return cleanup;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,17 +99,58 @@ export const generateEmbeddableLink = (src: string, theme: "light" | "dark"):str
|
||||
}
|
||||
|
||||
export function setFileToLocalGraph(app: App, file: TFile) {
|
||||
let lgv;
|
||||
let lgv: any;
|
||||
app.workspace.iterateAllLeaves((l) => {
|
||||
if (l.view?.getViewType() === "localgraph") lgv = l.view;
|
||||
});
|
||||
if(!lgv) return;
|
||||
try {
|
||||
//@ts-ignore
|
||||
const loadFile = lgv?.loadFile;
|
||||
if (loadFile) {
|
||||
loadFile(file);
|
||||
if (lgv.loadFile && lgv.file !== file) {
|
||||
lgv.loadFile(file);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
export function predictViewType(app: App, file: TFile): string {
|
||||
const ext = file.extension?.toLowerCase?.() ?? "";
|
||||
|
||||
// 1) Try private registry APIs when available (covers .md files with custom views like Kanban)
|
||||
const vr = (app as any)?.viewRegistry;
|
||||
const registryFileMethods = [
|
||||
"getViewTypeForFile",
|
||||
"getViewTypeByFile",
|
||||
"getTypeByFile",
|
||||
];
|
||||
for (const m of registryFileMethods) {
|
||||
if (vr?.[m]) {
|
||||
try {
|
||||
const vt = vr[m](file);
|
||||
if (typeof vt === "string" && vt) return vt;
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
// 2) Try extension mapping from registry
|
||||
const registryExtMethods = [
|
||||
"getViewTypeByExtension",
|
||||
"getTypeByExtension",
|
||||
];
|
||||
for (const m of registryExtMethods) {
|
||||
if (vr?.[m]) {
|
||||
try {
|
||||
const vt = vr[m](ext);
|
||||
if (typeof vt === "string" && vt) return vt;
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
// 3) Fallbacks by extension
|
||||
if (ext === "md") return "markdown";
|
||||
if (ext === "pdf") return "pdf";
|
||||
if (ext === "canvas") return "canvas";
|
||||
if (AUDIO_TYPES.contains(ext)) return "audio";
|
||||
if (VIDEO_TYPES.contains(ext)) return "video";
|
||||
|
||||
return "empty";
|
||||
}
|
||||
@@ -42,6 +42,7 @@ import { SVGColorInfo } from "src/types/excalidrawAutomateTypes";
|
||||
import { ExcalidrawData, getExcalidrawMarkdownHeaderSection, REGEX_LINK } from "src/shared/ExcalidrawData";
|
||||
import { getFrameBasedOnFrameNameOrId } from "./excalidrawViewUtils";
|
||||
import { ScriptEngine } from "src/shared/Scripts";
|
||||
import { getEA } from "src/core";
|
||||
|
||||
declare const PLUGIN_VERSION:string;
|
||||
|
||||
@@ -290,7 +291,7 @@ export async function getTemplate(
|
||||
if(filenameParts.hasArearef) {
|
||||
const el=scene.elements.find((el: ExcalidrawElement)=>el.id===filenameParts.blockref);
|
||||
if(el) {
|
||||
groupElements = plugin.ea.getElementsInArea(scene.elements, el).concat(el);
|
||||
groupElements = plugin.ea.getElementsInArea(scene.elements, el);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -643,9 +644,9 @@ export function repositionElementsToCursor(
|
||||
return restore({elements}, null, null).elements;
|
||||
}
|
||||
|
||||
export const insertLaTeXToView = (view: ExcalidrawView) => {
|
||||
export const insertLaTeXToView = (view: ExcalidrawView, center: boolean = false) => {
|
||||
const app = view.plugin.app;
|
||||
const ea = view.plugin.ea;
|
||||
const ea = getEA(view) as ExcalidrawAutomate;
|
||||
GenericInputPrompt.Prompt(
|
||||
view,
|
||||
view.plugin,
|
||||
@@ -656,13 +657,19 @@ export const insertLaTeXToView = (view: ExcalidrawView) => {
|
||||
undefined,
|
||||
3
|
||||
).then(async (formula: string) => {
|
||||
if (!formula) {
|
||||
return;
|
||||
if (formula) {
|
||||
const id = await ea.addLaTex(0, 0, formula);
|
||||
if(center) {
|
||||
const el = ea.getElement(id);
|
||||
let {width, height} = el;
|
||||
let {x, y} = ea.getViewCenterPosition();
|
||||
el.x = x - width / 2;
|
||||
el.y = y - height / 2;
|
||||
}
|
||||
await ea.addElementsToView(!center, false, true);
|
||||
ea.selectElementsInView([id]);
|
||||
}
|
||||
ea.reset();
|
||||
await ea.addLaTex(0, 0, formula);
|
||||
ea.setView(view);
|
||||
ea.addElementsToView(true, false, true);
|
||||
ea.destroy();
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
|
||||
import { MAX_IMAGE_SIZE, IMAGE_TYPES, ANIMATED_IMAGE_TYPES, MD_EX_SECTIONS } from "src/constants/constants";
|
||||
import { MAX_IMAGE_SIZE, IMAGE_TYPES, ANIMATED_IMAGE_TYPES, MD_EX_SECTIONS, AUDIO_TYPES, CARD_WIDTH, CARD_HEIGHT } from "src/constants/constants";
|
||||
import { App, Modal, Notice, TFile } from "obsidian";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { REGEX_LINK, REG_LINKINDEX_HYPERLINK, getExcalidrawMarkdownHeaderSection, REGEX_TAGS, getExcalidrawMarkdownHeader } from "../shared/ExcalidrawData";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { ExcalidrawElement, ExcalidrawFrameElement, ExcalidrawImageElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { getEmbeddedFilenameParts, getLinkParts, isImagePartRef } from "./utils";
|
||||
import { cleanSectionHeading } from "./obsidianUtils";
|
||||
import { cleanSectionHeading, getAudioElementHeight } from "./obsidianUtils";
|
||||
import { getEA } from "src/core";
|
||||
import { AppState, ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { EmbeddableMDCustomProps } from "src/shared/Dialogs/EmbeddableSettings";
|
||||
@@ -66,11 +66,20 @@ export async function insertEmbeddableToView (
|
||||
if(file && (IMAGE_TYPES.contains(file.extension) || ea.isExcalidrawFile(file)) && !ANIMATED_IMAGE_TYPES.contains(file.extension)) {
|
||||
return await insertImageToView(ea, position, link??file, undefined, shouldInsertToView);
|
||||
} else {
|
||||
let height = MAX_IMAGE_SIZE;
|
||||
if (
|
||||
(file && AUDIO_TYPES.contains(file.extension.toLowerCase())) ||
|
||||
(link && AUDIO_TYPES.contains(link.match(/\[\[[^\]]+?\.([^\.\]]+)]]/)?.[1]?.toLocaleLowerCase()))
|
||||
) {
|
||||
ea.style.strokeColor = "transparent";
|
||||
ea.style.backgroundColor = "transparent";
|
||||
height = getAudioElementHeight();
|
||||
}
|
||||
const id = ea.addEmbeddable(
|
||||
position.x,
|
||||
position.y,
|
||||
MAX_IMAGE_SIZE,
|
||||
MAX_IMAGE_SIZE,
|
||||
height,
|
||||
link,
|
||||
file,
|
||||
);
|
||||
@@ -224,6 +233,7 @@ export async function addBackOfTheNoteCard(
|
||||
activate: boolean = true,
|
||||
cardBody?: string,
|
||||
embeddableCustomData?: EmbeddableMDCustomProps,
|
||||
center: boolean = false,
|
||||
):Promise<string> {
|
||||
const data = view.data;
|
||||
const header = getExcalidrawMarkdownHeaderSection(data);
|
||||
@@ -253,13 +263,22 @@ export async function addBackOfTheNoteCard(
|
||||
}
|
||||
|
||||
const ea = getEA(view) as ExcalidrawAutomate;
|
||||
let x,y = 0;
|
||||
if(center) {
|
||||
const centerPos = ea.getViewCenterPosition();
|
||||
if(centerPos) {
|
||||
x = centerPos.x - (CARD_WIDTH / 2);
|
||||
y = centerPos.y - (CARD_HEIGHT / 2);
|
||||
}
|
||||
}
|
||||
|
||||
const id = ea.addEmbeddable(
|
||||
0,0,400,500,
|
||||
x,y,CARD_WIDTH,CARD_HEIGHT,
|
||||
`[[${view.file.path}#${title}]]`,
|
||||
undefined,
|
||||
embeddableCustomData
|
||||
);
|
||||
await ea.addElementsToView(true, false, true);
|
||||
await ea.addElementsToView(!center, false, true);
|
||||
|
||||
const api = view.excalidrawAPI as ExcalidrawImperativeAPI;
|
||||
const el = ea.getViewElements().find(el=>el.id === id);
|
||||
|
||||
@@ -455,4 +455,53 @@ export function isUnwantedLeaf(leaf:WorkspaceLeaf):boolean {
|
||||
leaf.view?.getViewType() === "empty" && leaf.parent && !leaf.parent.parent &&
|
||||
//@ts-ignore
|
||||
leaf.parent.type === "split" && leaf.parent.children.length === 1
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the height of an audio element in Obsidian's CSS environment
|
||||
* @returns The height of the audio element in pixels
|
||||
*/
|
||||
export function getAudioElementHeight(): number {
|
||||
// Create a temporary audio element with controls
|
||||
const audioElement = document.createElement("audio");
|
||||
audioElement.controls = true;
|
||||
audioElement.src = "data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA"; // Minimal valid audio
|
||||
|
||||
// Create a wrapper to avoid affecting page layout
|
||||
const wrapper = document.createElement("div");
|
||||
wrapper.style.position = "absolute";
|
||||
wrapper.style.left = "-9999px";
|
||||
wrapper.style.visibility = "hidden";
|
||||
wrapper.style.pointerEvents = "none";
|
||||
wrapper.appendChild(audioElement);
|
||||
|
||||
// Add to document to allow CSS to be applied
|
||||
document.body.appendChild(wrapper);
|
||||
|
||||
// Get height
|
||||
let height = 0;
|
||||
try {
|
||||
// Force layout calculation
|
||||
document.body.offsetHeight;
|
||||
|
||||
// Get height from bounding rect
|
||||
const rect = audioElement.getBoundingClientRect();
|
||||
height = rect.height;
|
||||
|
||||
// Fallback to computed style if bounding rect returns 0
|
||||
if (height === 0) {
|
||||
const computedStyle = window.getComputedStyle(audioElement);
|
||||
height = parseFloat(computedStyle.height) || 0;
|
||||
|
||||
// If still 0, try measuring the wrapper
|
||||
if (height === 0) {
|
||||
height = wrapper.getBoundingClientRect().height;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
// Clean up
|
||||
document.body.removeChild(wrapper);
|
||||
}
|
||||
|
||||
return Math.round(height);
|
||||
}
|
||||
+3
-1
@@ -625,6 +625,8 @@ export function getLinkParts (fname: string, file?: TFile): LinkParts {
|
||||
const REG = /(^[^#\|]*)#?(\^)?([^\|]*)?\|?(\d*)x?(\d*)/;
|
||||
const parts = fname.match(REG);
|
||||
const isBlockRef = parts[2] === "^";
|
||||
let page = parseInt(parts[3]?.match(/page=(\d*)/)?.[1]);
|
||||
page = isNaN(page) ? null : page;
|
||||
return {
|
||||
original: fname,
|
||||
path: file && (parts[1] === "") ? file.path : parts[1],
|
||||
@@ -634,7 +636,7 @@ export function getLinkParts (fname: string, file?: TFile): LinkParts {
|
||||
: isBlockRef ? cleanBlockRef(parts[3]) : cleanSectionHeading(parts[3]),
|
||||
width: parts[4] ? parseInt(parts[4]) : undefined,
|
||||
height: parts[5] ? parseInt(parts[5]) : undefined,
|
||||
page: parseInt(parts[3]?.match(/page=(\d*)/)?.[1])
|
||||
page,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
+24
-17
@@ -109,6 +109,7 @@ import {
|
||||
arrayToMap,
|
||||
addAppendUpdateCustomData,
|
||||
getFilePathFromObsidianURL,
|
||||
getLinkParts,
|
||||
} from "../utils/utils";
|
||||
import { cleanBlockRef, cleanSectionHeading, closeLeafView, getActivePDFPageNumberFromPDFView, getAttachmentsFolderAndFilePath, getLeaf, getParentOfClass, obsidianPDFQuoteWithRef, openLeaf, setExcalidrawView } from "../utils/obsidianUtils";
|
||||
import { splitFolderAndFilename } from "../utils/fileUtils";
|
||||
@@ -1649,11 +1650,11 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
t("RAW"),
|
||||
() => this.changeTextMode(TextMode.parsed),
|
||||
);
|
||||
this.actionButtons['isParsed'] = this.addAction(
|
||||
/*this.actionButtons['isParsed'] = this.addAction(
|
||||
TEXT_DISPLAY_PARSED_ICON_NAME,
|
||||
t("PARSED"),
|
||||
() => this.changeTextMode(TextMode.raw),
|
||||
);
|
||||
);*/
|
||||
|
||||
this.actionButtons['link'] = this.addAction("link", t("OPEN_LINK"), (ev) =>
|
||||
this.handleLinkClick(ev),
|
||||
@@ -1845,10 +1846,10 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
this.textMode = textMode;
|
||||
if (textMode === TextMode.parsed) {
|
||||
this.actionButtons['isRaw'].hide();
|
||||
this.actionButtons['isParsed'].show();
|
||||
//this.actionButtons['isParsed'].hide();
|
||||
} else {
|
||||
this.actionButtons['isRaw'].show();
|
||||
this.actionButtons['isParsed'].hide();
|
||||
//this.actionButtons['isParsed'].hide();
|
||||
}
|
||||
if (this.toolsPanelRef && this.toolsPanelRef.current) {
|
||||
this.toolsPanelRef.current.setPreviewMode(textMode === TextMode.parsed);
|
||||
@@ -4432,8 +4433,14 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
ea.selectElementsInView([await insertEmbeddableToView (ea, center, file, link)]);
|
||||
ea.destroy();
|
||||
} else {
|
||||
const modal = new UniversalInsertFileModal(this.plugin, this);
|
||||
modal.open(file, center);
|
||||
const linkParts = getLinkParts(link);
|
||||
if(linkParts.page) {
|
||||
const path = file.path + "#" + link.split("#")[1];
|
||||
ea.selectElementsInView([await insertImageToView (ea, center, path)]);
|
||||
} else {
|
||||
const modal = new UniversalInsertFileModal(this.plugin, this);
|
||||
modal.open(file, center);
|
||||
}
|
||||
}
|
||||
this.setDirty(9);
|
||||
}
|
||||
@@ -4636,12 +4643,12 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
return {imageEl: el, embeddedFile: imageFile};
|
||||
}
|
||||
|
||||
public async insertBackOfTheNoteCard() {
|
||||
public async insertBackOfTheNoteCard(center: boolean = false) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.insertBackOfTheNoteCard, "ExcalidrawView.insertBackOfTheNoteCard");
|
||||
await this.forceSave(true);
|
||||
const sections = await this.getBackOfTheNoteSections();
|
||||
const selectCardDialog = new SelectCard(this.app,this,sections);
|
||||
selectCardDialog.start();
|
||||
selectCardDialog.start(center);
|
||||
}
|
||||
|
||||
public async moveBackOfTheNoteCardToFile(id?: string) {
|
||||
@@ -5309,7 +5316,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
"aria-label": t("ARIA_LABEL_TRAY_MODE"),
|
||||
onSelect: ()=> this.toggleTrayMode(),
|
||||
},
|
||||
"Toggle tray-mode"
|
||||
t("TRAY_TRAY_MODE")
|
||||
) : null,
|
||||
React.createElement(
|
||||
MainMenu.Item,
|
||||
@@ -5318,34 +5325,34 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
"aria-label": t("FORCE_SAVE"),
|
||||
onSelect: ()=> this.forceSave(),
|
||||
},
|
||||
"Save"
|
||||
t("TRAY_SAVE")
|
||||
),
|
||||
React.createElement(
|
||||
MainMenu.Item,
|
||||
{
|
||||
icon: ICONS.scriptEngine,
|
||||
"aria-label": "Explore the Excalidraw Script Library",
|
||||
"aria-label": t("TRAY_SCRIPT_LIBRARY_ARIA"),
|
||||
onSelect: ()=> this.actionOpenScriptInstallPrompt(),
|
||||
},
|
||||
"Script Library"
|
||||
t("TRAY_SCRIPT_LIBRARY")
|
||||
),
|
||||
React.createElement(
|
||||
MainMenu.Item,
|
||||
{
|
||||
icon: ICONS.ExportImage,
|
||||
"aria-label": "Export image as PNG, SVG, or Excalidraw file",
|
||||
"aria-label": t("TRAY_EXPORT_ARIA"),
|
||||
onSelect: ()=> this.actionOpenExportImageDialog(),
|
||||
},
|
||||
"Export Image..."
|
||||
t("TRAY_EXPORT")
|
||||
),
|
||||
React.createElement(
|
||||
MainMenu.Item,
|
||||
{
|
||||
icon: ICONS.switchToMarkdown,
|
||||
"aria-label": "Switch to markdown view",
|
||||
"aria-label": t("TRAY_SWITCH_TO_MD_ARIA"),
|
||||
onSelect: ()=> this.openAsMarkdown(),
|
||||
},
|
||||
"Open as Markdown"
|
||||
t("TRAY_SWITCH_TO_MD")
|
||||
),
|
||||
React.createElement(MainMenu.Separator),
|
||||
React.createElement(MainMenu.DefaultItems.Help),
|
||||
@@ -5941,7 +5948,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
if(elements.length === 2) {
|
||||
const textEl = elements.filter(el=>el.type==="text");
|
||||
if(textEl.length===1 && (textEl[0] as ExcalidrawTextElement).containerId) {
|
||||
const container = elements.filter(el=>el.boundElements.some(be=>be.type==="text"))
|
||||
const container = elements.filter(el=>el.boundElements && el.boundElements.some(be=>be.type==="text"))
|
||||
if(container.length===1) {
|
||||
elementId = textEl[0].id;
|
||||
}
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import { NonDeletedExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ExcalidrawEmbeddableElement, } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { Notice, WorkspaceLeaf, WorkspaceSplit } from "obsidian";
|
||||
import { Notice, WorkspaceLeaf, } from "obsidian";
|
||||
import * as React from "react";
|
||||
import { ConstructableWorkspaceSplit, getContainerForDocument, isObsidianThemeDark } from "src/utils/obsidianUtils";
|
||||
import { DEVICE, EXTENDED_EVENT_TYPES, KEYBOARD_EVENT_TYPES } from "src/constants/constants";
|
||||
import { isObsidianThemeDark } from "src/utils/obsidianUtils";
|
||||
import { DEVICE, EXTENDED_EVENT_TYPES, KEYBOARD_EVENT_TYPES, } from "src/constants/constants";
|
||||
import { ExcalidrawImperativeAPI, UIAppState } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { ObsidianCanvasNode } from "src/view/managers/CanvasNodeFactory";
|
||||
import { processLinkText, patchMobileView, setFileToLocalGraph } from "src/utils/customEmbeddableUtils";
|
||||
import { processLinkText, patchMobileView, setFileToLocalGraph, createLeaf, predictViewType } from "src/utils/customEmbeddableUtils";
|
||||
import { EmbeddableMDCustomProps } from "src/shared/Dialogs/EmbeddableSettings";
|
||||
import { t } from "src/lang/helpers";
|
||||
|
||||
const CANVAS_VIEWTYPES = new Set(["markdown", "bases"]);
|
||||
const CANVAS_VIEWTYPES = new Set(["markdown", "bases", "audio", "video", "pdf"]);
|
||||
|
||||
declare module "obsidian" {
|
||||
interface Workspace {
|
||||
@@ -21,6 +22,17 @@ declare module "obsidian" {
|
||||
}
|
||||
}
|
||||
|
||||
let noticeTimer: number;
|
||||
function showNoticeOnce(message: string) {
|
||||
if (noticeTimer) {
|
||||
return
|
||||
}
|
||||
noticeTimer = window.setTimeout(() => {
|
||||
noticeTimer = undefined;
|
||||
}, 1000);
|
||||
new Notice(message,6000);
|
||||
}
|
||||
|
||||
function getTheme (view: ExcalidrawView, theme:string): string {
|
||||
return view.excalidrawData.embeddableTheme === "dark"
|
||||
? "theme-dark"
|
||||
@@ -31,6 +43,258 @@ function getTheme (view: ExcalidrawView, theme:string): string {
|
||||
: isObsidianThemeDark() ? "theme-dark" : "theme-light";
|
||||
}
|
||||
|
||||
function setPDFViewTheme(view: ExcalidrawView, pdfView: any) {
|
||||
if(!pdfView) return;
|
||||
if(view.excalidrawData.embeddableTheme === "auto") {
|
||||
pdfView.viewer?.child?.pdfViewer?.setBackground?.(null, false);
|
||||
const pdfContainerEl = pdfView.containerEl?.querySelector(".pdf-container");
|
||||
if(pdfContainerEl) {
|
||||
pdfContainerEl.classList.remove("mod-themed");
|
||||
}
|
||||
const thumbnailViewEl = pdfView.containerEl?.querySelector(".pdf-thumbnail-view");
|
||||
if(thumbnailViewEl) {
|
||||
thumbnailViewEl.style.filter = "var(--theme-filter)";
|
||||
}
|
||||
} else {
|
||||
const pdfViewerEl = pdfView.containerEl?.querySelector("div.pdfViewer");
|
||||
if(pdfViewerEl) {
|
||||
pdfViewerEl.addClass("mod-nofilter");
|
||||
}
|
||||
}
|
||||
if(["dark", "light"].includes(view.excalidrawData.embeddableTheme)) {
|
||||
const pdfContainerEl = pdfView.containerEl?.querySelector(".pdf-container");
|
||||
if(pdfContainerEl && !pdfContainerEl.classList.contains("mod-themed")) {
|
||||
pdfContainerEl.classList.add("mod-themed");
|
||||
}
|
||||
}
|
||||
if(view.excalidrawData.embeddableTheme === "light") {
|
||||
pdfView.viewer?.child?.pdfViewer?.setBackground?.(null, false);
|
||||
}
|
||||
if(view.excalidrawData.embeddableTheme === "dark") {
|
||||
pdfView.viewer?.child?.pdfViewer?.setBackground?.(
|
||||
document.body.getCssPropertyValue("--color-base-00"), true
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function setupPdfViewEnhancements(
|
||||
view: ExcalidrawView,
|
||||
leafRef: React.MutableRefObject<{ leaf: WorkspaceLeaf; node?: ObsidianCanvasNode; editNode?: Function } | null>,
|
||||
pdfObserverRef: React.MutableRefObject<MutationObserver | null> & { currentCleanup?: () => void },
|
||||
pdfObserverDisabledRef: React.MutableRefObject<boolean>
|
||||
) {
|
||||
const pdfView = leafRef.current?.node?.child;
|
||||
if (!pdfView) return;
|
||||
|
||||
const patchPDF = () => {
|
||||
// Disable observer while applying the theme to avoid loops
|
||||
pdfObserverDisabledRef.current = true;
|
||||
setPDFViewTheme(view, pdfView);
|
||||
requestAnimationFrame(() => { pdfObserverDisabledRef.current = false; });
|
||||
|
||||
// Observe inline height changes on the PDF root container and reset them
|
||||
// this could be an obsidian bug, should be revisted later 2025-08-23
|
||||
const containerEl = pdfView.containerEl as HTMLElement | null;
|
||||
let prevHeight = containerEl?.style?.height || "";
|
||||
let heightObserver: MutationObserver | null = null;
|
||||
if (containerEl) {
|
||||
heightObserver = new MutationObserver(() => {
|
||||
const h = containerEl.style.height || "";
|
||||
if (h !== prevHeight) {
|
||||
prevHeight = h;
|
||||
if (h) {
|
||||
containerEl.style.height = "";
|
||||
prevHeight = "";
|
||||
}
|
||||
}
|
||||
});
|
||||
heightObserver.observe(containerEl, { attributes: true, attributeFilter: ["style"] });
|
||||
}
|
||||
|
||||
// Transform-aware MMB drag-to-scroll (bypasses Chromium autoscroll)
|
||||
const scroller = pdfView.containerEl?.querySelector(".pdf-viewer-container") || null;
|
||||
let active = false;
|
||||
let lastX = 0, lastY = 0;
|
||||
let scaleX = 1, scaleY = 1;
|
||||
|
||||
const getScaleFromAncestor = (target: Element | null) => {
|
||||
// Read scale from the outer excalidraw embeddable container transform
|
||||
const container = target?.closest(".excalidraw__embeddable-container") as HTMLElement | null;
|
||||
if (!container) return { sx: 1, sy: 1 };
|
||||
const t = getComputedStyle(container).transform;
|
||||
// t can be "none", "matrix(a,b,c,d,tx,ty)" or "matrix3d(...)"
|
||||
if (!t || t === "none") return { sx: 1, sy: 1 };
|
||||
if (t.startsWith("matrix3d(")) {
|
||||
// matrix3d: m11=a1, m12=b1, m21=a2, m22=b2 in the first 6 entries
|
||||
const m = t.slice(9, -1).split(",").map(Number);
|
||||
const a = m[0], b = m[1], c = m[4], d = m[5];
|
||||
// scaleX = length of first column, scaleY = length of second column
|
||||
return { sx: Math.hypot(a, b) || 1, sy: Math.hypot(c, d) || 1 };
|
||||
}
|
||||
if (t.startsWith("matrix(")) {
|
||||
const m = t.slice(7, -1).split(",").map(Number); // [a,b,c,d,tx,ty]
|
||||
const a = m[0], b = m[1], c = m[2], d = m[3];
|
||||
return { sx: Math.hypot(a, b) || 1, sy: Math.hypot(c, d) || 1 };
|
||||
}
|
||||
return { sx: 1, sy: 1 };
|
||||
};
|
||||
|
||||
const onPointerDownCapture = (e: PointerEvent) => {
|
||||
if ((
|
||||
(DEVICE.isDesktop && e.button !== 1) ||
|
||||
(DEVICE.isMobile && e.button !== 0)) ||
|
||||
!scroller) return;
|
||||
// Start custom pan, cancel browser autoscroll and prevent Excalidraw from handling it.
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
active = true;
|
||||
lastX = e.clientX;
|
||||
lastY = e.clientY;
|
||||
|
||||
const { sx, sy } = getScaleFromAncestor(scroller);
|
||||
scaleX = sx;
|
||||
scaleY = sy;
|
||||
|
||||
// Listen on window so we keep panning even if we leave the element.
|
||||
window.addEventListener("pointermove", onPointerMove, { capture: true });
|
||||
window.addEventListener("pointerup", onPointerUp, { capture: true, once: true });
|
||||
window.addEventListener("pointercancel", onPointerUp, { capture: true, once: true });
|
||||
|
||||
try { (view.contentEl as HTMLElement).style.cursor = "grabbing"; } catch {}
|
||||
};
|
||||
|
||||
const onPointerMove = (e: PointerEvent) => {
|
||||
if (!active || !scroller) return;
|
||||
// Continue only while the pointer button is held:
|
||||
// - Desktop: middle mouse button (bit 3 = 4)
|
||||
// - Mobile: primary/left button (bit 0 = 1)
|
||||
if (
|
||||
(DEVICE.isDesktop && (e.buttons & 4) === 0) ||
|
||||
(DEVICE.isMobile && (e.buttons & 1) === 0)
|
||||
) return;
|
||||
|
||||
const dx = e.clientX - lastX;
|
||||
const dy = e.clientY - lastY;
|
||||
lastX = e.clientX;
|
||||
lastY = e.clientY;
|
||||
|
||||
// Convert viewport dx/dy to local CSS px by dividing on scale.
|
||||
scroller.scrollLeft -= dx / (scaleX || 1);
|
||||
scroller.scrollTop -= dy / (scaleY || 1);
|
||||
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
};
|
||||
|
||||
const onPointerUp = (_e: PointerEvent) => {
|
||||
active = false;
|
||||
try { (view.contentEl as HTMLElement).style.cursor = ""; } catch {}
|
||||
window.removeEventListener("pointermove", onPointerMove, { capture: true } as any);
|
||||
window.removeEventListener("pointerup", onPointerUp, { capture: true } as any);
|
||||
window.removeEventListener("pointercancel", onPointerUp,{ capture: true } as any);
|
||||
};
|
||||
|
||||
const root = pdfView.containerEl as HTMLElement;
|
||||
root?.addEventListener("pointerdown", onPointerDownCapture, { capture: true });
|
||||
|
||||
const cleanupPan = () => {
|
||||
root?.removeEventListener("pointerdown", onPointerDownCapture, { capture: true } as any);
|
||||
window.removeEventListener("pointermove", onPointerMove, { capture: true } as any);
|
||||
window.removeEventListener("pointerup", onPointerUp, { capture: true } as any);
|
||||
window.removeEventListener("pointercancel", onPointerUp,{ capture: true } as any);
|
||||
heightObserver?.disconnect();
|
||||
heightObserver = null;
|
||||
};
|
||||
(pdfObserverRef as any).currentCleanup = () => { cleanupPan(); };
|
||||
|
||||
if (view.excalidrawData.embeddableTheme !== "default") {
|
||||
const pdfContainerEl = pdfView.containerEl?.querySelector(".pdf-container") as HTMLElement | null;
|
||||
if (pdfContainerEl) {
|
||||
pdfObserverRef.current?.disconnect();
|
||||
pdfObserverRef.current = new MutationObserver(() => {
|
||||
if (pdfObserverDisabledRef.current) return;
|
||||
pdfObserverDisabledRef.current = true;
|
||||
try {
|
||||
setPDFViewTheme(view, pdfView);
|
||||
if(view.excalidrawData.embeddableTheme !== "default") {
|
||||
showNoticeOnce(t("NOTICE_PDF_THEME"));
|
||||
}
|
||||
} finally {
|
||||
requestAnimationFrame(() => { pdfObserverDisabledRef.current = false; });
|
||||
}
|
||||
});
|
||||
pdfObserverRef.current.observe(pdfContainerEl, {
|
||||
attributes: true,
|
||||
attributeFilter: ["class"],
|
||||
});
|
||||
|
||||
// https://github.com/RyotaUshio/obsidian-pdf-plus/issues/477
|
||||
// Watch for the PDF container being removed from DOM (e.g. by PDF+)
|
||||
const rootEl = pdfView.containerEl as HTMLElement | null;
|
||||
if (rootEl) {
|
||||
let detachObserver: MutationObserver | null = new MutationObserver((_muts, obs) => {
|
||||
// If the tracked pdfContainerEl is gone/replaced, clean up and reattach
|
||||
if (!pdfContainerEl.isConnected || !rootEl.contains(pdfContainerEl)) {
|
||||
obs.disconnect();
|
||||
detachObserver = null;
|
||||
|
||||
// Cleanup existing handlers/observers
|
||||
try { (pdfObserverRef as any).currentCleanup?.(); } catch {}
|
||||
try { pdfObserverRef.current?.disconnect(); } catch {}
|
||||
|
||||
// Re-setup on next tick to allow DOM to settle
|
||||
setTimeout(() => {
|
||||
if (leafRef.current?.node?.child?.containerEl?.isConnected) {
|
||||
setupPdfViewEnhancements(
|
||||
view,
|
||||
leafRef as React.MutableRefObject<{ leaf: WorkspaceLeaf; node?: ObsidianCanvasNode; editNode?: Function } | null>,
|
||||
pdfObserverRef as any,
|
||||
pdfObserverDisabledRef
|
||||
);
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
});
|
||||
detachObserver.observe(rootEl, { childList: true, subtree: true });
|
||||
|
||||
// Extend cleanup to also stop the detachObserver and the class observer
|
||||
const prevCleanup = (pdfObserverRef as any).currentCleanup;
|
||||
(pdfObserverRef as any).currentCleanup = () => {
|
||||
try { prevCleanup?.(); } catch {}
|
||||
try { pdfObserverRef.current?.disconnect(); } catch {}
|
||||
try { detachObserver?.disconnect(); } catch {}
|
||||
detachObserver = null;
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const root = leafRef?.current?.node?.child?.containerEl;
|
||||
if (root) {
|
||||
const selector = ".pdf-viewer-container";
|
||||
const existing = root.querySelector(selector);
|
||||
if (existing) {
|
||||
patchPDF();
|
||||
} else {
|
||||
let timeoutId:number = null as any;
|
||||
const mo = new MutationObserver((_, obs) => {
|
||||
const el = root.querySelector(selector);
|
||||
if (el) {
|
||||
patchPDF();
|
||||
obs.disconnect();
|
||||
if (timeoutId) clearTimeout(timeoutId);
|
||||
}
|
||||
});
|
||||
mo.observe(root as HTMLElement, { childList: true, subtree: true });
|
||||
timeoutId = window.setTimeout(() => {
|
||||
mo.disconnect();
|
||||
}, 10000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------------
|
||||
//Render webview for anything other than Vimeo and Youtube
|
||||
//Vimeo and Youtube are rendered by Excalidraw because of the window messaging
|
||||
@@ -46,6 +310,7 @@ export function renderWebView (src: string, view: ExcalidrawView, id: string, _:
|
||||
title="Excalidraw Embedded Content"
|
||||
allowFullScreen={true}
|
||||
src={src}
|
||||
webpreferences="autoplayPolicy=document-user-activation-required"
|
||||
style={{
|
||||
overflow: "hidden",
|
||||
borderRadius: "var(--embeddable-radius)",
|
||||
@@ -59,7 +324,7 @@ export function renderWebView (src: string, view: ExcalidrawView, id: string, _:
|
||||
className="excalidraw__embeddable"
|
||||
title="Excalidraw Embedded Content"
|
||||
allowFullScreen={true}
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
src={isDataURL ? null : src}
|
||||
style={{
|
||||
overflow: "hidden",
|
||||
@@ -74,15 +339,16 @@ export function renderWebView (src: string, view: ExcalidrawView, id: string, _:
|
||||
//Render WorkspaceLeaf or CanvasNode
|
||||
//--------------------------------------------------------------------------------
|
||||
function RenderObsidianView(
|
||||
{ mdProps, element, linkText, view, containerRef, activeEmbeddable, theme, canvasColor }:{
|
||||
{ mdProps, element, linkText, view, containerRef, activeEmbeddable, theme, canvasColor, selectedElementId }:{
|
||||
mdProps: EmbeddableMDCustomProps;
|
||||
element: NonDeletedExcalidrawElement;
|
||||
element: ExcalidrawEmbeddableElement;
|
||||
linkText: string;
|
||||
view: ExcalidrawView;
|
||||
containerRef: React.RefObject<HTMLDivElement>;
|
||||
activeEmbeddable: {element: NonDeletedExcalidrawElement; state: string};
|
||||
activeEmbeddable: {element: ExcalidrawEmbeddableElement; state: string};
|
||||
theme: string;
|
||||
canvasColor: string;
|
||||
selectedElementId: string;
|
||||
}): JSX.Element {
|
||||
|
||||
const { subpath, file } = processLinkText(linkText, view);
|
||||
@@ -96,8 +362,13 @@ function RenderObsidianView(
|
||||
const leafRef = React.useRef<{leaf: WorkspaceLeaf; node?: ObsidianCanvasNode, editNode?: Function} | null>(null);
|
||||
const isEditingRef = React.useRef(false);
|
||||
const isActiveRef = React.useRef(false);
|
||||
const viewTypeRef = React.useRef("empty");
|
||||
const themeRef = React.useRef(theme);
|
||||
const elementRef = React.useRef(element);
|
||||
const pdfObserverRef = React.useRef(null);
|
||||
const pdfObserverDisabledRef = React.useRef(false);
|
||||
// Keep-alive mobile patch cleanup holder
|
||||
const mobilePatchCleanupRef = React.useRef(null);
|
||||
|
||||
// Update themeRef when theme changes
|
||||
React.useEffect(() => {
|
||||
@@ -110,7 +381,7 @@ function RenderObsidianView(
|
||||
}, [element]);
|
||||
|
||||
//--------------------------------------------------------------------------------
|
||||
//block propagation of events to the parent if the iframe element is active
|
||||
//block propagation of events to the parent if the embeddable element is active
|
||||
//--------------------------------------------------------------------------------
|
||||
const stopPropagation = React.useCallback((event:React.PointerEvent<HTMLElement>) => {
|
||||
if(isActiveRef.current) {
|
||||
@@ -137,7 +408,7 @@ function RenderObsidianView(
|
||||
}; //cleanup on unmount
|
||||
}, []);
|
||||
|
||||
//blocking or not the propagation of events to the parent if the iframe is active
|
||||
//blocking or not the propagation of events to the parent if the embeddable element is active
|
||||
React.useEffect(() => {
|
||||
EXTENDED_EVENT_TYPES.forEach((type) => containerRef.current.removeEventListener(type, stopPropagation));
|
||||
if(!containerRef?.current) {
|
||||
@@ -166,6 +437,21 @@ function RenderObsidianView(
|
||||
}
|
||||
}, [isActiveRef.current]);
|
||||
|
||||
const setKeepOnTop = () => {
|
||||
const keepontop = (view.app.workspace.activeLeaf === view.leaf) && DEVICE.isDesktop;
|
||||
if (keepontop) {
|
||||
//@ts-ignore
|
||||
if(!view.ownerWindow.electronWindow.isAlwaysOnTop()) {
|
||||
//@ts-ignore
|
||||
view.ownerWindow.electronWindow.setAlwaysOnTop(true);
|
||||
setTimeout(() => {
|
||||
//@ts-ignore
|
||||
view.ownerWindow.electronWindow.setAlwaysOnTop(false);
|
||||
}, 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------------
|
||||
//Mount the workspace leaf or the canvas node depending on subpath
|
||||
//--------------------------------------------------------------------------------
|
||||
@@ -180,71 +466,80 @@ function RenderObsidianView(
|
||||
|
||||
containerRef.current.parentElement.style.padding = "";
|
||||
|
||||
const doc = view.ownerDocument;
|
||||
const rootSplit:WorkspaceSplit = new (WorkspaceSplit as ConstructableWorkspaceSplit)(view.app.workspace, "vertical");
|
||||
rootSplit.getRoot = () => view.app.workspace[doc === document ? 'rootSplit' : 'floatingSplit'];
|
||||
rootSplit.getContainer = () => getContainerForDocument(doc);
|
||||
rootSplit.containerEl.style.width = '100%';
|
||||
rootSplit.containerEl.style.height = '100%';
|
||||
rootSplit.containerEl.style.borderRadius = "var(--embeddable-radius)";
|
||||
view.plugin.setDebounceActiveLeafChangeHandler();
|
||||
leafRef.current = {
|
||||
leaf: view.app.workspace.createLeafInParent(rootSplit, 0),
|
||||
leaf: null,
|
||||
node: null,
|
||||
editNode: null,
|
||||
};
|
||||
|
||||
const setKeepOnTop = () => {
|
||||
const keepontop = (view.app.workspace.activeLeaf === view.leaf) && DEVICE.isDesktop;
|
||||
if (keepontop) {
|
||||
//@ts-ignore
|
||||
if(!view.ownerWindow.electronWindow.isAlwaysOnTop()) {
|
||||
//@ts-ignore
|
||||
view.ownerWindow.electronWindow.setAlwaysOnTop(true);
|
||||
setTimeout(() => {
|
||||
//@ts-ignore
|
||||
view.ownerWindow.electronWindow.setAlwaysOnTop(false);
|
||||
}, 500);
|
||||
const createNode = (viewType: string) => {
|
||||
setKeepOnTop();
|
||||
leafRef.current.node = view.canvasNodeFactory.createFileNote(file, subpath, containerRef.current, element.id);
|
||||
setColors(containerRef.current, element, mdProps, canvasColor, viewType);
|
||||
view.updateEmbeddableLeafRef(element.id, leafRef.current);
|
||||
viewTypeRef.current = "markdown";
|
||||
}
|
||||
|
||||
patchMobileView(view);
|
||||
//if subpath is defined, create a canvas node else create a workspace leaf
|
||||
if(subpath && view.canvasNodeFactory.isInitialized() && file.extension.toLowerCase() === "md") {
|
||||
createNode("markdown");
|
||||
} else {
|
||||
let viewType = predictViewType(view.app,file);
|
||||
// markdown could still be a kanban board or other custom view on top of markdown, those need to be displayed in leaves
|
||||
if(viewType !== "markdown" && CANVAS_VIEWTYPES.has(viewType) && view.canvasNodeFactory.isInitialized()) {
|
||||
createNode(viewType);
|
||||
if(viewType === "pdf") {
|
||||
// Moved PDF setup logic into a helper for readability
|
||||
setupPdfViewEnhancements(
|
||||
view,
|
||||
leafRef as React.MutableRefObject<{ leaf: WorkspaceLeaf; node?: ObsidianCanvasNode; editNode?: Function } | null>,
|
||||
pdfObserverRef as unknown as React.MutableRefObject<MutationObserver | null> & { currentCleanup?: () => void },
|
||||
pdfObserverDisabledRef
|
||||
);
|
||||
}
|
||||
} else {
|
||||
(async () => {
|
||||
const {rootSplit, leaf } = createLeaf(view);
|
||||
leafRef.current.leaf = leaf;
|
||||
await leafRef.current.leaf.openFile(file, {
|
||||
active: false,
|
||||
state: {mode:"preview"},
|
||||
...subpath ? { eState: { subpath }}:{},
|
||||
});
|
||||
const viewType = leafRef.current.leaf.view?.getViewType();
|
||||
viewTypeRef.current = viewType;
|
||||
if(viewType === "canvas") {
|
||||
leafRef.current.leaf.view.canvas?.setReadonly(true);
|
||||
}
|
||||
if (viewType === "markdown" && view.canvasNodeFactory.isInitialized()) {
|
||||
createNode("markdown");
|
||||
//I haven't found a better way of deciding if an .md file has its own view (e.g., kanban) or not
|
||||
//This runs only when the file is added, thus should not be a major performance issue
|
||||
await leafRef.current.leaf.setViewState({state: {file:null}})
|
||||
leafRef.current.leaf?.detach();
|
||||
} else {
|
||||
const workspaceLeaf:HTMLDivElement = rootSplit.containerEl.querySelector("div.workspace-leaf");
|
||||
if(workspaceLeaf) workspaceLeaf.style.borderRadius = "var(--embeddable-radius)";
|
||||
rootSplit.containerEl.addClass("mod-visible");
|
||||
containerRef.current.appendChild(rootSplit.containerEl);
|
||||
setColors(containerRef.current, element, mdProps, canvasColor, viewType);
|
||||
view.updateEmbeddableLeafRef(element.id, leafRef.current);
|
||||
}
|
||||
})();
|
||||
}
|
||||
}
|
||||
|
||||
//if subpath is defined, create a canvas node else create a workspace leaf
|
||||
if(subpath && view.canvasNodeFactory.isInitialized()) {
|
||||
setKeepOnTop();
|
||||
leafRef.current.node = view.canvasNodeFactory.createFileNote(file, subpath, containerRef.current, element.id);
|
||||
view.updateEmbeddableLeafRef(element.id, leafRef.current);
|
||||
} else {
|
||||
(async () => {
|
||||
await leafRef.current.leaf.openFile(file, {
|
||||
active: false,
|
||||
state: {mode:"preview"},
|
||||
...subpath ? { eState: { subpath }}:{},
|
||||
});
|
||||
const viewType = leafRef.current.leaf.view?.getViewType();
|
||||
if(viewType === "canvas") {
|
||||
leafRef.current.leaf.view.canvas?.setReadonly(true);
|
||||
}
|
||||
if (CANVAS_VIEWTYPES.has(viewType) && view.canvasNodeFactory.isInitialized()) {
|
||||
setKeepOnTop();
|
||||
//I haven't found a better way of deciding if an .md file has its own view (e.g., kanban) or not
|
||||
//This runs only when the file is added, thus should not be a major performance issue
|
||||
await leafRef.current.leaf.setViewState({state: {file:null}})
|
||||
leafRef.current.node = view.canvasNodeFactory.createFileNote(file, subpath, containerRef.current, element.id);
|
||||
setColors(containerRef.current, element, mdProps, canvasColor);
|
||||
} else {
|
||||
const workspaceLeaf:HTMLDivElement = rootSplit.containerEl.querySelector("div.workspace-leaf");
|
||||
if(workspaceLeaf) workspaceLeaf.style.borderRadius = "var(--embeddable-radius)";
|
||||
rootSplit.containerEl.addClass("mod-visible");
|
||||
containerRef.current.appendChild(rootSplit.containerEl);
|
||||
setColors(containerRef.current, element, mdProps, canvasColor);
|
||||
}
|
||||
patchMobileView(view);
|
||||
view.updateEmbeddableLeafRef(element.id, leafRef.current);
|
||||
})();
|
||||
}
|
||||
|
||||
return () => {
|
||||
// disconnect observer if any
|
||||
(pdfObserverRef as any).currentCleanup?.();
|
||||
pdfObserverRef.current?.disconnect();
|
||||
pdfObserverRef.current = null;
|
||||
|
||||
// cleanup persistent mobile patch if active
|
||||
try { mobilePatchCleanupRef.current?.(); } catch {}
|
||||
mobilePatchCleanupRef.current = null;
|
||||
|
||||
if(!leafRef.current) {
|
||||
return;
|
||||
}
|
||||
@@ -257,7 +552,7 @@ function RenderObsidianView(
|
||||
//--------------------------------------------------------------------------------
|
||||
//Set colors of the canvas node
|
||||
//--------------------------------------------------------------------------------
|
||||
function setColors (canvasNode: HTMLDivElement, element: NonDeletedExcalidrawElement, mdProps: EmbeddableMDCustomProps, canvasColor: string) {
|
||||
function setColors (canvasNode: HTMLDivElement, element: ExcalidrawEmbeddableElement, mdProps: EmbeddableMDCustomProps, canvasColor: string, viewType: string) {
|
||||
if(!mdProps) return;
|
||||
if (!leafRef.current?.hasOwnProperty("node")) return;
|
||||
|
||||
@@ -297,22 +592,31 @@ function RenderObsidianView(
|
||||
canvasNode?.style.setProperty("--background-primary", color);
|
||||
canvasNodeContainer?.style.setProperty("background-color", color);
|
||||
}
|
||||
canvasNode?.style.setProperty("--bases-cards-container-background","var(--background-primary)");
|
||||
canvasNode?.style.setProperty("--bases-embed-border-color","var(--background-modifier-border)");
|
||||
canvasNode?.style.setProperty("--bases-table-header-color","var(--text-muted)");
|
||||
canvasNode?.style.setProperty("--bases-table-header-background","var(--background-primary)");
|
||||
canvasNode?.style.setProperty("--bases-table-header-background-hover","var(--background-modifier-hover)");
|
||||
canvasNode?.style.setProperty("--bases-table-header-sort-mask","linear-gradient(to left, transparent var(--size-4-6), black var(--size-4-6))");
|
||||
canvasNode?.style.setProperty("--bases-table-border-color","var(--table-border-color)");
|
||||
canvasNode?.style.setProperty("--bases-table-row-background-hover","var(--table-row-background-hover)");
|
||||
canvasNode?.style.setProperty("--bases-table-cell-shadow-active","0 0 0 2px var(--interactive-accent)");
|
||||
canvasNode?.style.setProperty("--bases-table-cell-background-active","var(--background-primary)");
|
||||
canvasNode?.style.setProperty("--bases-table-cell-background-disabled","var(--background-primary-alt)");
|
||||
canvasNode?.style.setProperty("--bases-cards-container-background","var(--background-primary)");
|
||||
canvasNode?.style.setProperty("--bases-cards-background","var(--background-primary)");
|
||||
canvasNode?.style.setProperty("--bases-cards-cover-background","var(--background-primary-alt)");
|
||||
canvasNode?.style.setProperty("--bases-cards-shadow","0 0 0 1px var(--background-modifier-border)");
|
||||
canvasNode?.style.setProperty("--bases-cards-shadow-hover","0 0 0 1px var(--background-modifier-border-hover)");
|
||||
switch (viewType) {
|
||||
case "bases":
|
||||
canvasNode?.style.setProperty("--bases-cards-container-background","var(--background-primary)");
|
||||
canvasNode?.style.setProperty("--bases-embed-border-color","var(--background-modifier-border)");
|
||||
canvasNode?.style.setProperty("--bases-table-header-color","var(--text-muted)");
|
||||
canvasNode?.style.setProperty("--bases-table-header-background","var(--background-primary)");
|
||||
canvasNode?.style.setProperty("--bases-table-header-background-hover","var(--background-modifier-hover)");
|
||||
canvasNode?.style.setProperty("--bases-table-header-sort-mask","linear-gradient(to left, transparent var(--size-4-6), black var(--size-4-6))");
|
||||
canvasNode?.style.setProperty("--bases-table-border-color","var(--table-border-color)");
|
||||
canvasNode?.style.setProperty("--bases-table-row-background-hover","var(--table-row-background-hover)");
|
||||
canvasNode?.style.setProperty("--bases-table-cell-shadow-active","0 0 0 2px var(--interactive-accent)");
|
||||
canvasNode?.style.setProperty("--bases-table-cell-background-active","var(--background-primary)");
|
||||
canvasNode?.style.setProperty("--bases-table-cell-background-disabled","var(--background-primary-alt)");
|
||||
canvasNode?.style.setProperty("--bases-cards-container-background","var(--background-primary)");
|
||||
canvasNode?.style.setProperty("--bases-cards-background","var(--background-primary)");
|
||||
canvasNode?.style.setProperty("--bases-cards-cover-background","var(--background-primary-alt)");
|
||||
canvasNode?.style.setProperty("--bases-cards-shadow","0 0 0 1px var(--background-modifier-border)");
|
||||
canvasNode?.style.setProperty("--bases-cards-shadow-hover","0 0 0 1px var(--background-modifier-border-hover)");
|
||||
break;
|
||||
case "pdf":
|
||||
canvasNode?.style.setProperty("--pdf-sidebar-background","var(--background-primary)");
|
||||
canvasNode?.style.setProperty("--pdf-background","var(--background-primary)");
|
||||
canvasNode?.style.setProperty("--pdf-sidebar-background","var(--background-primary)");
|
||||
break;
|
||||
}
|
||||
|
||||
if(mdProps.borderMatchElement) {
|
||||
const opacity = (mdProps?.borderOpacity ?? 50)/100;
|
||||
@@ -342,7 +646,7 @@ function RenderObsidianView(
|
||||
const element = elementRef.current;
|
||||
const canvasNode = containerRef.current;
|
||||
if(!canvasNode.hasClass("canvas-node")) return;
|
||||
setColors(canvasNode, element, mdProps, canvasColor);
|
||||
setColors(canvasNode, element, mdProps, canvasColor, viewTypeRef.current);
|
||||
}, [
|
||||
mdProps?.useObsidianDefaults,
|
||||
mdProps?.backgroundMatchCanvas,
|
||||
@@ -355,6 +659,7 @@ function RenderObsidianView(
|
||||
elementRef.current,
|
||||
containerRef.current,
|
||||
canvasColor,
|
||||
viewTypeRef.current,
|
||||
])
|
||||
|
||||
//--------------------------------------------------------------------------------
|
||||
@@ -378,50 +683,80 @@ function RenderObsidianView(
|
||||
event?.stopPropagation();
|
||||
}
|
||||
|
||||
if (isActiveRef.current && !isEditingRef.current && leafRef.current?.leaf) {
|
||||
if(leafRef.current.leaf.view?.getViewType() === "markdown") {
|
||||
const api:ExcalidrawImperativeAPI = view.excalidrawAPI;
|
||||
const el = api.getSceneElements().filter(el=>el.id === element.id)[0];
|
||||
|
||||
if(!el || el.angle !== 0) {
|
||||
new Notice("Sorry, cannot edit rotated markdown documents");
|
||||
return;
|
||||
}
|
||||
//@ts-ignore
|
||||
const modes = leafRef.current.leaf.view.modes;
|
||||
if (!modes) {
|
||||
return;
|
||||
}
|
||||
leafRef.current.leaf.view.setMode(modes['source']);
|
||||
isEditingRef.current = true;
|
||||
patchMobileView(view);
|
||||
} else if (leafRef.current?.node) {
|
||||
//Handle canvas node
|
||||
const newTheme = getTheme(view, themeRef.current);
|
||||
containerRef.current?.addClasses(["is-editing", "is-focused"]);
|
||||
view.canvasNodeFactory.startEditing(leafRef.current.node, newTheme);
|
||||
}
|
||||
if(!isActiveRef.current || isEditingRef.current || !leafRef.current) {
|
||||
return;
|
||||
}
|
||||
}, [leafRef.current?.leaf, element.id, view, themeRef.current]);
|
||||
|
||||
if(leafRef.current) leafRef.current.editNode = handleClick;
|
||||
/*if(isActiveRef.current && leafRef.current?.leaf) {
|
||||
setKeepOnTop();
|
||||
view.app.workspace.setActiveLeaf(leafRef.current.leaf, { focus: true });
|
||||
}*/
|
||||
|
||||
if (leafRef.current.node) {
|
||||
//Handle canvas node
|
||||
const newTheme = getTheme(view, themeRef.current);
|
||||
containerRef.current?.addClasses(["is-editing", "is-focused"]);
|
||||
view.canvasNodeFactory.startEditing(leafRef.current.node, newTheme);
|
||||
return;
|
||||
}
|
||||
|
||||
if(leafRef.current.leaf && viewTypeRef.current === "markdown") {
|
||||
const api:ExcalidrawImperativeAPI = view.excalidrawAPI;
|
||||
const el = api.getSceneElements().filter(el=>el.id === element.id)[0];
|
||||
if(!el || el.angle !== 0) {
|
||||
new Notice("Sorry, cannot edit rotated markdown documents");
|
||||
return;
|
||||
}
|
||||
//@ts-ignore
|
||||
const modes = leafRef.current.leaf.view.modes;
|
||||
if (!modes) {
|
||||
return;
|
||||
}
|
||||
patchMobileView(view);
|
||||
leafRef.current.leaf.view.setMode(modes['source']);
|
||||
isEditingRef.current = true;
|
||||
}
|
||||
}, [leafRef.current?.leaf, element.id, view, themeRef.current, isActiveRef.current, isEditingRef.current, viewTypeRef.current]);
|
||||
|
||||
const startEditing = React.useCallback(() => {
|
||||
if(isActiveRef.current && isEditingRef.current) {
|
||||
return;
|
||||
}
|
||||
isActiveRef.current = true;
|
||||
handleClick();
|
||||
}, [isActiveRef.current, isEditingRef.current, handleClick]);
|
||||
|
||||
if(leafRef.current) leafRef.current.editNode = startEditing;
|
||||
// Event listener for key press
|
||||
React.useEffect(() => {
|
||||
const handleKeyPress = (event: KeyboardEvent) => {
|
||||
if (event.key === "Enter") {
|
||||
handleClick(event); // Call handleClick function when Enter key is pressed
|
||||
// Deactivate active embeddable on Escape
|
||||
if (event.key === "Escape" && isActiveRef.current) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
view.updateScene({ appState: { activeEmbeddable: null } });
|
||||
return;
|
||||
}
|
||||
// Existing Enter behavior
|
||||
|
||||
if (
|
||||
event.key === "Enter" && !isEditingRef.current &&
|
||||
(selectedElementId === element.id || activeEmbeddable?.element?.id === element.id)
|
||||
) {
|
||||
startEditing(); // Call handleClick function when Enter key is pressed
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener("keydown", handleKeyPress); // Add event listener for key press
|
||||
// Use capture so this runs even if container stops bubbling
|
||||
document.addEventListener("keydown", handleKeyPress, true);
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("keydown", handleKeyPress); // Remove event listener when component unmounts
|
||||
document.removeEventListener("keydown", handleKeyPress, true);
|
||||
};
|
||||
}, [handleClick]);
|
||||
}, [handleClick, isActiveRef.current, view, activeEmbeddable, element, selectedElementId]);
|
||||
|
||||
//--------------------------------------------------------------------------------
|
||||
// Set isActiveRef and switch to preview mode when the iframe is not active
|
||||
// Set isActiveRef and switch to preview mode when the embeddable is not active
|
||||
//--------------------------------------------------------------------------------
|
||||
React.useEffect(() => {
|
||||
if(!containerRef?.current || !leafRef?.current) {
|
||||
@@ -431,7 +766,6 @@ function RenderObsidianView(
|
||||
const previousIsActive = isActiveRef.current;
|
||||
isActiveRef.current = (activeEmbeddable?.element.id === element.id) && (activeEmbeddable?.state === "active");
|
||||
|
||||
const node = leafRef.current?.node as ObsidianCanvasNode;
|
||||
if (previousIsActive === isActiveRef.current) {
|
||||
return;
|
||||
}
|
||||
@@ -440,21 +774,8 @@ function RenderObsidianView(
|
||||
setFileToLocalGraph(view.app, file);
|
||||
}
|
||||
|
||||
if(leafRef.current.leaf?.view?.getViewType() === "markdown") {
|
||||
//Handle markdown leaf
|
||||
//@ts-ignore
|
||||
const modes = leafRef.current.leaf.view.modes;
|
||||
if(!modes) {
|
||||
return;
|
||||
}
|
||||
|
||||
if(!isActiveRef.current) {
|
||||
//@ts-ignore
|
||||
leafRef.current.leaf.view.setMode(modes["preview"]);
|
||||
isEditingRef.current = false;
|
||||
return;
|
||||
}
|
||||
} else if (node) {
|
||||
const node = leafRef.current?.node as ObsidianCanvasNode;
|
||||
if (node) {
|
||||
//Handle canvas node
|
||||
if(isActiveRef.current && view.plugin.settings.markdownNodeOneClickEditing && !containerRef.current?.hasClass("is-editing")) { //!node.isEditing
|
||||
const newTheme = getTheme(view, themeRef.current);
|
||||
@@ -464,10 +785,49 @@ function RenderObsidianView(
|
||||
containerRef.current?.removeClasses(["is-editing", "is-focused"]);
|
||||
view.canvasNodeFactory.stopEditing(node);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if(leafRef.current.leaf) {
|
||||
// Manage persistent mobile patch lifecycle for LEAF on phones
|
||||
if (DEVICE.isPhone) {
|
||||
if (isActiveRef.current) {
|
||||
// start persistent observer if not running
|
||||
if (!mobilePatchCleanupRef.current) {
|
||||
const cleanup = patchMobileView(view, {
|
||||
keepAlive: true,
|
||||
isActive: () => isActiveRef.current,
|
||||
});
|
||||
mobilePatchCleanupRef.current = (typeof cleanup === "function") ? cleanup : null;
|
||||
}
|
||||
} else {
|
||||
// stop persistent observer when deactivated
|
||||
try { mobilePatchCleanupRef.current?.(); } catch {}
|
||||
mobilePatchCleanupRef.current = null;
|
||||
}
|
||||
}
|
||||
|
||||
//I think this no longer happens since markdown is always a canvas node if canvasNodeFactory is initialized
|
||||
if(viewTypeRef.current === "markdown") {
|
||||
//Handle markdown leaf
|
||||
//@ts-ignore
|
||||
const modes = leafRef.current.leaf?.view.modes;
|
||||
if(!modes) {
|
||||
return;
|
||||
}
|
||||
|
||||
if(!isActiveRef.current) {
|
||||
//@ts-ignore
|
||||
leafRef.current.leaf.view.setMode(modes["preview"]);
|
||||
isEditingRef.current = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [
|
||||
containerRef,
|
||||
leafRef,
|
||||
activeEmbeddable?.state,
|
||||
isActiveRef,
|
||||
activeEmbeddable?.element,
|
||||
activeEmbeddable?.state,
|
||||
@@ -482,11 +842,12 @@ function RenderObsidianView(
|
||||
};
|
||||
|
||||
|
||||
export const CustomEmbeddable: React.FC<{element: NonDeletedExcalidrawElement; view: ExcalidrawView; appState: UIAppState; linkText: string}> = ({ element, view, appState, linkText }) => {
|
||||
export const CustomEmbeddable: React.FC<{element: ExcalidrawEmbeddableElement; view: ExcalidrawView; appState: UIAppState; linkText: string}> = ({ element, view, appState, linkText }) => {
|
||||
const React = view.packages.react;
|
||||
const containerRef: React.RefObject<HTMLDivElement> = React.useRef(null);
|
||||
const theme = getTheme(view, appState.theme);
|
||||
const mdProps: EmbeddableMDCustomProps = element.customData?.mdProps || null;
|
||||
const selectedElementIds = Object.keys(appState.selectedElementIds);
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
@@ -495,6 +856,7 @@ export const CustomEmbeddable: React.FC<{element: NonDeletedExcalidrawElement; v
|
||||
height: `100%`,
|
||||
borderRadius: "var(--embeddable-radius)",
|
||||
color: `var(--text-normal)`,
|
||||
touchAction: "auto",
|
||||
}}
|
||||
className={`${theme} canvas-node ${
|
||||
mdProps?.filenameVisible && !mdProps.useObsidianDefaults ? "" : "excalidraw-mdEmbed-hideFilename"}`}
|
||||
@@ -508,6 +870,7 @@ export const CustomEmbeddable: React.FC<{element: NonDeletedExcalidrawElement; v
|
||||
activeEmbeddable={appState.activeEmbeddable}
|
||||
theme={appState.theme}
|
||||
canvasColor={appState.viewBackgroundColor}
|
||||
selectedElementId={selectedElementIds.length === 1 ? selectedElementIds[0] : null}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -10,9 +10,9 @@ import { ScriptEngine } from "../../../shared/Scripts";
|
||||
import { MD_EX_SECTIONS, ROOTELEMENTSIZE, nanoid, sceneCoordsToViewportCoords } from "src/constants/constants";
|
||||
import { REGEX_LINK, REG_LINKINDEX_HYPERLINK } from "../../../shared/ExcalidrawData";
|
||||
import { processLinkText, useDefaultExcalidrawFrame } from "src/utils/customEmbeddableUtils";
|
||||
import { cleanSectionHeading } from "src/utils/obsidianUtils";
|
||||
import { cleanSectionHeading, getActivePDFPageNumberFromPDFView } from "src/utils/obsidianUtils";
|
||||
import { EmbeddableSettings } from "src/shared/Dialogs/EmbeddableSettings";
|
||||
import { openExternalLink } from "src/utils/excalidrawViewUtils";
|
||||
import { insertImageToView, openExternalLink } from "src/utils/excalidrawViewUtils";
|
||||
import { getEA } from "src/core";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { CaptureUpdateAction } from "src/constants/constants";
|
||||
@@ -40,7 +40,7 @@ export class EmbeddableMenu {
|
||||
this.renderButtons = null;
|
||||
}
|
||||
|
||||
private updateElement = (subpath: string, element: ExcalidrawEmbeddableElement, file: TFile) => {
|
||||
private updateElement = async (subpath: string, element: ExcalidrawEmbeddableElement, file: TFile, save: boolean = true) => {
|
||||
if(!element) return;
|
||||
const view = this.view;
|
||||
const app = view.app;
|
||||
@@ -56,7 +56,8 @@ export class EmbeddableMenu {
|
||||
ea.copyViewElementsToEAforEditing([element]);
|
||||
ea.getElement(element.id).link = link;
|
||||
view.excalidrawData.elementLinks.set(element.id, link);
|
||||
ea.addElementsToView(false, true, true).then(() => ea.destroy());
|
||||
await ea.addElementsToView(false, save, true);
|
||||
ea.destroy();
|
||||
}
|
||||
|
||||
private handleMouseEnter () {
|
||||
@@ -119,6 +120,46 @@ export class EmbeddableMenu {
|
||||
}
|
||||
}
|
||||
|
||||
private actionBookmarkPage (element: ExcalidrawEmbeddableElement) {
|
||||
if(!element) return;
|
||||
const pdfView = this.view.getEmbeddableLeafElementById(element.id)?.node?.child;
|
||||
if(!pdfView) return;
|
||||
const page = getActivePDFPageNumberFromPDFView(pdfView);
|
||||
if(!page) return;
|
||||
const pdfFile: TFile = pdfView?.file;
|
||||
if(!pdfFile) return;
|
||||
this.updateElement(`#page=${page}`, element, pdfFile, false);
|
||||
}
|
||||
|
||||
private async actionInsertPageAsImage (element: ExcalidrawEmbeddableElement) {
|
||||
if(!element) return;
|
||||
const pdfView = this.view.getEmbeddableLeafElementById(element.id)?.node?.child;
|
||||
if(!pdfView) return;
|
||||
const page = getActivePDFPageNumberFromPDFView(pdfView);
|
||||
if(!page) return;
|
||||
const pdfFile: TFile = pdfView?.file;
|
||||
if(!pdfFile) return;
|
||||
const ea = getEA(this.view) as ExcalidrawAutomate;
|
||||
ea.selectElementsInView([]);
|
||||
const x = element.x + element.width + 20;
|
||||
const y = element.y;
|
||||
const path = this.view.app.metadataCache.fileToLinktext(
|
||||
pdfFile,
|
||||
this.view.file.path,
|
||||
false,
|
||||
)
|
||||
const id = await insertImageToView(
|
||||
ea,
|
||||
{x,y},
|
||||
`${path}#page=${page}`,
|
||||
undefined,
|
||||
undefined,
|
||||
false,
|
||||
);
|
||||
ea.selectElementsInView([id]);
|
||||
ea.destroy();
|
||||
}
|
||||
|
||||
private async actionMarkdownBlock (file: TFile, subpath: string, element: ExcalidrawEmbeddableElement) {
|
||||
if(!file) return;
|
||||
this.view.updateScene({appState: {activeEmbeddable: null}, captureUpdate: CaptureUpdateAction.NEVER});
|
||||
@@ -298,12 +339,26 @@ export class EmbeddableMenu {
|
||||
icon={ICONS.Properties}
|
||||
/>
|
||||
{isPDF && (
|
||||
<ActionButton
|
||||
key={"Crop"}
|
||||
title={t("CROP_PAGE")}
|
||||
action={() => this.actionCrop(element)}
|
||||
icon={ICONS.Crop}
|
||||
/>
|
||||
<>
|
||||
<ActionButton
|
||||
key={"Crop"}
|
||||
title={t("CROP_PAGE")}
|
||||
action={() => this.actionCrop(element)}
|
||||
icon={ICONS.Crop}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"Bookmark"}
|
||||
title={t("BOOKMARK_PAGE")}
|
||||
action={() => this.actionBookmarkPage(element)}
|
||||
icon={ICONS.Bookmark}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"Camera"}
|
||||
title={t("CAPTURE_PAGE")}
|
||||
action={() => this.actionInsertPageAsImage(element)}
|
||||
icon={ICONS.Camera}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -498,7 +498,7 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
<fieldset>
|
||||
<legend>Utility actions</legend>
|
||||
<div className="buttonList buttonListIcon">
|
||||
<ActionButton
|
||||
<ActionButton
|
||||
key={"scriptEngine"}
|
||||
title={t("INSTALL_SCRIPT_BUTTON")}
|
||||
action={this.actionOpenScriptInstallDialog.bind(this)}
|
||||
@@ -517,7 +517,7 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
action={(this.actionConvertExcalidrawToMD.bind(this))}
|
||||
icon={ICONS.convertFile}
|
||||
/>
|
||||
) : (
|
||||
) : !this.state.isPreviewMode && (
|
||||
<ActionButton
|
||||
key={"viewmode"}
|
||||
title={this.state.isPreviewMode ? t("PARSED") : t("RAW")}
|
||||
@@ -549,6 +549,8 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
: ICONS.gotoFullScreen
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="buttonList buttonListIcon">
|
||||
<ActionButton
|
||||
key={"search"}
|
||||
title={t("SEARCH")}
|
||||
|
||||
@@ -34,6 +34,7 @@ export interface ObsidianCanvasNode {
|
||||
isEditing: boolean;
|
||||
file: TFile;
|
||||
detach: Function;
|
||||
isEditable: Function;
|
||||
}
|
||||
|
||||
export class CanvasNodeFactory {
|
||||
@@ -84,8 +85,8 @@ export class CanvasNodeFactory {
|
||||
|
||||
private async waitForEditor(node: ObsidianCanvasNode): Promise<HTMLElement | null> {
|
||||
let counter = 0;
|
||||
while (!node.child.editor?.containerEl?.parentElement?.parentElement && counter++ < 100) {
|
||||
await new Promise(resolve => setTimeout(resolve, 25));
|
||||
while (!node.child.editor?.containerEl?.parentElement?.parentElement && counter++ < 40) {
|
||||
await sleep(25);
|
||||
}
|
||||
return node.child.editor?.containerEl?.parentElement?.parentElement;
|
||||
}
|
||||
@@ -112,12 +113,11 @@ export class CanvasNodeFactory {
|
||||
}
|
||||
|
||||
public async startEditing(node: ObsidianCanvasNode, theme: string) {
|
||||
if (!this.initialized || !node) return;
|
||||
if (!this.initialized || !node || !node.isEditable()) return;
|
||||
|
||||
try {
|
||||
//if (node.file === this.view.file) {
|
||||
await this.view.setEmbeddableNodeIsEditing();
|
||||
//}
|
||||
await this.view.setEmbeddableNodeIsEditing();
|
||||
|
||||
node.startEditing();
|
||||
node.isEditing = true;
|
||||
|
||||
@@ -138,12 +138,10 @@ export class CanvasNodeFactory {
|
||||
}
|
||||
|
||||
public stopEditing(node: ObsidianCanvasNode) {
|
||||
if (!this.initialized || !node || !node.isEditing) return;
|
||||
if (!this.initialized || !node || !node.isEditing || !node.isEditable()) return;
|
||||
|
||||
try {
|
||||
//if (node.file === this.view.file) {
|
||||
this.view.clearEmbeddableNodeIsEditing();
|
||||
//}
|
||||
this.view.clearEmbeddableNodeIsEditing();
|
||||
node.child.showPreview();
|
||||
node.isEditing = false;
|
||||
this.observer?.disconnect();
|
||||
|
||||
+23
@@ -857,3 +857,26 @@ textarea.excalidraw-wysiwyg, .excalidraw input {
|
||||
fill: none;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/*remove blur from PDF embed*/
|
||||
.excalidraw__embeddable-container canvas {
|
||||
image-rendering: auto;
|
||||
}
|
||||
|
||||
.excalidraw__embeddable-container .mod-nofilter canvas {
|
||||
filter: none !important;
|
||||
}
|
||||
|
||||
.excalidraw__embeddable-container .canvas-node.is-selected .canvas-node-container,
|
||||
.excalidraw__embeddable-container .canvas-node.is-focused .canvas-node-container {
|
||||
border-color: inherit;
|
||||
box-shadow: inherit;
|
||||
}
|
||||
|
||||
.excalidraw__embeddable-container .pdf-toolbar-right {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.excalidraw-scriptengine-install .modal-close-button {
|
||||
z-index: 9999;
|
||||
}
|
||||
Reference in new issue
Block a user