Compare commits

...
Author SHA1 Message Date
zsviczian 989e7969dc renderScriptButtons, referenced view in toolspanel with weak reference 2025-11-30 21:05:46 +01:00
zsviczian f5c7820315 Merge pull request #2554 from rlan/feat/zh-tw/ba5d1aa
Update zh-tw.ts to ba5d1aa
2025-11-30 20:52:03 +01:00
zsviczian c416c21985 Merge pull request #2553 from playermiller109/2025-11-30
Update zh-cn.ts to ba5d1aa
2025-11-30 20:51:50 +01:00
zsviczian e5f6466542 improved ExcalidrawView onClose cleanup and timer removal 2025-11-30 16:44:13 +01:00
zsviczian 95ba981445 fix markdownPostProcessor blob leak 2025-11-30 16:34:56 +01:00
zsviczian 31cc45ff6d fixed prompt.ts event listner release 2025-11-30 16:31:54 +01:00
zsviczian 62f51511ed fixed suggestionmodal event listners release 2025-11-30 16:28:43 +01:00
zsviczian 5c628e08f4 fix remove debunceActiveLeafChangeHandlerTimer; cleanup observerManager; clear timers in ExcalidrawView onunload 2025-11-30 16:14:17 +01:00
zsviczian 0e11150055 fixed embeddedFileLoader memory stuck interval issue 2025-11-30 16:04:05 +01:00
zsviczian 37b4cdd44a fix memory leak with updateEmbeddableLeafRef and ImageCache obsidianURL 2025-11-30 15:55:05 +01:00
zsviczian a2a33bc463 fixed memory issues with updateEmbeddableRef, highlight color cache, embeddable onKeyDown event handler 2025-11-30 15:41:01 +01:00
Rick Lan 00531325ea Update zh-tw.ts to ba5d1aa 2025-11-29 22:34:11 -08:00
zsviczian a7d4d59619 updated getHighlightColor (only use background, not stroke) 2025-11-30 07:05:02 +01:00
playermiller109 b05e26d138 Unify the translation of 'opacity'
In the design field, '不透明度' is widely recognized.
As for general users, while '透明度' and '不透明度' are often interchangeable in daily use,
recent AI-powered tools reliably translate it as '不透明度'.
Unifying it as '不透明度' should be clear to both general users and future maintainers.
2025-11-30 13:01:24 +08:00
playermiller109 ce3cda7a1d Update zh-cn.ts to ba5d1aa 2025-11-30 10:17:18 +08:00
21 changed files with 405 additions and 171 deletions

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.18.0-beta-4",
"version": "2.18.0-beta-5",
"minAppVersion": "1.5.7",
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
"author": "Zsolt Viczian",
+1 -1
View File
@@ -24,7 +24,7 @@
"license": "MIT",
"dependencies": {
"@popperjs/core": "^2.11.8",
"@zsviczian/excalidraw": "0.18.0-58",
"@zsviczian/excalidraw": "0.18.0-59",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"@zsviczian/colormaster": "^1.2.2",
+1 -1
View File
@@ -560,7 +560,7 @@ export default class ExcalidrawPlugin extends Plugin {
let fontMetrics = f.extension.startsWith("woff") ? undefined : await getFontMetrics(fourthFontDataURL, "Local Font");
if (!fontMetrics) {
console.log("Font Metrics not found, using default");
//console.log("Font Metrics not found, using default");
fontMetrics = {
unitsPerEm: 1000,
ascender: 750,
+4
View File
@@ -53,6 +53,10 @@ export class EventManager {
window.clearTimeout(this.leafChangeTimeout);
this.leafChangeTimeout = null;
}
if(this.debunceActiveLeafChangeHandlerTimer) {
window.clearTimeout(this.debunceActiveLeafChangeHandlerTimer);
this.debunceActiveLeafChangeHandlerTimer = null;
}
this.removeEventLisnters.forEach((removeEventListener) =>
removeEventListener(),
);
+19 -2
View File
@@ -136,8 +136,17 @@ const _getPNG = async ({imgAttributes,filenameParts,theme,cacheReady,img,file,ex
if (!png) {
return null;
}
img.src = URL.createObjectURL(png);
cacheReady && imageCache.addImageToCache(cacheKey, img.src, png);
const blobUrl = URL.createObjectURL(png);
img.src = blobUrl;
// Revoke the ObjectURL after the image loads or fails to prevent memory leaks
if (!cacheReady) {
const cleanup = () => URL.revokeObjectURL(blobUrl);
img.addEventListener('load', cleanup, { once: true });
img.addEventListener('error', cleanup, { once: true });
}
cacheReady && imageCache.addImageToCache(cacheKey, blobUrl, png);
return img;
}
@@ -382,6 +391,14 @@ const addSVGToImgSrc = (img: HTMLImageElement, svg: SVGSVGElement, cacheReady: b
const blob = new Blob([svgString], { type: 'image/svg+xml' });
const blobUrl = URL.createObjectURL(blob);
img.setAttribute("src", blobUrl);
// Revoke the ObjectURL after the image loads or fails to prevent memory leaks
if (!cacheReady) {
const cleanup = () => URL.revokeObjectURL(blobUrl);
img.addEventListener('load', cleanup, { once: true });
img.addEventListener('error', cleanup, { once: true });
}
cacheReady && imageCache.addImageToCache(cacheKey, blobUrl, blob);
return img;
}
+7 -6
View File
@@ -41,19 +41,20 @@ export class ObserverManager {
this.removeModalContainerObserver();
if (this.workspaceDrawerLeftObserver) {
this.workspaceDrawerLeftObserver.disconnect();
this.workspaceDrawerLeftObserver = null;
}
if (this.workspaceDrawerRightObserver) {
this.workspaceDrawerRightObserver.disconnect();
this.workspaceDrawerRightObserver = null;
}
if (this.fileExplorerObserver) {
this.fileExplorerObserver.disconnect();
this.fileExplorerObserver = null;
}
if (this.workspaceDrawerRightObserver) {
this.workspaceDrawerRightObserver.disconnect();
}
if (this.workspaceDrawerLeftObserver) {
this.workspaceDrawerLeftObserver.disconnect();
}
this.plugin = null;
this.app = null;
this.activeViewDoc = null;
}
public addThemeObserver() {
+7 -8
View File
@@ -508,9 +508,8 @@ export default {
GRID_DYNAMIC_COLOR_DESC:
"<b>开启:</b>更改网格颜色以匹配绘图颜色。<br><b>关闭:</b>将以下颜色用作网格颜色。",
GRID_COLOR_NAME: "网格颜色",
GRID_OPACITY_NAME: "网格透明度",
GRID_OPACITY_DESC: "设置网格的透明度。还将控制将箭头绑定到元素时绑定框的透明度。" +
"0 全透明 ⟺ 100 不透明。",
GRID_OPACITY_NAME: "网格不透明度",
GRID_OPACITY_DESC: "设置网格的不透明度。0 全透明 ⟺ 100 不透明。",
GRID_DIRECTION_NAME: "网格方向",
GRID_DIRECTION_DESC: "第一个开关显示/隐藏水平网格,第二个开关显示/隐藏垂直网格。",
GRID_HORIZONTAL: "渲染水平网格",
@@ -585,9 +584,9 @@ export default {
`<b>开启:</b>在 Excalidraw <u>查看模式(View)</u>下,鼠标悬停在 <code>[[内部链接]]</code> 上即可预览;` +
"而在<u>普通模式(Normal)</u>下,鼠标悬停在内部链接右上角的蓝色标识上即可预览。<br>" +
`<b>关闭:</b>鼠标悬停在 <code>[[内部链接]]</code> 上,并且按住 ${labelCTRL()} 才能预览。`,
LINKOPACITY_NAME: "链接标识的透明度",
LINKOPACITY_NAME: "链接标识的不透明度",
LINKOPACITY_DESC:
"含有链接的元素,其右上角的链接标识的透明度。0 全透明 ⟺ 100 不透明。",
"含有链接的元素,其右上角的链接标识的不透明度。0 全透明 ⟺ 100 不透明。",
LINK_CTRL_CLICK_NAME:
`按住 ${labelCTRL()} 并点击含有 [[链接]] 或 [别名](链接) 的文本来打开链接`,
LINK_CTRL_CLICK_DESC:
@@ -1017,15 +1016,15 @@ export default {
ES_FILENAME_VISIBLE: "显示页内标题",
ES_BACKGROUND_HEAD: "背景色",
ES_BACKGROUND_DESC_INFO: "点击此处查看更多颜色信息",
ES_BACKGROUND_DESC_DETAIL: "背景色仅影响预览模式的 MD-Embeddable。在编辑模式,它会根据场景(通过笔记属性设置)或插件设置,遵循 Obsidian 的深色/浅色主题。背景色有两层:元素背景色(下层颜色)和上层颜色。选择“匹配元素”表示两层都遵循元素背景色。选择“匹配绘图”或特定背景色不会改变元素背景色。设置透明度(如 50%)会将绘图或选定的颜色与元素背景色混合。要移除元素背景色,可以在 Excalidraw 的元素属性编辑器中将元素背景色设置为透明,这样只有上层颜色生效。",
ES_BACKGROUND_DESC_DETAIL: "背景色仅影响预览模式的 MD-Embeddable。在编辑模式,它会根据场景(通过笔记属性设置)或插件设置,遵循 Obsidian 的深色/浅色主题。背景色有两层:元素背景色(下层颜色)和上层颜色。选择“匹配元素”表示两层都遵循元素背景色。选择“匹配绘图”或特定背景色不会改变元素背景色。设置不透明度(如 50%)会将绘图或选定的颜色与元素背景色混合。要移除元素背景色,可以在 Excalidraw 的元素属性编辑器中将元素背景色设置为透明,这样只有上层颜色生效。",
ES_BACKGROUND_MATCH_ELEMENT: "匹配元素背景色",
ES_BACKGROUND_MATCH_CANVAS: "匹配绘图背景色",
ES_BACKGROUND_COLOR: "背景色",
ES_BORDER_HEAD: "边框颜色",
ES_BORDER_COLOR: "边框颜色",
ES_BORDER_MATCH_ELEMENT: "匹配元素边框颜色",
ES_BACKGROUND_OPACITY: "背景透明度",
ES_BORDER_OPACITY: "边框透明度",
ES_BACKGROUND_OPACITY: "背景不透明度",
ES_BORDER_OPACITY: "边框不透明度",
ES_EMBEDDABLE_SETTINGS: "MD-Embeddable 设置",
ES_USE_OBSIDIAN_DEFAULTS: "使用 Obsidian 默认设置",
ES_ZOOM_100_RELATIVE_DESC: "使元素的缩放等级等于当前绘图的缩放等级",
+2 -1
View File
@@ -315,7 +315,7 @@ export default {
AI_OPENAI_DEFAULT_MODEL_PLACEHOLDER: "gpt-3.5-turbo-1106",
AI_OPENAI_DEFAULT_MAX_TOKENS_NAME: "最大 token 數",
AI_OPENAI_DEFAULT_MAX_TOKENS_DESC:
"API 響應中生成的最大 token 數。設置為 0 以忽略 max_tokens 欄位(適用於不支援該參數的模型,如 GPT-5)。",
"API 響應中生成的最大 token 數。設定為 0 以忽略 max_tokens 欄位(適用於不支援該引數的模型,如 GPT-5)。",
AI_OPENAI_DEFAULT_IMAGE_MODEL_NAME: "預設的圖片 AI 模型",
AI_OPENAI_DEFAULT_IMAGE_MODEL_DESC:
"使用哪個 AI 模型來生成圖片。圖生圖會強制使用 dall-e-2 模型," +
@@ -1134,6 +1134,7 @@ export default {
EXPORTDIALOG_BACKGROUND: "背景",
EXPORTDIALOG_BACKGROUND_TRANSPARENT: "透明",
EXPORTDIALOG_BACKGROUND_USE_COLOR: "使用場景顏色",
EXPORTDIALOG_INCLUDE_INTERNAL_LINKS: "匯出內部連結為 SVG/PDF?",
// Selection
EXPORTDIALOG_SELECTED_ELEMENTS: "匯出",
EXPORTDIALOG_SELECTED_ALL: "整個場景",
+10 -2
View File
@@ -37,6 +37,7 @@ export class EmbeddableSettings extends Modal {
private isLocalURI: boolean;
private mdCustomData: EmbeddableMDCustomProps;
private onKeyDown: (ev: KeyboardEvent) => void;
private listenerHost: Document | null = null;
constructor(
private plugin: ExcalidrawPlugin,
@@ -72,7 +73,10 @@ export class EmbeddableSettings extends Modal {
}
onClose() {
this.containerEl.removeEventListener("keydown",this.onKeyDown);
if(this.listenerHost && this.onKeyDown) {
this.listenerHost.removeEventListener("keydown",this.onKeyDown);
this.listenerHost = null;
}
this.plugin = null;
this.view = null;
this.file = null;
@@ -166,7 +170,11 @@ export class EmbeddableSettings extends Modal {
}
this.onKeyDown = onKeyDown;
this.containerEl.ownerDocument.addEventListener("keydown",onKeyDown);
const ownerDoc = this.containerEl.ownerDocument;
if(ownerDoc) {
this.listenerHost = ownerDoc;
ownerDoc.addEventListener("keydown",onKeyDown);
}
}
private async applySettings() {
+4
View File
@@ -28,6 +28,10 @@ I build this plugin in my free time, as a labor of love. Curious about the philo
- By default, internal links are included in exports.
- Use the new document property: \`export-internal-links: false\` to disable exporting internal links on a per-drawing basis.
## Fixed
- Memory leak issues
- Potential fix to Backspace and CTRL+V stopping working in text elements after extended use of Excalidraw.
## New in ExcalidrawAutomate
- **createSVG()** now exposes convertMarkdownLinksToObsidianURLs and includeInternalLinks parameters.
\`\`\`ts
+41 -34
View File
@@ -101,6 +101,26 @@ export class GenericInputPrompt extends Modal {
private draggable: boolean = false;
private cleanupDragListeners: (() => void) | null = null;
// Add event handler instance properties
private handleKeyDown = (evt: KeyboardEvent) => {
if ((evt.key === "Enter" && this.lines === 1) || (isWinCTRLorMacCMD(evt) && evt.key === "Enter")) {
evt.preventDefault();
this.submit();
}
if (this.displayEditorButtons && evt.key === "k" && isWinCTRLorMacCMD(evt)) {
evt.preventDefault();
this.linkBtnClickCallback();
}
};
private handleCheckCaret = () => {
//timer is implemented because on iPad with pencil the button click generates an event on the textarea
this.selectionUpdateTimer = this.view.ownerWindow.setTimeout(() => {
this.selectionStart = this.inputComponent.inputEl.selectionStart;
this.selectionEnd = this.inputComponent.inputEl.selectionEnd;
}, 30);
};
public static Prompt(
view: ExcalidrawView,
plugin: ExcalidrawPlugin,
@@ -226,25 +246,15 @@ export class GenericInputPrompt extends Modal {
.setValue(value ?? "")
.onChange((value) => (this.input = value));
let i = 0;
const checkcaret = () => {
//timer is implemented because on iPad with pencil the button click generates an event on the textarea
this.selectionUpdateTimer = this.view.ownerWindow.setTimeout(() => {
this.selectionStart = this.inputComponent.inputEl.selectionStart;
this.selectionEnd = this.inputComponent.inputEl.selectionEnd;
}, 30);
}
textComponent.inputEl.addEventListener("keydown", this.keyDownCallback.bind(this));
textComponent.inputEl.addEventListener('keyup', checkcaret.bind(this)); // Every character written
textComponent.inputEl.addEventListener('pointerup', checkcaret.bind(this)); // Click down
textComponent.inputEl.addEventListener('touchend', checkcaret.bind(this)); // Click down
textComponent.inputEl.addEventListener('input', checkcaret.bind(this)); // Other input events
textComponent.inputEl.addEventListener('paste', checkcaret.bind(this)); // Clipboard actions
textComponent.inputEl.addEventListener('cut', checkcaret.bind(this));
textComponent.inputEl.addEventListener('select', checkcaret.bind(this)); // Some browsers support this event
textComponent.inputEl.addEventListener('selectionchange', checkcaret.bind(this));// Some browsers support this event
textComponent.inputEl.addEventListener("keydown", this.handleKeyDown);
textComponent.inputEl.addEventListener('keyup', this.handleCheckCaret);
textComponent.inputEl.addEventListener('pointerup', this.handleCheckCaret);
textComponent.inputEl.addEventListener('touchend', this.handleCheckCaret);
textComponent.inputEl.addEventListener('input', this.handleCheckCaret);
textComponent.inputEl.addEventListener('paste', this.handleCheckCaret);
textComponent.inputEl.addEventListener('cut', this.handleCheckCaret);
textComponent.inputEl.addEventListener('select', this.handleCheckCaret);
textComponent.inputEl.addEventListener('selectionchange', this.handleCheckCaret);
return textComponent;
}
@@ -372,17 +382,6 @@ export class GenericInputPrompt extends Modal {
this.cancel();
}
private keyDownCallback = (evt: KeyboardEvent) => {
if ((evt.key === "Enter" && this.lines === 1) || (isWinCTRLorMacCMD(evt) && evt.key === "Enter")) {
evt.preventDefault();
this.submit();
}
if (this.displayEditorButtons && evt.key === "k" && isWinCTRLorMacCMD(evt)) {
evt.preventDefault();
this.linkBtnClickCallback();
}
};
private submit() {
this.didSubmit = true;
this.close();
@@ -401,10 +400,18 @@ export class GenericInputPrompt extends Modal {
}
private removeInputListener() {
this.inputComponent?.inputEl?.removeEventListener(
"keydown",
this.keyDownCallback,
);
if (!this.inputComponent?.inputEl) return;
const inputEl = this.inputComponent.inputEl;
inputEl.removeEventListener("keydown", this.handleKeyDown);
inputEl.removeEventListener('keyup', this.handleCheckCaret);
inputEl.removeEventListener('pointerup', this.handleCheckCaret);
inputEl.removeEventListener('touchend', this.handleCheckCaret);
inputEl.removeEventListener('input', this.handleCheckCaret);
inputEl.removeEventListener('paste', this.handleCheckCaret);
inputEl.removeEventListener('cut', this.handleCheckCaret);
inputEl.removeEventListener('select', this.handleCheckCaret);
inputEl.removeEventListener('selectionchange', this.handleCheckCaret);
}
private specialCharsBtnClickCallback = (evt: MouseEvent) => {
+4
View File
@@ -742,6 +742,10 @@ export class EmbeddedFilesLoader {
}
const addFilesTimer = setInterval(() => {
if (this.terminate) {
clearInterval(addFilesTimer);
return;
}
if(files[batch].length === 0) {
return;
}
+11
View File
@@ -55,6 +55,7 @@ class ImageCache {
this.db = null;
this.plugin = null;
this.app = null;
this.obsidanURLCache.forEach((url) => URL.revokeObjectURL(url));
this.obsidanURLCache.clear();
this.obsidanURLCache = null;
}
@@ -179,6 +180,10 @@ class ImageCache {
const fileExists = files.some((f: TFile) => f.path === filepath);
const file = fileExists ? files.find((f: TFile) => f.path === filepath) : null;
if (isLegacyKey || !file || (file && (file.stat.mtime > cursor.value.mtime)) || (!cursor.value.blob && !cursor.value.svg)) {
if(this.obsidanURLCache.has(key)) {
URL.revokeObjectURL(this.obsidanURLCache.get(key));
this.obsidanURLCache.delete(key);
}
deletePromises.push(
new Promise<void>((innerResolve, innerReject) => {
const deleteRequest = store.delete(cursor.primaryKey);
@@ -368,6 +373,9 @@ class ImageCache {
const key = getKey(key_);
store.put(data, key);
if(!Boolean(svg)) {
if(this.obsidanURLCache.has(key) && this.obsidanURLCache.get(key) !== obsidianURL) {
URL.revokeObjectURL(this.obsidanURLCache.get(key));
}
this.obsidanURLCache.set(key, obsidianURL);
}
}
@@ -406,6 +414,9 @@ class ImageCache {
return; // Database not initialized yet
}
this.obsidanURLCache.forEach((url) => URL.revokeObjectURL(url));
this.obsidanURLCache.clear();
return this.clear(this.cacheStoreName, "Image cache was cleared");
}
+12 -1
View File
@@ -17,6 +17,8 @@ export class FileSuggestionModal extends SuggestionModal<LinkSuggestion> {
cache: CachedMetadata;
filesAndAliases: LinkSuggestion[];
file: TFile;
private handleGetFile: () => void;
constructor(app: App, input: TextComponent, items: TFile[], private plugin: ExcalidrawPlugin) {
const filesAndAliases = [];
for (const file of items) {
@@ -36,7 +38,11 @@ export class FileSuggestionModal extends SuggestionModal<LinkSuggestion> {
this.text = input;
this.suggestEl.style.maxWidth = "100%";
this.suggestEl.style.width = `${input.inputEl.clientWidth}px`;
this.inputEl.addEventListener("input", () => this.getFile());
// Pre-bind the handler
this.handleGetFile = this.getFile.bind(this);
this.inputEl.addEventListener("input", this.handleGetFile);
this.setPlaceholder(t("SELECT_FILE_TO_INSERT"));
this.emptyStateText = t("NO_MATCH");
}
@@ -139,4 +145,9 @@ export class FileSuggestionModal extends SuggestionModal<LinkSuggestion> {
getItems() {
return this.filesAndAliases;
}
close(): void {
this.inputEl.removeEventListener("input", this.handleGetFile);
super.close();
}
}
@@ -12,12 +12,16 @@ export class FolderSuggestionModal extends SuggestionModal<TFolder> {
cache: CachedMetadata;
folders: TFolder[];
folder: TFolder;
private handleGetFolder: () => void;
constructor(app: App, input: TextComponent, items: TFolder[]) {
super(app, input.inputEl, items);
this.folders = [...items];
this.text = input;
this.inputEl.addEventListener("input", () => this.getFolder());
// Pre-bind the handler
this.handleGetFolder = this.getFolder.bind(this);
this.inputEl.addEventListener("input", this.handleGetFolder);
}
getFolder() {
const v = this.inputEl.value;
@@ -32,6 +36,10 @@ export class FolderSuggestionModal extends SuggestionModal<TFolder> {
this.onInputChanged();
}
close(): void {
this.inputEl.removeEventListener("input", this.handleGetFolder);
super.close();
}
getItemText(item: TFolder) {
return item.path;
}
+17 -2
View File
@@ -16,13 +16,16 @@ export class PathSuggestionModal extends SuggestionModal<
files: TFile[];
text: TextComponent;
cache: CachedMetadata;
private handleGetFile: () => void;
constructor(app: App, input: TextComponent, items: TFile[]) {
super(app, input.inputEl, items);
this.files = [...items];
this.text = input;
//this.getFile();
this.inputEl.addEventListener("input", this.getFile.bind(this));
// Pre-bind the handler
this.handleGetFile = this.getFile.bind(this);
this.inputEl.addEventListener("input", this.handleGetFile);
}
getFile() {
@@ -40,6 +43,12 @@ export class PathSuggestionModal extends SuggestionModal<
}
this.onInputChanged();
}
close(): void {
this.inputEl.removeEventListener("input", this.handleGetFile);
super.close();
}
getItemText(item: TFile | HeadingCache | BlockCache) {
if (item instanceof TFile) {
return item.path;
@@ -51,6 +60,7 @@ export class PathSuggestionModal extends SuggestionModal<
return (<BlockCache>item).id;
}
}
onChooseItem(item: TFile | HeadingCache | BlockCache) {
if (item instanceof TFile) {
this.text.setValue(item.basename);
@@ -64,6 +74,7 @@ export class PathSuggestionModal extends SuggestionModal<
this.text.setValue(`${this.file.basename}^${(<BlockCache>item).id}`);
}
}
selectSuggestion({ item }: FuzzyMatch<TFile | BlockCache | HeadingCache>) {
let link: string;
if (item instanceof TFile) {
@@ -79,6 +90,7 @@ export class PathSuggestionModal extends SuggestionModal<
this.close();
}
renderSuggestion(
result: FuzzyMatch<TFile | BlockCache | HeadingCache>,
el: HTMLElement,
@@ -131,6 +143,7 @@ export class PathSuggestionModal extends SuggestionModal<
content.setText((<BlockCache>item).id);
}
}
get headings() {
if (!this.file) {
return [];
@@ -140,6 +153,7 @@ export class PathSuggestionModal extends SuggestionModal<
}
return this.cache.headings || [];
}
get blocks() {
if (!this.file) {
return [];
@@ -149,6 +163,7 @@ export class PathSuggestionModal extends SuggestionModal<
}
return Object.values(this.cache.blocks || {}) || [];
}
getItems() {
const v = this.inputEl.value;
if (/#/.test(v)) {
+23 -13
View File
@@ -19,24 +19,34 @@ export abstract class SuggestionModal<T> extends FuzzySuggestModal<T> {
emptyStateText: string = "No match found";
limit: number = 100;
shouldNotOpen: boolean;
// Pre-bound event handlers
private handleInput: () => void;
private handleFocus: () => void;
private handleBlur: () => void;
private handleMouseDown: (event: MouseEvent) => void;
constructor(app: App, inputEl: HTMLInputElement, items: T[]) {
super(app);
this.inputEl = inputEl;
this.items = items;
// Pre-bind event handlers
this.handleInput = this.onInputChanged.bind(this);
this.handleFocus = this.onFocus.bind(this);
this.handleBlur = this.close.bind(this);
this.handleMouseDown = (event: MouseEvent) => {
event.preventDefault();
};
this.suggestEl = createDiv("suggestion-container");
this.contentEl = this.suggestEl.createDiv("suggestion");
this.suggester = new Suggester(this, this.contentEl, this.scope);
this.scope.register([], "Escape", this.onEscape.bind(this));
this.inputEl.addEventListener("input", this.onInputChanged.bind(this));
this.inputEl.addEventListener("focus", this.onFocus.bind(this));
this.inputEl.addEventListener("blur", this.close.bind(this));
this.suggestEl.on(
"mousedown",
".suggestion-container",
(event: MouseEvent) => {
event.preventDefault();
},
);
this.inputEl.addEventListener("input", this.handleInput);
this.inputEl.addEventListener("focus", this.handleFocus);
this.inputEl.addEventListener("blur", this.handleBlur);
this.suggestEl.on("mousedown", ".suggestion-container", this.handleMouseDown);
}
empty() {
@@ -106,9 +116,9 @@ export abstract class SuggestionModal<T> extends FuzzySuggestModal<T> {
if (this.popper?.deref()) {
this.popper.deref().destroy();
}
this.inputEl.removeEventListener("input", this.onInputChanged.bind(this));
this.inputEl.removeEventListener("focus", this.onFocus.bind(this));
this.inputEl.removeEventListener("blur", this.close.bind(this));
this.inputEl.removeEventListener("input", this.handleInput);
this.inputEl.removeEventListener("focus", this.handleFocus);
this.inputEl.removeEventListener("blur", this.handleBlur);
this.suggestEl.detach();
}
+11 -7
View File
@@ -192,7 +192,7 @@ export const setDynamicStyle = (
});
}
const colorsCache: Map<string,ColorMaster> = new Map();
const colorsCache: Map<string,string> = new Map();
export function getHighlightColor(
ea: ExcalidrawAutomate,
@@ -200,12 +200,16 @@ export function getHighlightColor(
sceneBgColor: string,
opacity:number = 1
): string {
strokeColor = strokeColor === "transparent"
/*strokeColor = strokeColor === "transparent"
? (sceneBgColor==="transparent" ? "#ffffff": sceneBgColor)
: strokeColor;
let contrasted = colorsCache.get(strokeColor);
if(!contrasted) {
: strokeColor;*/
strokeColor = sceneBgColor==="transparent" ? "#ffffff": sceneBgColor;
let contrasted: ColorMaster;
const cachedColor = colorsCache.get(strokeColor);
if(cachedColor) {
contrasted = CM(cachedColor);
} else {
const bg = ea.getCM(strokeColor);
const bgMix = ea.getCM(strokeColor);
const isDark = bg.isDark();
@@ -226,7 +230,7 @@ export function getHighlightColor(
color.contrast({bgColor: strokeColor, ratio:false}) as number >= desiredContrast) ??
candidates.reduce((best, color) => (color.contrast({bgColor: strokeColor, ratio: false}) > best.contrast({bgColor: strokeColor, ratio:false}) ? color : best)
);
colorsCache.set(strokeColor, contrasted);
colorsCache.set(strokeColor, contrasted.stringHEX({alpha:false}));
}
contrasted.alphaTo(opacity);
return contrasted.stringRGB({alpha:true});
+100 -22
View File
@@ -2036,7 +2036,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
//I noticed Obsidian calls this function twice when disabling the plugin
//once from "unregisterView"
//the from "detachLeavesOfType"
if(!this.dropManager) return; //the view is already closed
if(!this.dropManager && !this.excalidrawRoot) return; //the view is already closed
// This happens when the user right clicks a tab and selects delete
// in this case the onDelete event handler tirggers, but then Obsidian's delete event handler reaches onclose first, and
@@ -2044,6 +2044,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
if(!this.file) return;
this.exitFullscreen();
await this.forceSaveIfRequired();
if (this.excalidrawRoot) {
this.excalidrawRoot.unmount();
@@ -2052,38 +2053,69 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
this.clearPreventReloadTimer();
this.clearEmbeddableNodeIsEditingTimer();
this.plugin.scriptEngine?.removeViewEAs(this);
if (this.activeLoader) {
this.activeLoader.terminate = true;
this.activeLoader = null;
}
if (this.nextLoader) {
this.nextLoader.terminate = true;
this.nextLoader = null;
}
if (this.plugin) {
this.plugin.scriptEngine?.removeViewEAs(this);
if(this.plugin.ea?.targetView === this) {
this.plugin.ea.targetView = null;
}
}
this.excalidrawAPI = null;
this.dropManager.destroy();
this.dropManager = null;
if (this.dropManager) {
this.dropManager.destroy();
this.dropManager = null;
}
if(this.canvasNodeFactory) {
this.canvasNodeFactory.destroy();
this.canvasNodeFactory = null;
}
this.canvasNodeFactory = null;
this.embeddableLeafRefs.clear();
this.embeddableRefs.clear();
Object.values(this.actionButtons).forEach((el) => el.remove());
this.actionButtons = {} as Record<ActionButtons, HTMLElement>;
if(this.embeddableLeafRefs) {
this.embeddableLeafRefs.clear();
this.embeddableLeafRefs = null;
}
if(this.embeddableRefs) {
this.embeddableRefs.clear();
this.embeddableRefs = null;
}
if(this.actionButtons) {
Object.values(this.actionButtons).forEach((el) => el.remove());
this.actionButtons = null; //{} as Record<ActionButtons, HTMLElement>;
}
if (this.excalidrawData) {
this.excalidrawData.destroy();
this.excalidrawData = null;
};
if(this.exportDialog) {
this.exportDialog.destroy();
this.exportDialog = null;
}
this.hoverPreviewTarget = null;
if(this.plugin.ea?.targetView === this) {
this.plugin.ea.targetView = null;
}
if(this._hookServer?.targetView === this) {
this._hookServer.targetView = null;
}
this._hookServer = null;
this.containerEl.onWindowMigrated = null;
this.packages = {react:null, reactDOM:null, excalidrawLib:null};
if(this.containerEl) {
this.containerEl.onWindowMigrated = null;
}
this.packages = null; //{react:null, reactDOM:null, excalidrawLib:null};
let leafcount = 0;
this.app.workspace.iterateAllLeaves(l=>{
@@ -2093,7 +2125,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
leafcount++;
}
})
if(leafcount === 0) {
if(leafcount === 0 && this.plugin) {
this.plugin.deletePackage(this.ownerWindow);
}
@@ -2103,6 +2135,11 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
//super.onClose will unmount Excalidraw, need to save before that
await super.onClose();
this._plugin = null;
this._hookServer = null;
this.excalidrawData = null;
this.canvasNodeFactory = null;
tmpBruteForceCleanup(this);
}
@@ -2130,11 +2167,42 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
this.removeParentMoveObserver();
this.removeSlidingPanesListner();
if (this.autosaveTimer) {
window.clearInterval(this.autosaveTimer);
window.clearTimeout(this.autosaveTimer);
this.autosaveTimer = null;
}
this.autosaveFunction = null;
if (this.dropManager) {
this.dropManager.destroy();
this.dropManager = null;
}
// Clear all other timers
if (this.isEditingTextResetTimer) {
window.clearTimeout(this.isEditingTextResetTimer);
this.isEditingTextResetTimer = null;
}
if (this.preventReloadResetTimer) {
window.clearTimeout(this.preventReloadResetTimer);
this.preventReloadResetTimer = null;
}
if (this.editingSelfResetTimer) {
window.clearTimeout(this.editingSelfResetTimer);
this.editingSelfResetTimer = null;
}
if (this.resizeBatchTimer) {
window.clearTimeout(this.resizeBatchTimer);
this.resizeBatchTimer = null;
}
if (this.colorChangeTimer) {
window.clearTimeout(this.colorChangeTimer);
this.colorChangeTimer = null;
}
if (this.semaphores?.wheelTimeout) {
window.clearTimeout(this.semaphores.wheelTimeout);
this.semaphores.wheelTimeout = null;
}
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.onunload,`ExcalidrawView.onunload, completed`);
}
@@ -6216,10 +6284,15 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
}
}
public updateEmbeddableRef(id: string, ref: HTMLIFrameElement | HTMLWebViewElement | null) {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.updateEmbeddableRef, "ExcalidrawView.updateEmbeddableRef", id, ref);
public updateEmbeddableRef(
elementId: string,
ref: HTMLIFrameElement | HTMLWebViewElement | null,
) {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.updateEmbeddableRef, "ExcalidrawView.updateEmbeddableRef", elementId, ref);
if (ref) {
this.embeddableRefs.set(id, ref);
this.embeddableRefs.set(elementId, ref);
} else {
this.embeddableRefs.delete(elementId);
}
}
@@ -6228,10 +6301,15 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
return this.embeddableRefs.get(id);
}
public updateEmbeddableLeafRef(id: string, ref: any) {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.updateEmbeddableLeafRef, "ExcalidrawView.updateEmbeddableLeafRef", id, ref);
public updateEmbeddableLeafRef(
elementId: string,
ref?: any
) {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.updateEmbeddableLeafRef, "ExcalidrawView.updateEmbeddableLeafRef", elementId, ref);
if(ref) {
this.embeddableLeafRefs.set(id, ref);
this.embeddableLeafRefs.set(elementId, ref);
} else {
this.embeddableLeafRefs.delete(elementId);
}
}
+3 -1
View File
@@ -542,6 +542,8 @@ function RenderObsidianView(
try { mobilePatchCleanupRef.current?.(); } catch {}
mobilePatchCleanupRef.current = null;
view.updateEmbeddableLeafRef(element.id);
if(!leafRef.current) {
return;
}
@@ -549,7 +551,7 @@ function RenderObsidianView(
leafRef.current.leaf?.detach();
leafRef.current = null;
}; //cleanup on unmount
}, [linkText, subpath, containerRef]);
}, [linkText, subpath, containerRef, element.id, file.path]);
//--------------------------------------------------------------------------------
//Set colors of the canvas node
+118 -68
View File
@@ -57,7 +57,9 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
onRightEdge: boolean = false;
onBottomEdge: boolean = false;
public containerRef: React.RefObject<HTMLDivElement>;
private view: ExcalidrawView;
private getView(): ExcalidrawView | null {
return this.props.view?.deref() ?? null;
}
componentWillUnmount(): void {
if (this.containerRef.current) {
@@ -65,14 +67,11 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
}
this.setState({ scriptIconMap: null });
this.containerRef = null;
this.view = null;
}
constructor(props: PanelProps) {
super(props);
this.view = props.view.deref();
const react = this.view.packages.react;
const react = this.getView()?.packages.react;
this.containerRef = react.createRef();
this.state = {
visible: props.visible,
@@ -209,84 +208,103 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
}
actionOpenScriptInstallDialog() {
new ScriptInstallPrompt(this.view.plugin).open();
const view = this.getView();
if (!view) return;
new ScriptInstallPrompt(view.plugin).open()
}
actionOpenReleaseNotes() {
new ReleaseNotes(
this.view.app,
this.view.plugin,
PLUGIN_VERSION,
).open();
const view = this.getView();
if (!view) return
new ReleaseNotes(view.app, view.plugin, PLUGIN_VERSION).open();
}
actionConvertExcalidrawToMD() {
this.view.convertExcalidrawToMD();
this.getView()?.convertExcalidrawToMD();
}
actionToggleViewMode() {
const view = this.getView();
if (!view) return;
if (this.state.isPreviewMode) {
this.view.changeTextMode(TextMode.raw);
view.changeTextMode(TextMode.raw);
} else {
this.view.changeTextMode(TextMode.parsed);
view.changeTextMode(TextMode.parsed);
}
}
actionToggleTrayMode() {
const uiModeSettings = new UIModeSettings(this.view.plugin);
uiModeSettings.open();
const plugin = this.getView()?.plugin;
if (!plugin) return;
new UIModeSettings(plugin).open();
}
actionToggleFullscreen() {
const view = this.getView();
if (!view) return;
if (this.state.isFullscreen) {
this.view.exitFullscreen();
view.exitFullscreen();
} else {
this.view.gotoFullscreen();
view.gotoFullscreen();
}
}
actionSearch() {
search(this.view);
const view = this.getView();
if (!view) return;
search(view);
}
actionOCR(e:React.MouseEvent<HTMLButtonElement, MouseEvent>) {
if(!this.view.plugin.settings.taskboneEnabled) {
const view = this.getView();
const plugin = view?.plugin;
if (!view || !plugin) return;
if(!plugin.settings.taskboneEnabled) {
new Notice("Taskbone OCR is not enabled. Please go to plugins settings to enable it.",4000);
return;
}
this.view.plugin.taskbone.getTextForView(this.view, {forceReScan: isWinCTRLorMacCMD(e)});
plugin.taskbone.getTextForView(view, {forceReScan: isWinCTRLorMacCMD(e)});
}
actionOpenLink(e:React.MouseEvent<HTMLButtonElement, MouseEvent>) {
const view = this.getView();
if (!view) return;
const event = new MouseEvent("click", {
ctrlKey: e.ctrlKey || !(DEVICE.isIOS || DEVICE.isMacOS),
metaKey: e.metaKey || (DEVICE.isIOS || DEVICE.isMacOS),
shiftKey: e.shiftKey,
altKey: e.altKey,
});
this.view.handleLinkClick(event, true);
view.handleLinkClick(event, true);
}
actionOpenLinkProperties() {
const view = this.getView();
if (!view) return;
const event = new MouseEvent("click", {
ctrlKey: true,
metaKey: true,
shiftKey: false,
altKey: false,
});
this.view.handleLinkClick(event);
view.handleLinkClick(event);
}
actionForceSave() {
this.view.forceSave();
const view = this.getView();
if (!view) return;
view.forceSave();
}
actionExportLibrary() {
this.view.plugin.exportLibrary();
const plugin = this.getView()?.plugin;
if (!plugin) return;
plugin.exportLibrary();
}
actionExportImage() {
const view = this.view;
const view = this.getView();
if (!view) return;
if(!view.exportDialog) {
view.exportDialog = new ExportDialog(view.plugin, view,view.file);
view.exportDialog.createForm();
@@ -295,69 +313,91 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
}
actionOpenAsMarkdown() {
this.view.openAsMarkdown();
const view = this.getView();
if (!view) return;
view.openAsMarkdown();
}
actionLinkToElement(e:React.MouseEvent<HTMLButtonElement, MouseEvent>) {
const view = this.getView();
if (!view) return;
if(isWinALTorMacOPT(e)) {
openExternalLink("https://youtu.be/yZQoJg2RCKI", this.view.app);
openExternalLink("https://youtu.be/yZQoJg2RCKI", view.app);
return;
}
this.view.copyLinkToSelectedElementToClipboard(
view.copyLinkToSelectedElementToClipboard(
isWinCTRLorMacCMD(e) ? "group=" : (isSHIFT(e) ? "area=" : "")
);
}
actionAddAnyFile() {
const view = this.getView();
const plugin = view?.plugin;
if (!view || !plugin) return;
this.props.centerPointer();
const insertFileModal = new UniversalInsertFileModal(this.view.plugin, this.view);
const insertFileModal = new UniversalInsertFileModal(plugin, view);
insertFileModal.open();
}
actionInsertImage() {
const view = this.getView();
const plugin = view?.plugin;
if (!view || !plugin) return;
this.props.centerPointer();
this.view.plugin.insertImageDialog.start(
this.view,
);
plugin.insertImageDialog.start(view);
}
actionInsertPDF() {
const view = this.getView();
const plugin = view?.plugin;
if (!view || !plugin) return;
this.props.centerPointer();
const insertPDFModal = new InsertPDFModal(this.view.plugin, this.view);
const insertPDFModal = new InsertPDFModal(plugin, view);
insertPDFModal.open();
}
actionInsertMarkdown() {
const view = this.getView();
const plugin = view?.plugin;
if (!view || !plugin) return;
this.props.centerPointer();
this.view.plugin.insertMDDialog.start(
this.view,
);
plugin.insertMDDialog.start(view);
}
actionInsertBackOfNote() {
const view = this.getView();
if (!view) return;
this.props.centerPointer();
this.view.insertBackOfTheNoteCard();
view.insertBackOfTheNoteCard();
}
actionInsertLaTeX(e:React.MouseEvent<HTMLButtonElement, MouseEvent>) {
const view = this.getView();
if (!view) return;
if(isWinALTorMacOPT(e)) {
openExternalLink("https://youtu.be/r08wk-58DPk", this.view.app);
openExternalLink("https://youtu.be/r08wk-58DPk", view.app);
return;
}
this.props.centerPointer();
insertLaTeXToView(this.view);
insertLaTeXToView(view);
}
actionInsertLink() {
const view = this.getView();
const plugin = view?.plugin;
if (!view || !plugin) return;
this.props.centerPointer();
this.view.plugin.insertLinkDialog.start(
this.view.file.path,
(text: string, fontFamily?: 1 | 2 | 3 | 4, save?: boolean) => this.view.addText (text, fontFamily, save),
plugin.insertLinkDialog.start(
view.file.path,
(text: string, fontFamily?: 1 | 2 | 3 | 4, save?: boolean) => view.addText (text, fontFamily, save),
);
}
actionImportSVG(e:React.MouseEvent<HTMLButtonElement, MouseEvent>) {
this.view.plugin.importSVGDialog.start(this.view);
const view = this.getView();
const plugin = view?.plugin;
if (!view || !plugin) return;
plugin.importSVGDialog.start(view);
}
actionCropImage(e:React.MouseEvent<HTMLButtonElement, MouseEvent>) {
@@ -366,8 +406,9 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
}
async actionRunScript(key: string) {
const view = this.view;
const plugin = view.plugin;
const view = this.getView();
const plugin = view?.plugin;
if (!view || !plugin) return;
const f = plugin.app.vault.getAbstractFileByPath(key);
if (f && f instanceof TFile) {
plugin.scriptEngine.executeScript(
@@ -380,9 +421,10 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
}
async actionPinScript(key: string, scriptName: string) {
const view = this.view;
const view = this.getView();
const plugin = view?.plugin;
if (!view || !plugin) return;
const api = view.excalidrawAPI as ExcalidrawImperativeAPI;
const plugin = view.plugin;
await plugin.loadSettings();
const index = plugin.settings.pinnedScripts.indexOf(key)
if(index > -1) {
@@ -412,27 +454,30 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
}
private islandOnPointerDown(event: React.PointerEvent) {
const onDrag = (e: PointerEvent) => {
e.preventDefault();
this.pos1 = this.pos3 - e.clientX;
this.pos2 = this.pos4 - e.clientY;
this.pos3 = e.clientX;
this.pos4 = e.clientY;
this.updatePosition(this.pos2, this.pos1);
};
const view = this.getView();
if (!view) return;
const onPointerUp = () => {
this.view.ownerDocument?.removeEventListener("pointerup", onPointerUp);
this.view.ownerDocument?.removeEventListener("pointermove", onDrag);
};
event.preventDefault();
this.penDownX = this.pos3 = event.clientX;
this.penDownY = this.pos4 = event.clientY;
this.view.ownerDocument.addEventListener("pointerup", onPointerUp);
this.view.ownerDocument.addEventListener("pointermove", onDrag);
const onDrag = (e: PointerEvent) => {
e.preventDefault();
this.pos1 = this.pos3 - e.clientX;
this.pos2 = this.pos4 - e.clientY;
this.pos3 = e.clientX;
this.pos4 = e.clientY;
this.updatePosition(this.pos2, this.pos1);
};
const onPointerUp = () => {
view.ownerDocument?.removeEventListener("pointerup", onPointerUp);
view.ownerDocument?.removeEventListener("pointermove", onDrag);
};
event.preventDefault();
this.penDownX = this.pos3 = event.clientX;
this.penDownY = this.pos4 = event.clientY;
view.ownerDocument.addEventListener("pointerup", onPointerUp);
view.ownerDocument.addEventListener("pointermove", onDrag);
};
render() {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.render,"ToolsPanel.render()");
return (
@@ -688,11 +733,16 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
return "";
}
if(!this.view.plugin._loaded) {
const view = this.getView();
const plugin = view?.plugin;
if (!view || !plugin) return null;
if(!plugin._loaded) {
return null;
}
const downloadedScriptsRoot = `${this.view.plugin.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}/`;
const downloadedScriptsRoot = `${plugin.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}/`;
const filterCondition = (key: string): boolean =>
isDownloaded