Compare commits

...
Author SHA1 Message Date
zsviczian 7b49bded34 2.25.0-beta.4 2026-06-29 20:46:57 +02:00
zsviczian cf916b0da9 LaTeX in markdown images type fixes 2026-06-29 19:24:17 +02:00
zsviczian d4a99e86a8 Merge pull request #2822 from Jmarcos13/fix/mathjax-chtml-markdown-embed
fix: render MathJax CHTML formulas in markdown-embed SVG (#2818)
2026-06-29 18:35:25 +02:00
zsviczian c024f1cfa3 mindmap builder, presets, task date and link relative position change 2026-06-29 18:13:32 +02:00
zsviczian 3c95990d7a WIP MindMap Builder Preset changes 2026-06-29 17:53:56 +02:00
zsviczian b225dd77fe Capture Note update 2026-06-29 17:09:44 +02:00
Jmarcos13 08bbe656ff fix: render MathJax CHTML formulas in markdown-embed SVG (#2818)
Obsidian renders LaTeX via MathJax CHTML output, which relies on a
shared <style id=MJX-CHTML-styles> element injected into the document
head. When convertMarkdownToSVG captures the markdown note as an SVG,
that stylesheet was never included, so all math elements appeared blank.

- After MarkdownRenderer.render(), call mjx.typesetPromise() to ensure
  MathJax has finished typesetting the embedded note.
- Read MathJax CSS rules from the live CSSStyleSheet.cssRules (not
  textContent, which misses per-glyph rules added via insertRule()).
- Scope every CSSStyleRule selector with .excalidraw-md-host to prevent
  MathJax styles from bleeding into surrounding text.
- Inline all @font-face src URLs as base64 data URIs so fonts load
  correctly inside the data:image/svg+xml context.
- Cache the processed stylesheet by rule-count+last-rule fingerprint to
  avoid redundant work across multiple embeds in the same session.
- Inject the scoped stylesheet into both the measurement iframe and the
  final SVG <style> block.

Fixes #2818. Relates to #2282.
2026-06-29 07:05:47 -03:00
zsviczian 395b9591bd fix !important 2026-06-28 22:45:11 +02:00
zsviczian 3137ebc08b resolving type issues 2026-06-28 20:59:23 +02:00
zsviczian 19d668d956 resolved type issues in ObsidianMenu.tsx, solved image cache null obsidian URL, improved tools panel styling. 2026-06-28 20:48:47 +02:00
zsviczian 9fbad17b0d Merge pull request #2821 from zsviczian/fix-terminate-image-generation
Fix: terminate image generation (MarkdownPostProcessor, EmbeddedFilesLoader), addressed image.ts memory leak in Excalidraw package
2026-06-28 17:39:54 +02:00
zsviczian c9c91449a0 style fixes 2026-06-27 23:33:52 +02:00
20 changed files with 1754 additions and 874 deletions

No files matched your search

+245 -28
View File
@@ -67,7 +67,7 @@ The script assembles dynamic "New Section" labels contextualizing the timestamp
7. Switches focus permanently to Note B and automatically executes `ea.viewZoomToElements()` centering the screen precisely on the newly built container.
```js*/
const VERSION = "v260629";
const FRAME_MARGIN = 10;
if (!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.23.8")) {
@@ -150,17 +150,31 @@ const getLucideIconIds = () => {
let suppressEscape = false;
class FolderSuggest extends ea.obsidian.AbstractInputSuggest {
constructor(app, inputEl) {
constructor(app, inputEl, state = null, originFolderPath = "/") {
super(app, inputEl);
this.inputEl = inputEl;
this.state = state;
this.originFolderPath = originFolderPath === "/" ? "" : originFolderPath;
}
getSuggestions(query) {
const folders = app.vault.getAllLoadedFiles()
let folders = app.vault.getAllLoadedFiles()
.filter(f => f instanceof ea.obsidian.TFolder)
.map(f => f.path);
// Filter and map paths relative to the current origin folder
if (this.state && this.state.useRelativeFolder) {
const prefix = this.originFolderPath ? this.originFolderPath + "/" : "";
folders = folders.filter(p => p.startsWith(prefix) || p === this.originFolderPath);
folders = folders.map(p => p === this.originFolderPath ? "" : p.substring(prefix.length));
}
return folders.filter(p => p.toLowerCase().includes(query.toLowerCase()));
}
renderSuggestion(value, el) { el.setText(value); }
renderSuggestion(value, el) {
// Display an indicator for the current folder if left empty in relative mode
const display = value === "" && this.state && this.state.useRelativeFolder ? "./ (Current Folder)" : value;
el.setText(display || "/");
}
selectSuggestion(value) {
this.inputEl.value = value;
this.inputEl.dispatchEvent(new Event("input"));
@@ -704,7 +718,7 @@ async function injectVisualFormat(target_ea, targetX, targetY, sectionRawText, t
// Conditionally add dynamic links back to the originating element and (if applicable) the DNP
let linkStr = "";
if (embeddedElementId && ontologyAction && originFilePath) {
linkStr += `(${ontologyAction}::[[${originFilePath}#^${embeddedElementId}]])`;
linkStr += `(${ontologyAction}::[[${originFilePath}#^group=${embeddedElementId}]])`;
}
if (!isCurrentDNP) {
const frameOntology = settings.frameOntology || "note";
@@ -849,7 +863,7 @@ async function injectMarkdownFormat(file, target_ea, targetX, targetY, sectionRa
if (embeddedElementId && ontologyAction && originFilePath) {
const originFile = app.vault.getAbstractFileByPath(originFilePath);
const originLinkpath = originFile ? getObsidianLinkpath(originFile, file.path) : originFilePath.replace(/\.md$/i, "");
linkStr += ` (${ontologyAction}::[[${originLinkpath}#^${embeddedElementId}]])`;
linkStr += ` (${ontologyAction}::[[${originLinkpath}#^group=${embeddedElementId}]])`;
}
if (!isCurrentDNP) {
const frameOntology = settings.frameOntology || "note";
@@ -1078,10 +1092,10 @@ async function injectIntoOriginView(originView, activeElement, format, actionTyp
const isEmbeddable = actionType === "CAPTURE_HERE" || !isMarkdownImage;
if (isEmbeddable) {
// Markdown Format + Embeddable: Multiple links
eaEl.link = `(${ontologyAction}:: [[${linkpath}#${refPath}]] [[${linkpath}#^${frameID}]])`;
eaEl.link = `(${ontologyAction}:: [[${linkpath}#${refPath}]] [[${linkpath}#^group=${frameID}]])`;
} else {
// Markdown Format + Static Image: Element ID link only
eaEl.link = `(${ontologyAction}:: [[${linkpath}#^${frameID}]])`;
eaEl.link = `(${ontologyAction}:: [[${linkpath}#^group=${frameID}]])`;
}
}
}
@@ -1310,8 +1324,15 @@ async function start() {
return;
}
// Set the folder from the modal box
const targetFolder = (customFolder !== undefined && customFolder !== "") ? customFolder : opt.folder;
// Set the folder from the modal box (and apply relative behaviors)
let targetFolder = (customFolder !== undefined && customFolder !== "") ? customFolder : opt.folder;
if (captureData.useRelativeFolder) {
const baseFolder = originView.file.parent.path;
if (baseFolder !== "/") {
targetFolder = targetFolder ? `${baseFolder}/${targetFolder}` : baseFolder;
}
}
const folder = ea.obsidian.normalizePath(targetFolder);
// 3. Assemble WikiLink and File Path
@@ -1343,13 +1364,13 @@ async function start() {
}
}
// Handle Existing File Conflict Workflow
// Handle Existing File Conflict Workflow (Bypasses rename warning if type matches)
if (fileTarget) {
const existingType = await detectNoteType(fileTarget);
const hasNoteType = existingType === noteType;
const hasPrefix = opt.prefix ? fileTarget.basename.startsWith(opt.prefix) : true;
if (!hasNoteType || !hasPrefix) {
if (!hasNoteType) {
const conflictDecision = await resolveExistingFileConflict(fileTarget, hasNoteType, hasPrefix, opt.prefix);
if (!conflictDecision) return;
@@ -1379,9 +1400,9 @@ async function start() {
let folderPath = (opt.type === "folder") ? `${folder}/${cleanFilename}` : folder;
const formattedFolderPath = folderPath ? folderPath.replace(/^\/+/, "") + "/" : "";
const format = app.vault.getConfig("newLinkFormat");
const fmt = app.vault.getConfig("newLinkFormat");
let linkpath = `${formattedFolderPath}${targetBasename}`;
if (format === "shortest") {
if (fmt === "shortest") {
const matches = app.vault.getFiles().filter(f => f.basename === targetBasename);
if (matches.length === 0) {
linkpath = targetBasename;
@@ -1399,7 +1420,7 @@ async function start() {
return;
}
// 4. Create File if new (File exists in memory for linking)
// 4. Create File if new
const file = await ensureTargetFileExists(folder, cleanFilename, fname, opt, noteType);
if (actionType === "ADD_LINK_CREATE") {
@@ -1546,15 +1567,19 @@ function buildCaptureFolderBox(contentEl, state) {
.setName("Folder")
.setDesc("Target directory for the note");
let folderInputComp;
const currentFolderPath = ea.targetView ? ea.targetView.file.parent.path : "/";
folderSetting.addText(text => {
state.ui.folderInput = text;
folderInputComp = text;
text.inputEl.style.width = "100%";
state.isProgrammaticUpdate = true;
text.setValue(state.initialFolder);
state.isProgrammaticUpdate = false;
new FolderSuggest(app, text.inputEl);
new FolderSuggest(app, text.inputEl, state, currentFolderPath);
// Track manual edits by the user (ignoring programmatic setValue)
text.inputEl.addEventListener("input", () => {
@@ -1563,6 +1588,49 @@ function buildCaptureFolderBox(contentEl, state) {
}
});
});
// Relative vs Absolute folder path toggle
folderSetting.addExtraButton(btn => {
state.ui.folderToggleBtn = btn;
const updateIcon = () => {
btn.setIcon(state.useRelativeFolder ? "folder-dot" : "folder-lock");
btn.setTooltip(state.useRelativeFolder ? "In current folder or subfolder" : "Fixed absolute folder path");
};
updateIcon();
btn.onClick(() => {
state.useRelativeFolder = !state.useRelativeFolder;
settings.useRelativeFolder = state.useRelativeFolder; // Save global preference
ea.setScriptSettings(settings);
updateIcon();
// Handle path transformation automatically
state.isProgrammaticUpdate = true;
let currentVal = folderInputComp.getValue().trim();
const prefix = currentFolderPath === "/" ? "" : currentFolderPath;
if (state.useRelativeFolder) {
// Absolute to Relative
if (currentVal === prefix) {
folderInputComp.setValue("");
} else if (currentVal.startsWith(prefix + "/")) {
folderInputComp.setValue(currentVal.substring(prefix.length + 1));
} else {
folderInputComp.setValue(""); // Does not fall within current path, clear
}
} else {
// Relative to Absolute
if (currentVal === "") {
folderInputComp.setValue(prefix);
} else {
folderInputComp.setValue(prefix ? `${prefix}/${currentVal}` : currentVal);
}
}
state.isProgrammaticUpdate = false;
state.ui.folderInput.inputEl.dispatchEvent(new Event("input")); // Re-evaluate suggester
});
});
}
function buildCaptureSearchBox(contentEl, state, callbacks) {
@@ -1747,12 +1815,12 @@ function buildCaptureLinkTypeSelector(contentEl, state, callbacks) {
state.selectedNoteType = selectedNoteType;
}
const linkTypeRow = new ea.obsidian.Setting(contentEl).setName("Link Type");
linkTypeRow.controlEl.addClass("link-type-row-control");
const iconPreviewSpan = linkTypeRow.controlEl.createSpan();
const noteTypeRow = new ea.obsidian.Setting(contentEl).setName("Type");
noteTypeRow.controlEl.addClass("link-type-row-control");
const iconPreviewSpan = noteTypeRow.controlEl.createSpan();
state.ui.iconPreviewSpan = iconPreviewSpan;
linkTypeRow.addDropdown(dropdown => {
noteTypeRow.addDropdown(dropdown => {
state.ui.dropdownComponent = dropdown;
noteTypeKeys.forEach(k => dropdown.addOption(k, k));
dropdown.setValue(selectedNoteType);
@@ -1772,6 +1840,11 @@ function buildCaptureLinkTypeSelector(contentEl, state, callbacks) {
if (opt && opt.folder !== undefined && state.ui.folderInput) {
state.isProgrammaticUpdate = true;
state.ui.folderInput.setValue(opt.folder);
state.useRelativeFolder = !!opt.useRelativeFolder;
if (state.ui.folderToggleBtn) {
state.ui.folderToggleBtn.setIcon(state.useRelativeFolder ? "folder-dot" : "folder-lock");
state.ui.folderToggleBtn.setTooltip(state.useRelativeFolder ? "In current folder or subfolder" : "Fixed absolute folder path");
}
state.isProgrammaticUpdate = false;
}
}
@@ -1780,7 +1853,7 @@ function buildCaptureLinkTypeSelector(contentEl, state, callbacks) {
});
// Add a button to manually pull the target directory from the active Note Type
linkTypeRow.addExtraButton(btn => {
noteTypeRow.addExtraButton(btn => {
state.ui.resetFolderBtn = btn;
btn.setIcon("folder-sync")
.setTooltip("Apply folder from selected Note Type")
@@ -1789,12 +1862,54 @@ function buildCaptureLinkTypeSelector(contentEl, state, callbacks) {
if (opt && opt.folder !== undefined && state.ui.folderInput) {
state.isProgrammaticUpdate = true;
state.ui.folderInput.setValue(opt.folder);
state.useRelativeFolder = !!opt.useRelativeFolder;
if (state.ui.folderToggleBtn) {
state.ui.folderToggleBtn.setIcon(state.useRelativeFolder ? "folder-dot" : "folder-lock");
state.ui.folderToggleBtn.setTooltip(state.useRelativeFolder ? "In current folder or subfolder" : "Fixed absolute folder path");
}
state.isProgrammaticUpdate = false;
state.folderManuallyEdited = false;
}
});
});
// 4.1 On-the-spot Note Type creation
noteTypeRow.addExtraButton(btn => {
btn.setIcon("plus")
.setTooltip("Create new Note Type")
.onClick(() => {
const tempId = "New Type " + (Object.keys(settings.noteTypes).length + 1);
settings.noteTypes[tempId] = {
folder: "",
useRelativeFolder: state.useRelativeFolder,
type: "file",
template: settings.baseTemplateForNewNoteTypes || "",
prefix: "",
icon: "file",
ontology: { default: "referencing", actions: ["referencing"] }
};
// Passed with isNew = true to gracefully handle escape/cancel deletions
openEditNoteTypeModal(tempId, (finalName) => {
ea.setScriptSettings(settings);
const targetName = finalName || tempId;
// Refresh dropdown options
const selectEl = state.ui.dropdownComponent.selectEl;
while(selectEl.options.length > 0) selectEl.remove(0);
Object.keys(settings.noteTypes).sort().forEach(k => state.ui.dropdownComponent.addOption(k, k));
// Select newly created type
state.selectedNoteType = targetName;
settings.lastSelectedNoteType = targetName;
state.ui.dropdownComponent.setValue(targetName);
callbacks.updateIconPreview();
callbacks.updateOntologyDropdown();
}, true);
});
});
callbacks.updateIconPreview();
}
@@ -1862,6 +1977,7 @@ function buildCaptureFooter(contentEl, state, modal) {
state.finalData = {
filename: val,
folder: folderVal,
useRelativeFolder: state.useRelativeFolder, // Append relative setting state
noteType: state.selectedNoteType,
format: state.selectedFormat,
ontologyAction: state.selectedOntology,
@@ -1904,7 +2020,22 @@ async function openCaptureModal(initialSearchValue) {
modal.modalEl.style.width = "480px";
modal.modalEl.style.maxWidth = "100%";
modal.modalEl.classList.add("excalidraw-capture-note-modal");
modal.titleEl.setText("Capture Contextual Note");
// Clear default title text and convert to a flex container to align elements
modal.titleEl.empty();
modal.titleEl.style.display = "flex";
modal.titleEl.style.justifyContent = "space-between";
modal.titleEl.style.alignItems = "center";
modal.titleEl.style.width = "100%";
// Add Main Title
modal.titleEl.createSpan({ text: "Capture Contextual Note" });
// Add right-aligned Version string
modal.titleEl.createSpan({
text: VERSION,
attr: { style: "font-size: 0.5em; color: var(--text-muted); font-weight: normal; margin-right: 8px;" }
});
let initialFolder = "";
let initialFilename = initialSearchValue || "";
@@ -1970,6 +2101,7 @@ async function openCaptureModal(initialSearchValue) {
const state = {
finalData: null,
initialFolder,
useRelativeFolder: settings.useRelativeFolder || false,
initialSearchValue: initialFilename,
folderManuallyEdited: false, // Start false so we can auto-update if they change to a new file
isProgrammaticUpdate: false,
@@ -2041,6 +2173,11 @@ async function openCaptureModal(initialSearchValue) {
if (opt && opt.folder !== undefined) {
state.isProgrammaticUpdate = true;
state.ui.folderInput.setValue(opt.folder);
state.useRelativeFolder = !!opt.useRelativeFolder;
if (state.ui.folderToggleBtn) {
state.ui.folderToggleBtn.setIcon(state.useRelativeFolder ? "folder-dot" : "folder-lock");
state.ui.folderToggleBtn.setTooltip(state.useRelativeFolder ? "In current folder or subfolder" : "Fixed absolute folder path");
}
state.isProgrammaticUpdate = false;
}
}
@@ -2393,6 +2530,18 @@ function buildNoteTypesSection(contentEl) {
const noteTypesSection = contentEl.createEl("details", { cls: "setting-sub-section" });
noteTypesSection.createEl("summary", { text: "Note Types & Custom Ontologies" });
const baseTemplateContainer = noteTypesSection.createDiv({ attr: { style: "margin-bottom: 15px;" } });
new ea.obsidian.Setting(baseTemplateContainer)
.setName("Base Template for New Ontologies")
.setDesc("A generic template used automatically when creating new note types on the fly.")
.addText(text => {
text.setValue(settings.baseTemplateForNewNoteTypes || "").onChange(val => {
settings.baseTemplateForNewNoteTypes = val;
ea.setScriptSettings(settings);
});
new TemplateSuggest(app, text.inputEl);
});
const addBtnContainer = noteTypesSection.createDiv({ cls: "flex-row-spaced", attr: { style: "margin-bottom:15px;" } });
addBtnContainer.createEl("span", { text: "Manage your note types:" });
const addBtn = addBtnContainer.createEl("button", { text: "Add", cls: "mod-cta" });
@@ -2404,16 +2553,19 @@ function buildNoteTypesSection(contentEl) {
const tempId = "New Type " + (Object.keys(settings.noteTypes).length + 1);
settings.noteTypes[tempId] = {
folder: "",
useRelativeFolder: false,
type: "file",
template: "",
template: settings.baseTemplateForNewNoteTypes || "",
prefix: "",
icon: "file",
ontology: { default: "referencing", actions: ["referencing"] }
};
// Passed with isNew = true to gracefully handle escape/cancel deletions
openEditNoteTypeModal(tempId, () => {
ea.setScriptSettings(settings);
refreshCallback();
});
}, true);
});
refreshCallback();
@@ -2462,12 +2614,13 @@ function openSettingsModal() {
// -------------------------------------------------------------
// 7. UI: Detailed Single Note Type Editor Modal (Secondary Modal)
// -------------------------------------------------------------
function openEditNoteTypeModal(noteTypeKey, saveCallback) {
function openEditNoteTypeModal(noteTypeKey, saveCallback, isNew = false) {
const modal = new ea.obsidian.Modal(app);
modal.titleEl.setText(`Configure Note Type`);
const typeConfig = settings.noteTypes[noteTypeKey];
let originalKeyName = noteTypeKey;
let isSaved = false;
// Fetch ExcaliBrain ontology actions
let brainOntologies = [];
@@ -2524,15 +2677,67 @@ function openEditNoteTypeModal(noteTypeKey, saveCallback) {
settings.noteTypes[finalName] = typeConfig;
delete settings.noteTypes[originalKeyName];
}
saveCallback();
isSaved = true;
saveCallback(finalName);
modal.close();
});
let folderInputComp;
const currentFolderPath = ea.targetView ? ea.targetView.file.parent.path : "/";
new ea.obsidian.Setting(contentEl)
.setName("Target Vault Folder")
.addText(text => {
folderInputComp = text;
text.setValue(typeConfig.folder).onChange(val => { typeConfig.folder = val; });
new FolderSuggest(app, text.inputEl);
// Passing typeConfig directly ensures the Suggester inherits the toggle boolean accurately
new FolderSuggest(app, text.inputEl, typeConfig, currentFolderPath);
typeConfig._tempTextInput = text.inputEl;
})
.addExtraButton(btn => {
const updateIcon = () => {
btn.setIcon(typeConfig.useRelativeFolder ? "folder-dot" : "folder-lock");
btn.setTooltip(typeConfig.useRelativeFolder ? "Relative to current note's folder" : "Absolute folder path");
};
updateIcon();
btn.onClick(() => {
typeConfig.useRelativeFolder = !typeConfig.useRelativeFolder;
updateIcon();
// Handle path transformation automatically
let currentVal = folderInputComp.getValue().trim();
const prefix = currentFolderPath === "/" ? "" : currentFolderPath;
if (typeConfig.useRelativeFolder) {
// Absolute to Relative
if (currentVal === prefix) {
folderInputComp.setValue("");
typeConfig.folder = "";
} else if (currentVal.startsWith(prefix + "/")) {
const newRelative = currentVal.substring(prefix.length + 1);
folderInputComp.setValue(newRelative);
typeConfig.folder = newRelative;
} else {
folderInputComp.setValue("");
typeConfig.folder = "";
}
} else {
// Relative to Absolute
if (currentVal === "") {
folderInputComp.setValue(prefix);
typeConfig.folder = prefix;
} else {
const newAbsolute = prefix ? `${prefix}/${currentVal}` : currentVal;
folderInputComp.setValue(newAbsolute);
typeConfig.folder = newAbsolute;
}
}
if (typeConfig._tempTextInput) {
typeConfig._tempTextInput.dispatchEvent(new Event("input"));
}
});
});
new ea.obsidian.Setting(contentEl)
@@ -2543,9 +2748,16 @@ function openEditNoteTypeModal(noteTypeKey, saveCallback) {
new TemplateSuggest(app, text.inputEl);
});
// Strip unsafe characters to guarantee OS-level file creation compatibility
new ea.obsidian.Setting(contentEl)
.setName("File Prefix")
.addText(text => text.setValue(typeConfig.prefix).onChange(val => { typeConfig.prefix = val; }));
.addText(text => text.setValue(typeConfig.prefix).onChange(val => {
const cleaned = val.replace(/[\\/:"*?<>|]/g, '');
if (cleaned !== val) {
text.setValue(cleaned);
}
typeConfig.prefix = cleaned;
}));
const iconSetting = new ea.obsidian.Setting(contentEl)
.setName("Lucide Icon");
@@ -2673,6 +2885,11 @@ function openEditNoteTypeModal(noteTypeKey, saveCallback) {
};
modal.onClose = () => {
// If the creation workflow is abandoned before explicitly saving, erase the orphaned entry
if (isNew && !isSaved) {
delete settings.noteTypes[originalKeyName];
ea.setScriptSettings(settings);
}
setTimeout(() => { delete modal; });
};
modal.open();
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -649,7 +649,7 @@
},
{
"fname": "Mindmap Builder.md",
"mtime": 1781460603530
"mtime": 1782749555972
},
{
"fname": "Mindmap Builder.svg",
@@ -665,7 +665,7 @@
},
{
"fname": "Capture Note.md",
"mtime": 1780986335837
"mtime": 1782745696796
},
{
"fname": "Capture Note.svg",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.25.0-beta.2",
"version": "2.25.0-beta.4",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+4 -4
View File
@@ -13,7 +13,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.110",
"@zsviczian/excalidraw": "0.18.111",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -5232,9 +5232,9 @@
"license": "MIT"
},
"node_modules/@zsviczian/excalidraw": {
"version": "0.18.110",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.110.tgz",
"integrity": "sha512-R/5aZ/6Sbk3O/TI0O28kA/KzyeXC61NDXFVjIi5857Lmx2Gvf1Xva3APKoqsnBwiR2aNjB92qBE86AiUyvxmhA==",
"version": "0.18.111",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.111.tgz",
"integrity": "sha512-Y0rHChvXRDVafpwxZ10CoKeV2U7EkhpNcC3xa4M29xEfFPH4fdFhbxwxODBg4aqMzBXD36MD1SSo+MDN3EXahg==",
"license": "MIT",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
+1 -1
View File
@@ -29,7 +29,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.110",
"@zsviczian/excalidraw": "0.18.111",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
+1 -1
View File
@@ -219,7 +219,7 @@ export const URL_REGISTRY = {
"https://community.obsidian.md/plugins/obsidian-excalidraw-plugin",
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM: defineUrl("https://github.com/", UrlPurpose.RELEASE_LOG),
GITHUB_COM: defineUrl("https://github.com", UrlPurpose.RELEASE_LOG),
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES: defineUrl(
"https://github.com/excalidraw/excalidraw/issues",
UrlPurpose.RELEASE_LOG,
+1 -1
View File
@@ -92,7 +92,7 @@ const discardImage = (el: Element | null) => {
: Array.from(el.querySelectorAll("img"));
images.forEach((img) => {
if (img.src.startsWith("blob:")) {
URL.revokeObjectURL(img.src);
getImageCache().releaseObsidianURL(img.src);
}
// Instantly aborts the browser's background V8 image decoder task
img.src = "";
+4
View File
@@ -1197,6 +1197,10 @@ export default {
SELECT_TO_EMBED: "Select the drawing to insert into active document.",
SELECT_MD: "Select the markdown document you want to insert",
//ToolsPanel.tsx
TASKBON_NOT_ENABLED:
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
//SelectCard.ts
TYPE_SECTION: "Type section name to select.",
SELECT_SECTION_OR_TYPE_NEW:
+2
View File
@@ -29,6 +29,8 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
## Fixed
- BUG: Double Click to edit from Obsidian in Live preview doesn't work anymore [#2813](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2813)
- Edge cases leading to memory leak and CPU overload when closing a markdown preview while embedded Excalidraw drawings are loading, or closing an ExcalidrawView, while nested images are still loading.
- Markdown-embed-as-image snapshot drops MathJax/LaTeX output [#2818](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2818), [#2282](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2282) 🙏[@Jmarcos13](${URLs.GITHUB_COM}/Jmarcos13) via [#2822](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2822)
- Fixed the "Customize the Embedded File Link" action. If you change the dimensions of the markdown image or the pdf page reference number, the image immediately updates in the scene. You can also use this feature to swap out images e.g. a png icon to an SVG icon. Default shortcut is CTRL+WIN+Click or CMD+Control+Click on the image element.
`,
"2.24.2": `
## Fixed
+184 -31
View File
@@ -18,7 +18,8 @@ import {
mainDocument,
} from "../constants/constants";
import { createSVG } from "src/utils/excalidrawAutomateUtils";
import { EquationItem, ExcalidrawData, getTransclusion } from "./ExcalidrawData";
import type { EquationItem } from "./ExcalidrawData";
import { ExcalidrawData, getTransclusion } from "./ExcalidrawData";
import { t } from "../lang/helpers";
import { tex2dataURL } from "./LaTeX";
import ExcalidrawPlugin from "../core/main";
@@ -74,7 +75,7 @@ import {
isInstanceOfHTMLImageElement,
isInstanceOfSVGElement,
} from "src/utils/typechecks";
import { strictArrayBuffer } from "src/utils/obsidianUtils";
import { getSafeFrontmatter, strictArrayBuffer } from "src/utils/obsidianUtils";
//An ugly workaround for the following situation.
//File A is a markdown file that has an embedded Excalidraw file B
@@ -996,10 +997,7 @@ export class EmbeddedFilesLoader {
const equations = excalidrawData.getEquationEntries();
while (!(equationItem = equations.next()).done) {
const eiValue = equationItem.value as [FileId, EquationItem];
if (
fileIDWhiteList &&
!fileIDWhiteList.has(eiValue[0])
) {
if (fileIDWhiteList && !fileIDWhiteList.has(eiValue[0])) {
continue;
}
const equation = eiValue[1];
@@ -1057,12 +1055,17 @@ export class EmbeddedFilesLoader {
if (result?.files) {
for (const key in result.files) {
const fileData = {
...result.files[key],
...(result.files as Record<string, { dataURL: string }>)[
key
],
id: element.fileId,
created: Date.now(),
hasSVGwithBitmap: false,
shouldScale: true,
size: await getImageSize(result.files[key].dataURL),
size: await getImageSize(
(result.files as Record<string, { dataURL: string }>)[key]
.dataURL,
),
} as FileData;
files[batch].push(fileData);
}
@@ -1079,7 +1082,7 @@ export class EmbeddedFilesLoader {
depth,
inFile: null,
hasSVGwithBitmap: false,
elements: result.elements,
elements: result.elements as ExcalidrawElement[],
});
if (this.terminate) {
return;
@@ -1123,7 +1126,7 @@ export class EmbeddedFilesLoader {
);
try {
addFiles(batchFiles, this.isDark, false);
} catch (e) {
} catch (e: unknown) {
errorlog({ where: "EmbeddedFileLoader.loadSceneFiles", error: e });
}
files.push([]);
@@ -1153,7 +1156,7 @@ export class EmbeddedFilesLoader {
try {
//in try block because by the time files are loaded the user may have closed the view
addFiles(batchFiles, this.isDark, true);
} catch (e) {
} catch (e: unknown) {
errorlog({ where: "EmbeddedFileLoader.loadSceneFiles", error: e });
}
} finally {
@@ -1406,8 +1409,12 @@ export class EmbeddedFilesLoader {
canvas.height = 0;
return result;
}
} catch (e) {
console.log(e);
} catch (e: unknown) {
errorlog({
where: "EmbeddedFileLoader.pdfToDataURL",
uid: this.uid,
error: e,
});
return [null, null, null, null, false];
}
}
@@ -1435,14 +1442,13 @@ export class EmbeddedFilesLoader {
//2.
//get styles
const fileCache = plugin.app.metadataCache.getFileCache(file);
let fontDef: string;
let fontName = plugin.settings.mdFont;
if (
fileCache?.frontmatter &&
Boolean(fileCache.frontmatter[FRONTMATTER_KEYS.font.name])
) {
fontName = fileCache.frontmatter[FRONTMATTER_KEYS.font.name];
const safeFrontmatter = getSafeFrontmatter(fileCache?.frontmatter);
if (safeFrontmatter[FRONTMATTER_KEYS.font.name]) {
fontName = safeFrontmatter[FRONTMATTER_KEYS.font.name];
}
switch (fontName) {
case "Virgil":
@@ -1484,14 +1490,10 @@ export class EmbeddedFilesLoader {
text = text.replace(/banner:\s*.*/, ""); //patch https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/814
}
const fontColor = fileCache?.frontmatter
? (fileCache.frontmatter[FRONTMATTER_KEYS["font-color"].name] ??
plugin.settings.mdFontColor)
: plugin.settings.mdFontColor;
const fmFontColor = safeFrontmatter[FRONTMATTER_KEYS["font-color"].name];
const fontColor = fmFontColor ?? plugin.settings.mdFontColor;
let style: string = safeFrontmatter[FRONTMATTER_KEYS["md-css"].name] ?? "";
let style = fileCache?.frontmatter
? (fileCache.frontmatter[FRONTMATTER_KEYS["md-css"].name] ?? "")
: "";
let frontmatterCSSisAfile = false;
if (style && style !== "") {
const f = plugin.app.metadataCache.getFirstLinkpathDest(style, file.path);
@@ -1514,10 +1516,9 @@ export class EmbeddedFilesLoader {
}
}
const borderColor = fileCache?.frontmatter
? (fileCache.frontmatter[FRONTMATTER_KEYS["border-color"].name] ??
plugin.settings.mdBorderColor)
: plugin.settings.mdBorderColor;
const borderColor: string =
safeFrontmatter[FRONTMATTER_KEYS["border-color"].name] ??
plugin.settings.mdBorderColor;
if (borderColor && borderColor !== "" && !style.match(/svg/i)) {
style += `svg{border:2px solid;color:${borderColor};transform:scale(.95)}`;
@@ -1570,6 +1571,35 @@ export class EmbeddedFilesLoader {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
}
// MathJax typesetting may complete asynchronously after MarkdownRenderer.render() resolves.
// Awaiting typesetPromise ensures all mjx-container elements are fully populated before
// we clone the DOM into the iframe or serialize to SVG.
const mjx = window.MathJax;
if (mjx?.typesetPromise) {
try {
await mjx.typesetPromise([mdDIV]);
} catch (e: unknown) {
errorlog({
where: "EmbeddedFileLoader.convertMarkdownToSVG",
message:
"Non-fatal: proceed with whatever state MathJax left the DOM in.",
error: e,
});
}
}
// Capture the MathJax CHTML stylesheet AFTER typesetting so all per-glyph rules
// are present. We pass the live <style> element (not textContent) because MathJax
// adds rules via sheet.insertRule(), which updates sheet.cssRules but never
// reflects in textContent — reading textContent would miss every glyph except
// any that happened to be in the element's original authored content.
const mjxCHtmlStyleContent = await scopeAndInlineMathJaxCSS(
mainDocument.getElementById(
"MJX-CHTML-styles",
) as HTMLStyleElement | null,
".excalidraw-md-host",
);
mdDIV
.querySelectorAll(":scope > *[class^='frontmatter']")
.forEach((el) => mdDIV.removeChild(el));
@@ -1625,10 +1655,16 @@ export class EmbeddedFilesLoader {
const iframeDoc = iframe.contentWindow.document;
if (style) {
const styleEl = iframeDoc.createElement("style");
styleEl.type = "text/css";
setStyleText(styleEl, style);
iframeDoc.head.appendChild(styleEl);
}
// Inject the MathJax CHTML stylesheet into the iframe so that mjx-* custom elements
// are styled correctly when measuring scroll height and computing inline styles.
if (mjxCHtmlStyleContent) {
const mjxStyleEl = iframeDoc.createElement("style");
setStyleText(mjxStyleEl, mjxCHtmlStyleContent);
iframeDoc.head.appendChild(mjxStyleEl);
}
const stylingDIV = iframeDoc.importNode(mdDIV, true);
iframeDoc.body.appendChild(stylingDIV);
const footerDIV = createDiv();
@@ -1703,10 +1739,15 @@ export class EmbeddedFilesLoader {
}
const xml = new XMLSerializer().serializeToString(mdDIV);
// Prepend the MathJax CHTML stylesheet to the SVG's embedded <style> block so that
// mjx-container elements inside the <foreignObject> render correctly.
const finalStyle = mjxCHtmlStyleContent
? mjxCHtmlStyleContent + "\n" + style
: style;
const finalSVG = svg(
xml,
'<div class="excalidraw-md-footer"></div>',
style,
finalStyle,
);
plugin.ea.mostRecentMarkdownSVG = parser.parseFromString(
finalSVG,
@@ -1719,6 +1760,118 @@ export class EmbeddedFilesLoader {
}
}
// ─── MathJax CHTML stylesheet helpers ────────────────────────────────────────
// Cache keyed by "<rule-count>:<last-rule-text>" — cheap to compute and sufficient
// for MathJax's append-only glyph stylesheet: every new character adds a new rule
// at the end, so a change in count or last entry signals a cache miss.
const mjxScopedStyleCache = new Map<string, Promise<string>>();
/**
* Fetches a font file and returns it as a base64 data URI.
* This is necessary because fonts referenced by relative/app:// URLs in
* @font-face rules are blocked when the SVG is loaded as a data: URL.
*/
const fetchFontAsDataURI = async (url: string): Promise<string | null> => {
if (url.startsWith("data:")) return url;
try {
const res = await fetch(url);
if (!res.ok) return null;
const buf = await res.arrayBuffer();
const bytes = new Uint8Array(buf);
// Build base64 in 8 KB chunks to avoid call-stack overflow on large fonts.
let binary = "";
const chunk = 8192;
for (let i = 0; i < bytes.length; i += chunk) {
binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
}
const ext = url.split("?")[0].split(".").pop()?.toLowerCase() ?? "";
const mime =
ext === "woff2"
? "font/woff2"
: ext === "woff"
? "font/woff"
: ext === "ttf"
? "font/ttf"
: ext === "otf"
? "font/otf"
: "font/woff2";
return `data:${mime};base64,${btoa(binary)}`;
} catch {
return null;
}
};
/**
* Processes the live MathJax CHTML <style> element so it is safe to embed in the SVG.
*
* WHY we accept the element instead of its textContent: MathJax adds per-glyph CSS
* rules via sheet.insertRule(), which updates sheet.cssRules but NOT the element's
* textContent. Reading textContent would therefore miss every glyph rule added after
* initial load, explaining why only the very last character in a formula appeared.
*
* What this function does:
* 1. Scopes every style rule to `scope` (e.g. ".excalidraw-md-host") so that broad
* selectors cannot bleed outside the math container and underline regular text.
* 2. Inlines every @font-face src URL as a base64 data URI so the mathematical fonts
* (needed for correct radical-bar vertical metrics) load inside a data: SVG, where
* the browser blocks all external URL references for security reasons.
*
* Results are cached by rule-count + last-rule text to avoid re-fetching fonts on
* every embed of the same formula set.
*/
const scopeAndInlineMathJaxCSS = (
styleEl: HTMLStyleElement | null,
scope: string,
): Promise<string> => {
const sheet = styleEl?.sheet;
if (!sheet?.cssRules.length) return Promise.resolve("");
// Cheap cache key: rule count + last rule text (MathJax only ever appends rules).
const lastRule = sheet.cssRules[sheet.cssRules.length - 1]?.cssText ?? "";
const cacheKey = `${sheet.cssRules.length}:${lastRule.slice(0, 80)}`;
const cached = mjxScopedStyleCache.get(cacheKey) ?? null;
if (cached !== null) return cached;
const work = (async (): Promise<string> => {
// Snapshot the live rules array before any await so we process the state
// that existed when typesetPromise resolved, not a later state.
const rules = Array.from(sheet.cssRules);
let result = "";
for (const rule of rules) {
if (rule instanceof CSSFontFaceRule) {
// Inline each src URL as base64 so fonts work inside data: SVGs.
let ruleText = rule.cssText;
const urlRe = /url\(["']?([^"')]+)["']?\)/g;
for (const m of [...ruleText.matchAll(urlRe)]) {
const dataURI = await fetchFontAsDataURI(m[1]);
if (dataURI) ruleText = ruleText.replace(m[0], `url("${dataURI}")`);
}
result += ruleText + "\n";
} else if (rule instanceof CSSStyleRule) {
// Prefix every selector with `scope` so rules cannot bleed to elements
// outside the math container (e.g. causing underlines on regular text).
const sr = rule;
const scoped = sr.selectorText
.split(",")
.map((s) => `${scope} ${s.trim()}`)
.join(", ");
result += `${scoped} { ${sr.style.cssText} }\n`;
} else {
// @media, @keyframes, @supports, etc. — pass through unchanged.
result += rule.cssText + "\n";
}
}
return result;
})();
mjxScopedStyleCache.set(cacheKey, work);
return work;
};
// ─────────────────────────────────────────────────────────────────────────────
const getSVGData = async (
app: App,
file: TFile,
+21 -1
View File
@@ -409,7 +409,7 @@ class ImageCache {
new Promise<undefined>((_, reject) =>
window.setTimeout(() => {
reject(new Error("Timeout while retrieving cache data"));
}, 100),
}, 200),
),
]);
this.fullyInitialized = true;
@@ -451,6 +451,7 @@ class ImageCache {
console.error(
"unexpected error in getResolvedCacheData",
this.getResolvedCacheData.bind(this),
key_,
error,
);
return undefined;
@@ -477,6 +478,9 @@ class ImageCache {
if (cacheData.svg) {
return convertSVGStringToElement(cacheData.svg);
}
if (!cacheData.blob) {
return undefined;
}
if (this.obsidanURLCache.has(key)) {
return this.obsidanURLCache.get(key);
}
@@ -485,6 +489,22 @@ class ImageCache {
return obsidianURL;
}
public releaseObsidianURL(url: string): void {
if (!url || !this.obsidanURLCache) {
return;
}
const keysToDelete: string[] = [];
this.obsidanURLCache.forEach((cachedUrl, key) => {
if (cachedUrl === url) {
keysToDelete.push(key);
}
});
keysToDelete.forEach((key) => this.obsidanURLCache.delete(key));
URL.revokeObjectURL(url);
}
public async getBAKFromCache(filepath: string): Promise<BackupData | null> {
if (!this.isReady()) {
return null; // Database not initialized yet
+3
View File
@@ -171,6 +171,9 @@ declare global {
React?: typeof import("react");
ReactDOM?: typeof import("react-dom/client");
ExcalidrawLib?: typeof ExcalidrawLib;
MathJax?: {
typesetPromise(elements: HTMLElement[]): Promise<void>;
};
}
interface File {
path?: string;
+25 -14
View File
@@ -1481,11 +1481,20 @@ export default class ExcalidrawView
ef.resetImage(this.file.path, link);
this.excalidrawData.setFile(fileId, ef);
this.setDirty();
await new Promise<void>((resolve) => {
void this.loadSceneFiles(
false,
new Set([fileId]),
resolve,
new Set([fileId]),
);
});
if (originalAnchor !== nextAnchor) {
await toggleImageAnchoring(el, this, nextAnchor, ef);
}
await this.save(false);
await sleep(100);
if (!this.plugin.isExcalidrawFile(ef.file) && !link.endsWith("|100%")) {
const ea = getEA(this);
const imgEl = this.getViewElements().find(
@@ -1496,10 +1505,12 @@ export default class ExcalidrawView
return;
}
if (imgEl && (await ea.resetImageAspectRatio(imgEl))) {
await ea.addElementsToView(false);
await ea.addElementsToView(false, false);
}
ea.destroy();
}
await this.save(false);
};
GenericInputPrompt.Prompt(
this,
@@ -7403,17 +7414,17 @@ export default class ExcalidrawView
: `${rank}: ${t("WELCOME_RANK_LEGENDARY")}`,
children: title,
}),
React.createElement(WelcomeScreen.Center.Heading, {
children: [
t("WELCOME_COMMAND_PALETTE"),
React.createElement("br"),
t("WELCOME_OBSIDIAN_MENU"),
React.createElement("br"),
t("WELCOME_SCRIPT_LIBRARY"),
React.createElement("br"),
t("WELCOME_HELP_MENU"),
],
}),
React.createElement(
WelcomeScreen.Center.Heading,
null,
t("WELCOME_COMMAND_PALETTE"),
React.createElement("br"),
t("WELCOME_OBSIDIAN_MENU"),
React.createElement("br"),
t("WELCOME_SCRIPT_LIBRARY"),
React.createElement("br"),
t("WELCOME_HELP_MENU"),
),
React.createElement(
WelcomeScreen.Center.Menu,
{},
+1 -1
View File
@@ -477,7 +477,7 @@ export function renderWebView(
view: ExcalidrawView,
id: string,
_: UIAppState,
): JSX.Element {
): React.JSX.Element {
let isAllowed = false;
try {
const url = new URL(src);
+1 -1
View File
@@ -5,7 +5,7 @@ type ButtonProps = {
title: string;
action: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
longpress?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
icon: JSX.Element;
icon: React.JSX.Element;
};
type ButtonState = {
+105 -72
View File
@@ -8,7 +8,7 @@ import * as React from "react";
import { DEVICE } from "src/constants/constants";
import { PenSettingsModal } from "src/shared/Dialogs/PenSettingsModal";
import ExcalidrawView from "src/view/ExcalidrawView";
import { PenStyle } from "src/types/penTypes";
import { ExtendedFillStyle, PenStyle } from "src/types/penTypes";
import { PENS } from "src/utils/pens";
import ExcalidrawPlugin from "../../../core/main";
import { ICONS, penIcon, stringToSVG } from "../../../constants/actionIcons";
@@ -20,6 +20,17 @@ import {
getAppStateStrokeWidthEntry,
getFreedrawStrokeWidthByKey,
} from "src/utils/excalidrawAutomateUtils";
import { ToolsPanel } from "./ToolsPanel";
export type ResetCustomPenState = {
currentItemStrokeWidthKey?: string;
currentItemStrokeWidth?: number;
currentItemStrokeVariability?: string;
currentItemBackgroundColor?: string;
currentItemStrokeColor?: string;
currentItemFillStyle?: string;
currentItemRoughness?: number;
};
export function setPen(pen: PenStyle, api: ExcalidrawImperativeAPI) {
const st = api.getAppState();
@@ -27,74 +38,88 @@ export function setPen(pen: PenStyle, api: ExcalidrawImperativeAPI) {
!pen.strokeWidth || pen.strokeWidth === 0
? {}
: getAppStateStrokeWidthEntry(undefined, pen.strokeWidth);
// Changed null to undefined so it neatly satisfies Partial<...>
const currentItemStrokeWidthKey =
"currentItemStrokeWidthKey" in strokeWidthEntry
? strokeWidthEntry.currentItemStrokeWidthKey
: null;
: undefined;
const currentItemStrokeWidth =
"currentItemStrokeWidth" in strokeWidthEntry
? strokeWidthEntry.currentItemStrokeWidth
: null;
: undefined;
// 1. Build the object and explicitly type it as your custom AppState
const nextAppState: Partial<AppState> = {
currentStrokeOptions: pen.penOptions,
currentItemStrokeWidthKey,
currentItemStrokeWidth,
currentItemStrokeVariability: pen.penOptions.constantPressure
? "constant"
: "variable",
...(pen.backgroundColor
? { currentItemBackgroundColor: pen.backgroundColor }
: null),
...(pen.strokeColor ? { currentItemStrokeColor: pen.strokeColor } : null),
...(pen.fillStyle === "" ? null : { currentItemFillStyle: pen.fillStyle }),
...(pen.roughness !== null
? { currentItemRoughness: pen.roughness }
: null),
...(pen.freedrawOnly && !st.resetCustomPen //switching from custom pen to next custom pen
? {
resetCustomPen: {
currentItemStrokeWidthKey: st.currentItemStrokeWidthKey as
| "extraThin"
| "thin"
| "medium"
| "bold"
| "extraBold",
currentItemStrokeWidth: st.currentItemStrokeWidth,
currentItemStrokeVariability: st.currentItemStrokeVariability as
| "constant"
| "variable",
currentItemBackgroundColor: st.currentItemBackgroundColor,
currentItemStrokeColor: st.currentItemStrokeColor,
currentItemFillStyle: st.currentItemFillStyle as ExtendedFillStyle,
currentItemRoughness: st.currentItemRoughness,
},
}
: null),
};
// 2. Cast it back to Partial<AppState> here to satisfy Excalidraw's API
api.updateScene({
appState: {
currentStrokeOptions: pen.penOptions,
currentItemStrokeWidthKey,
currentItemStrokeWidth,
currentItemStrokeVariability: pen.penOptions.constantPressure
? "constant"
: "variable",
...(pen.backgroundColor
? { currentItemBackgroundColor: pen.backgroundColor }
: null),
...(pen.strokeColor ? { currentItemStrokeColor: pen.strokeColor } : null),
...(pen.fillStyle === ""
? null
: { currentItemFillStyle: pen.fillStyle }),
...(pen.roughness !== null
? { currentItemRoughness: pen.roughness }
: null),
...(pen.freedrawOnly && !st.resetCustomPen //switching from custom pen to next custom pen
? {
resetCustomPen: {
currentItemStrokeWidthKey: st.currentItemStrokeWidthKey,
currentItemStrokeWidth: st.currentItemStrokeWidth,
currentItemStrokeVariability: st.currentItemStrokeVariability,
currentItemBackgroundColor: st.currentItemBackgroundColor,
currentItemStrokeColor: st.currentItemStrokeColor,
currentItemFillStyle: st.currentItemFillStyle,
currentItemRoughness: st.currentItemRoughness,
},
}
: null),
},
appState: nextAppState as Pick<AppState, keyof AppState>,
captureUpdate: CaptureUpdateAction.NEVER,
});
}
export function resetStrokeOptions(
resetCustomPen: Partial<AppState> | null,
resetCustomPen: ResetCustomPenState | null,
api: ExcalidrawImperativeAPI,
clearCurrentStrokeOptions: boolean,
) {
const appState = api.getAppState();
// 1. Build the object and explicitly type it as your custom AppState
const nextAppState: Partial<AppState> = {
...(resetCustomPen
? {
currentItemStrokeWidthKey: resetCustomPen.currentItemStrokeWidthKey,
currentItemStrokeWidth: resetCustomPen.currentItemStrokeWidth,
currentItemBackgroundColor: resetCustomPen.currentItemBackgroundColor,
currentItemStrokeColor: resetCustomPen.currentItemStrokeColor,
currentItemFillStyle: resetCustomPen.currentItemFillStyle,
currentItemRoughness: resetCustomPen.currentItemRoughness,
currentItemStrokeVariability:
resetCustomPen.currentItemStrokeVariability,
}
: null),
resetCustomPen: null,
...(clearCurrentStrokeOptions ? { currentStrokeOptions: null } : null),
};
// 2. Cast it back to Partial<AppState> here to satisfy Excalidraw's API
api.updateScene({
appState: {
...(resetCustomPen
? {
currentItemStrokeWidthKey: resetCustomPen.currentItemStrokeWidthKey,
currentItemStrokeWidth: resetCustomPen.currentItemStrokeWidth,
currentItemBackgroundColor:
resetCustomPen.currentItemBackgroundColor,
currentItemStrokeColor: resetCustomPen.currentItemStrokeColor,
currentItemFillStyle: resetCustomPen.currentItemFillStyle,
currentItemRoughness: resetCustomPen.currentItemRoughness,
currentItemStrokeVariability:
resetCustomPen.currentItemStrokeVariability,
}
: null),
resetCustomPen: null,
...(clearCurrentStrokeOptions ? { currentStrokeOptions: null } : null),
},
appState: nextAppState as Pick<AppState, keyof AppState>,
captureUpdate: CaptureUpdateAction.NEVER,
});
}
@@ -106,8 +131,8 @@ export class ObsidianMenu {
private prevClickTimestamp: number = 0;
constructor(
private plugin: ExcalidrawPlugin,
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ref instance is injected from ToolsPanel and carries imperative methods.
private toolsRef: React.MutableRefObject<any>,
private toolsRef: React.MutableRefObject<ToolsPanel>,
private view: ExcalidrawView,
) {
this.clickTimestamp = Array.from(
@@ -138,7 +163,7 @@ export class ObsidianMenu {
st.currentStrokeOptions === pen.penOptions &&
st.activeTool.type === "freedraw"
) {
resetStrokeOptions(st.resetCustomPen, api, true);
resetStrokeOptions(st.resetCustomPen as ResetCustomPenState, api, true);
return;
}
@@ -148,7 +173,7 @@ export class ObsidianMenu {
api.setActiveTool({ type: "freedraw" });
}
private actionScriptButtonPonterUp(index: number, key: string) {
private actionScriptButtonPointerUp(index: number, key: string) {
if (this.longpressTimeout[index]) {
this.view.ownerWindow.clearTimeout(this.longpressTimeout[index]);
this.longpressTimeout[index] = 0;
@@ -166,7 +191,11 @@ export class ObsidianMenu {
}
}
private actionScriptButtonPointerDown(index: number, key: string) {
private actionScriptButtonPointerDown(
index: number,
key: string,
name: string,
) {
const now = Date.now();
if (this.longpressTimeout[index] > 0) {
this.view.ownerWindow.clearTimeout(this.longpressTimeout[index]);
@@ -197,7 +226,7 @@ export class ObsidianMenu {
}
private actionShowHideMenu(isMobile: boolean, appState: AppState) {
this.toolsRef.current.setTheme(appState.theme);
this.toolsRef.current.setTheme(appState.theme as "dark" | "light");
this.toolsRef.current.toggleVisibility(appState.zenModeEnabled || isMobile);
}
@@ -233,7 +262,7 @@ export class ObsidianMenu {
) {
window.setTimeout(() =>
resetStrokeOptions(
appState.resetCustomPen,
appState.resetCustomPen as ResetCustomPenState,
this.view.excalidrawAPI,
false,
),
@@ -259,12 +288,18 @@ export class ObsidianMenu {
) {
const activePen = this.activePens[index] ?? { ...pen };
activePen.strokeWidth = getFreedrawStrokeWidthByKey(
appState.currentItemStrokeWidthKey,
appState.currentItemStrokeWidthKey as
| "extraThin"
| "thin"
| "medium"
| "bold"
| "extraBold",
appState.currentItemStrokeWidth,
);
activePen.backgroundColor = appState.currentItemBackgroundColor;
activePen.strokeColor = appState.currentItemStrokeColor;
activePen.fillStyle = appState.currentItemFillStyle;
activePen.fillStyle =
appState.currentItemFillStyle as ExtendedFillStyle;
activePen.roughness = appState.currentItemRoughness;
this.activePens[index] = activePen;
}
@@ -275,7 +310,7 @@ export class ObsidianMenu {
className={clsx("ToolIcon", "ToolIcon_size_medium", {
"is-mobile": isMobile,
})}
onClick={this.actionCustomPenLabelClick.bind(this, index, pen)}
onClick={() => this.actionCustomPenLabelClick(index, pen)}
>
<div
className="ToolIcon__icon"
@@ -311,12 +346,10 @@ export class ObsidianMenu {
className={clsx("ToolIcon", "ToolIcon_size_medium", {
"is-mobile": isMobile,
})}
onPointerUp={this.actionScriptButtonPonterUp.bind(this, index, key)}
onPointerDown={this.actionScriptButtonPointerDown.bind(
this,
index,
key,
)}
onPointerUp={() => this.actionScriptButtonPointerUp(index, key)}
onPointerDown={() =>
this.actionScriptButtonPointerDown(index, key, name)
}
>
<div
className="ToolIcon__icon"
@@ -337,7 +370,7 @@ export class ObsidianMenu {
className={clsx("ToolIcon", "ToolIcon_size_medium", {
"is-mobile": isMobile,
})}
onClick={this.actionShowHideMenu.bind(this, isMobile, appState)}
onClick={() => this.actionShowHideMenu(isMobile, appState)}
>
<div
className="ToolIcon__icon"
@@ -350,7 +383,7 @@ export class ObsidianMenu {
className={clsx("ToolIcon", "ToolIcon_size_medium", {
"is-mobile": isMobile,
})}
onClick={this.actionInsertAnyFile.bind(this)}
onClick={() => this.actionInsertAnyFile()}
>
<div className="ToolIcon__icon" aria-label={t("UNIVERSAL_ADD_FILE")}>
{ICONS["add-file"]}
@@ -360,7 +393,7 @@ export class ObsidianMenu {
className={clsx("ToolIcon", "ToolIcon_size_medium", {
"is-mobile": isMobile,
})}
onClick={this.actionToggleFullscreen.bind(this)}
onClick={() => this.actionToggleFullscreen()}
>
<div
className="ToolIcon__icon"
+30 -33
View File
@@ -280,10 +280,7 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
return;
}
if (!plugin.settings.taskboneEnabled) {
new Notice(
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
4000,
);
new Notice(t("TASKBON_NOT_ENABLED"), 4000);
return;
}
void plugin.taskbone.getTextForView(view, {
@@ -570,8 +567,8 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
>
<div
className="excalidraw-toolsPanel-dragHandle"
onClick={this.islandOnClick.bind(this)}
onPointerDown={this.islandOnPointerDown.bind(this)}
onClick={(e) => this.islandOnClick(e)}
onPointerDown={(e) => this.islandOnPointerDown(e)}
>
<svg
aria-hidden="true"
@@ -604,26 +601,26 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
<ActionButton
key={"scriptEngine"}
title={t("INSTALL_SCRIPT_BUTTON")}
action={this.actionOpenScriptInstallDialog.bind(this)}
action={() => this.actionOpenScriptInstallDialog()}
icon={ICONS.scriptEngine}
/>
<ActionButton
key={"release-notes"}
title={t("READ_RELEASE_NOTES")}
action={this.actionOpenReleaseNotes.bind(this)}
action={() => this.actionOpenReleaseNotes()}
icon={ICONS.releaseNotes}
/>
<ActionButton
key={"about-excalidraw"}
title={t("ABOUT_EXCALIDRAW")}
action={this.actionOpenAboutExcalidraw.bind(this)}
action={() => this.actionOpenAboutExcalidraw()}
icon={ICONS.Info}
/>
{this.state.isPreviewMode === null ? (
<ActionButton
key={"convert"}
title={t("CONVERT_FILE")}
action={this.actionConvertExcalidrawToMD.bind(this)}
action={() => this.actionConvertExcalidrawToMD()}
icon={ICONS.convertFile}
/>
) : (
@@ -633,7 +630,7 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
title={
this.state.isPreviewMode ? t("PARSED") : t("RAW")
}
action={this.actionToggleViewMode.bind(this)}
action={() => this.actionToggleViewMode()}
icon={
this.state.isPreviewMode
? ICONS.rawMode
@@ -645,7 +642,7 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
<ActionButton
key={"ui-mode"}
title={t("UI_MODE")}
action={this.actionToggleTrayMode.bind(this)}
action={() => this.actionToggleTrayMode()}
icon={ICONS.tray}
/>
<ActionButton
@@ -655,7 +652,7 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
? t("EXIT_FULLSCREEN")
: t("GOTO_FULLSCREEN")
}
action={this.actionToggleFullscreen.bind(this)}
action={() => this.actionToggleFullscreen()}
icon={
this.state.isFullscreen
? ICONS.exitFullScreen
@@ -667,31 +664,31 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
<ActionButton
key={"search"}
title={t("SEARCH")}
action={this.actionSearch.bind(this)}
action={() => this.actionSearch()}
icon={ICONS.search}
/>
<ActionButton
key={"ocr"}
title={t("RUN_OCR")}
action={this.actionOCR.bind(this)}
action={(e) => this.actionOCR(e)}
icon={ICONS.ocr}
/>
<ActionButton
key={"openLink"}
title={t("OPEN_LINK_CLICK")}
action={this.actionOpenLink.bind(this)}
action={(e) => this.actionOpenLink(e)}
icon={ICONS.openLink}
/>
<ActionButton
key={"openLinkProperties"}
title={t("OPEN_LINK_PROPS")}
action={this.actionOpenLinkProperties.bind(this)}
action={() => this.actionOpenLinkProperties()}
icon={ICONS.openLinkProperties}
/>
<ActionButton
key={"save"}
title={t("FORCE_SAVE")}
action={this.actionForceSave.bind(this)}
action={() => this.actionForceSave()}
icon={saveIcon(this.state.isDirty)}
/>
</div>
@@ -702,25 +699,25 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
<ActionButton
key={"lib"}
title={t("DOWNLOAD_LIBRARY")}
action={this.actionExportLibrary.bind(this)}
action={() => this.actionExportLibrary()}
icon={ICONS.exportLibrary}
/>
<ActionButton
key={"exportIMG"}
title={t("EXPORT_IMAGE")}
action={this.actionExportImage.bind(this)}
action={() => this.actionExportImage()}
icon={ICONS.ExportImage}
/>
<ActionButton
key={"md"}
title={t("OPEN_AS_MD")}
action={this.actionOpenAsMarkdown.bind(this)}
action={() => this.actionOpenAsMarkdown()}
icon={ICONS.switchToMarkdown}
/>
<ActionButton
key={"link-to-element"}
title={t("INSERT_LINK_TO_ELEMENT")}
action={this.actionLinkToElement.bind(this)}
action={(e) => this.actionLinkToElement(e)}
icon={ICONS.copyElementLink}
/>
</div>
@@ -731,55 +728,55 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
<ActionButton
key={"anyfile"}
title={t("UNIVERSAL_ADD_FILE")}
action={this.actionAddAnyFile.bind(this)}
action={() => this.actionAddAnyFile()}
icon={ICONS["add-file"]}
/>
<ActionButton
key={"image"}
title={t("INSERT_IMAGE")}
action={this.actionInsertImage.bind(this)}
action={() => this.actionInsertImage()}
icon={ICONS.insertImage}
/>
<ActionButton
key={"pdf"}
title={t("INSERT_PDF")}
action={this.actionInsertPDF.bind(this)}
action={() => this.actionInsertPDF()}
icon={ICONS.insertPDF}
/>
<ActionButton
key={"insertMD"}
title={t("INSERT_MD")}
action={this.actionInsertMarkdown.bind(this)}
action={() => this.actionInsertMarkdown()}
icon={ICONS.insertMD}
/>
<ActionButton
key={"insertBackOfNote"}
title={t("INSERT_CARD")}
action={this.actionInsertBackOfNote.bind(this)}
action={() => this.actionInsertBackOfNote()}
icon={ICONS.BackOfNote}
/>
<ActionButton
key={"latex"}
title={t("INSERT_LATEX")}
action={this.actionInsertLaTeX.bind(this)}
action={(e) => this.actionInsertLaTeX(e)}
icon={ICONS.insertLaTeX}
/>
<ActionButton
key={"link"}
title={t("INSERT_LINK")}
action={this.actionInsertLink.bind(this)}
action={() => this.actionInsertLink()}
icon={ICONS.insertLink}
/>
<ActionButton
key={"import-svg"}
title={t("IMPORT_SVG")}
action={this.actionImportSVG.bind(this)}
action={() => this.actionImportSVG()}
icon={ICONS.importSVG}
/>
<ActionButton
key={"crop-image"}
title={t("CROP_IMAGE")}
action={this.actionCropImage.bind(this)}
action={() => this.actionCropImage()}
icon={ICONS.Crop}
/>
</div>
@@ -845,8 +842,8 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
<ActionButton
key={key}
title={value.name}
action={this.actionRunScript.bind(this, key)}
longpress={this.actionPinScript.bind(this, key, value.name)}
action={() => void this.actionRunScript(key)}
longpress={() => void this.actionPinScript(key, value.name)}
icon={new WeakRef(
value.svgString
? stringToSVG(value.svgString)
+27 -9
View File
@@ -1032,7 +1032,15 @@ End Obsidian Sheets Plus support
}
.excalidraw-toolsPanel-island {
width: 14.5rem;
/*
Width calculation:
- 5 buttons: (var(--default-button-size) * 5)
- 4 column gaps of 0.25rem: 1rem
- standard left/right panel padding: ~1.5rem (0.75rem each side)
- plus a tiny 0.1rem buffer to prevent accidental wrapping
*/
width: calc((var(--default-button-size) * 5) + 3rem);
height: fit-content;
max-height: 400px;
z-index: 5;
@@ -1044,19 +1052,29 @@ End Obsidian Sheets Plus support
cursor: move;
}
.excalidraw .App-bottom-bar .App-toolbar {
min-width: 12.8em;
}
.excalidraw .Island.App-menu__left {
scrollbar-width: none;
}
.excalidraw .Island.excalidraw-toolsPanel-island .buttonList Button.ToolIcon_type_button {
flex: 0 0 18%;
/* Ensure tool buttons remain perfectly square and sized just like native Excalidraw.
This overrides the old '18%' rule which was stretching the buttons. */
.excalidraw .Island.excalidraw-toolsPanel-island .buttonList>.ToolIcon_type_button,
.excalidraw .Island.excalidraw-toolsPanel-island .buttonList>.ToolIcon,
.excalidraw .Island.excalidraw-toolsPanel-island .buttonList>label {
flex: 0 0 auto;
margin: 0;
}
/* Replicate the EXACT native Excalidraw property panel layout */
.excalidraw .Island.excalidraw-toolsPanel-island .selected-shape-actions .buttonList {
justify-content: space-between;
column-gap: unset;
display: flex;
flex-wrap: wrap;
justify-content: flex-start;
/* Use standard gap shorthand: row-gap(0.5rem) column-gap(0.25rem).
This perfectly matches the native panel spacing and avoids linter warnings! */
gap: 0.5rem 0.25rem;
}
.excalidraw .App-tray-menu {
min-width: calc(6 * var(--default-button-size));
}