Compare commits

...
Author SHA1 Message Date
zsviczian 13e58fb005 2.25.3-beta.2 - export CM6 and getMathEditorExtensions, initial version of ExcaliMath 2026-07-09 10:25:13 +00:00
zsviczian c8daa43221 update filters on settings change 2026-07-08 21:03:27 +02:00
zsviczian 27b2dae94f updated Icon Library script 2026-07-08 20:15:14 +02:00
zsviczian 8dda9317b5 lint 2026-07-08 08:57:18 +00:00
zsviczian 1f181f3ce1 2.25.3-beta.1 : custom pens buttons refactored, plugin crash due to dynamic style 2026-07-08 08:43:14 +00:00
zsviczian 8ef705689d updated icon library, added filter and pagination 2026-07-08 07:01:39 +00:00
zsviczian 6552132e38 2.25.3-beta.0 2026-07-07 19:33:25 +02:00
zsviczian c72cd2d241 updated icon library script 2026-07-07 19:18:50 +02:00
zsviczian 9d870489e2 updated icon library 2026-07-07 19:10:37 +02:00
zsviczian 0aab180dd7 publishing Icon Library Script 2026-07-07 13:47:57 +00:00
zsviczian 3c308100cd Icon Library.svg 2026-07-07 15:39:33 +02:00
zsviczian b911272116 new script image for Icon Library 2026-07-07 15:36:54 +02:00
zsviczian e0563598c4 updated Shade Master to be responsive to selection in the scene 2026-07-07 10:46:02 +00:00
zsviczian 847433b1fe Merge pull request #2832 from iwanhoogendoorn/csd-polish-round2
Comic Strip Director: polish round 2 + update timestamp
2026-07-07 09:38:34 +02:00
iwanhoogendoorn 1bfbf1f91c Comic Strip Director: polish round 2 + update timestamp
Changes that landed just after #2831 was merged:

- Missing thumbnail images degrade gracefully (onerror fallback: the FX
  word in the FX grid, a neutral glyph in the picker tiles) instead of
  showing the browser's broken-image placeholder.
- Effects-count label removed from the FX header (the grid speaks for
  itself; 'No effects yet' duplicated the starter onboarding).
- Store button uses its own shop-orange colour instead of the accent, so
  it no longer competes with primary actions.

directory-info.json mtime bumped so Excalidraw offers the update.
2026-07-07 07:56:15 +02:00
zsviczian b47f90ad77 updated Comic Strip Director date 2026-07-07 07:49:47 +02:00
zsviczian 8719f585b6 Merge pull request #2831 from iwanhoogendoorn/csd-description-and-polish
Csd description and polish
2026-07-07 07:48:46 +02:00
iwanhoogendoorn 0e23dd0d28 Starter-pack button only shows while the library is empty 2026-07-07 07:37:39 +02:00
iwanhoogendoorn 942a1540a0 No auto-margins in wrapping toolbars (orphaned right-pushed buttons on wrap) 2026-07-07 07:33:43 +02:00
iwanhoogendoorn 6c0cfd48b0 Footer store link wraps at narrow widths (was clipped by nowrap) 2026-07-07 07:32:46 +02:00
iwanhoogendoorn 44259770be Consistent button arrangement: toolbar rows per section, single store button 2026-07-07 07:31:54 +02:00
iwanhoogendoorn 0ec2db3c3c Pack discovery also covers the script's data folder
.strippack files dropped into 'Comic Strip Director (Library)' (or its
legacy folder names) now show up in the import picker alongside the
scripts folder and Scripts/Downloaded/.
2026-07-06 23:29:34 +02:00
iwanhoogendoorn c6303edc7e Comic Strip Director: index description + UI polish
Follow-up to #2830 (the review commit landed just after the merge):

- index-new.md: short text description in the entry's Description cell,
  as requested in review, ahead of the screenshot.
- Script update: the data folder it creates is now named 'Comic Strip
  Director (Library)' (folders from previous names keep resolving), the
  footer Close button is gone, the panel is responsive (images scale,
  rows wrap, long names break), all buttons share one uniform size, and
  the accent starter button no longer loses its background on hover.
2026-07-06 23:26:25 +02:00
zsviczian 1dcd7a3229 missing codeblock 2026-07-06 21:59:53 +02:00
zsviczian 11fffb559f publishing comic strip director 2026-07-06 21:52:19 +02:00
zsviczian e56bc1d7f9 Merge pull request #2830 from iwanhoogendoorn/add-comic-strip-director
New script: Comic Strip Director
2026-07-06 21:50:22 +02:00
iwanhoogendoorn 71c4257aed New script: Comic Strip Director
Turns the canvas into a comic-strip studio: 30 panel layouts (plus a
parametric generator), polygon/angled panels, panel splits, a character
system (who x costume x action with real thumbnails), painted FX callouts,
and reserved callout zones that compose with the Comicbook Callout Editor
(the two scripts cross-link with each other's icons). A free starter cast
(8 characters, 176 poses + 3 FX) installs with one click from inside the
script; add-on packs import from .strippack files.

Adds the script, its icon, a description image, and the index-new.md
entries (Conversation and Creation category + detail section).
2026-07-06 21:45:27 +02:00
zsviczian ddcdc03b1f added version check to comicbook script 2026-07-06 20:49:46 +02:00
zsviczian 51a770fd00 updated comic book callout editor (comic strip director link), fixed preview height, responsive to selection in the scene 2026-07-06 20:45:43 +02:00
zsviczian 7e745599f3 2.25.2 2026-07-05 19:39:09 +02:00
zsviczian 3a953818b1 2.25.2-beta.1 2026-07-05 15:25:31 +02:00
29 changed files with 9628 additions and 5097 deletions

No files matched your search

File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+23
View File
@@ -0,0 +1,23 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100">
<g fill="none" stroke="currentColor" stroke-width="7" stroke-linecap="round" stroke-linejoin="round">
<!-- speech bubble -->
<rect x="52" y="10" width="40" height="26" rx="9"/>
<path d="M60 36 l-3 12 l14 -12"/>
<!-- head -->
<circle cx="38" cy="42" r="18"/>
<!-- body -->
<line x1="38" y1="60" x2="38" y2="80"/>
<!-- arms: one waving up -->
<path d="M38 66 L22 74"/>
<path d="M38 65 L56 55"/>
<!-- legs -->
<path d="M38 80 L28 94"/>
<path d="M38 80 L48 94"/>
</g>
<!-- bubble dots + face (filled) -->
<g fill="currentColor" stroke="none">
<circle cx="63" cy="23" r="3"/><circle cx="72" cy="23" r="3"/><circle cx="81" cy="23" r="3"/>
<circle cx="32" cy="40" r="3"/><circle cx="44" cy="40" r="3"/>
</g>
<path d="M31 48 q7 6 14 0" fill="none" stroke="currentColor" stroke-width="4.5" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 973 B

+112 -7
View File
@@ -34,6 +34,11 @@ Features:
- Action buttons dynamically enable/disable based on whether the active workspace leaf matches the script's target Excalidraw view.
*/
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.25.0")) {
new Notice("This script requires a Excalidraw 2.25.0 or later. Please install the latest version.");
return;
}
// ---------------------------------------------------------
// 1. Constants & State Initialization
// ---------------------------------------------------------
@@ -1149,9 +1154,11 @@ async function renderPreview(previewContainer) {
await buildElements(false);
const svg = await ea.createSVG(undefined, undefined, undefined, undefined, undefined, 10);
// Constrain the SVG to neatly fit the preview boundary
svg.style.width = "100%";
svg.style.height = "100%";
// Constrain the SVG to neatly fit the preview boundary without stretching.
// The 'auto' height preserves the true aspect ratio of the generated callout,
// while the 100% max bounds prevent it from overflowing the 1:1 container.
// The flex properties of the container handle horizontal & vertical centering.
svg.style.height = "auto";
svg.style.maxWidth = "100%";
svg.style.maxHeight = "100%";
@@ -1509,7 +1516,7 @@ function buildPanelLayout(contentEl) {
// 2. Preview & Actions Column
previewWrapper = topSection.createDiv({ cls: "comic-preview-col" });
previewContainer = previewWrapper.createDiv({
attr: { style: `flex: 1 1 auto; min-height: 140px; border: 1px solid var(--background-modifier-border); border-radius: 8px; display: flex; align-items: center; justify-content: center; overflow: hidden; background-color: ${st()?.viewBackgroundColor ?? "gray"};` }
attr: { style: `width: 100%; max-width: 500px; aspect-ratio: 1 / 1; margin: 0 auto; border: 1px solid var(--background-modifier-border); border-radius: 8px; display: flex; align-items: center; justify-content: center; overflow: hidden; background-color: ${st()?.viewBackgroundColor ?? "gray"};` }
});
buildActionButtons(previewWrapper);
@@ -1915,7 +1922,7 @@ function renderColorsUI(container) {
}
/**
* Creates the functional UI buttons (Insert, Replace) for the side panel
* Creates the functional UI buttons (Director, Insert, Replace) for the side panel
*
* @param {HTMLElement} container - The parent DOM element to render into.
*/
@@ -1927,11 +1934,77 @@ function buildActionButtons(container) {
if (!localActionsContainer) {
localActionsContainer = container.createDiv({
cls: "comic-actions-container",
attr: { style: "display: flex; justify-content: flex-end; gap: 15px; flex: 0 0 auto;" }
attr: { style: "display: flex; justify-content: flex-end; gap: 15px; flex: 0 0 auto; align-items: center;" }
});
}
// Retrieve existing buttons or create them to avoid destroying DOM elements
// 1. Comic Strip Director Button - Retrieve or create
let directorBtn = localActionsContainer.querySelector(".comic-director-btn");
if (!directorBtn) {
directorBtn = localActionsContainer.createEl("button", { cls: "comic-director-btn clickable-icon" });
// Push this button to the far left, allowing subsequent buttons to stay right-aligned
directorBtn.style.marginRight = "auto";
directorBtn.style.padding = "4px";
directorBtn.style.background = "transparent";
directorBtn.style.boxShadow = "none";
}
// Check availability every time buildActionButtons is called (including during tab.onFocus)
const SCRIPT_MD = "Comic Strip Director.md";
const SCRIPT_SVG = "Comic Strip Director.svg";
const scriptsFolder = ea.plugin.settings.scriptFolderPath + "/";
const f = app.vault.getMarkdownFiles().find(file => file.name === SCRIPT_MD && file.path.startsWith(scriptsFolder));
const svgFile = app.vault.getFiles().find(file => file.name === SCRIPT_SVG && file.path.startsWith(scriptsFolder));
const isInstalled = Boolean(f && svgFile);
const currentState = isInstalled ? "installed" : "missing";
// Only update DOM and click handlers if the installation state actually changed
if (directorBtn.dataset.state !== currentState) {
directorBtn.dataset.state = currentState;
if (isInstalled) {
app.vault.read(svgFile).then(svgContent => {
directorBtn.innerHTML = svgContent;
const svg = directorBtn.querySelector("svg");
if (svg) {
svg.style.width = "24px";
svg.style.height = "24px";
}
});
directorBtn.title = "Open Comic Strip Director";
directorBtn.setAttribute("aria-label", "Open Comic Strip Director");
directorBtn.onclick = () => {
const scriptpath = f.parent.path.split(scriptsFolder)[1] ?? "";
const commandId = `obsidian-excalidraw-plugin:${scriptpath}${scriptpath===""?"":"/"}${f.basename}`;
const cmd = app.commands.commands[commandId];
if (cmd?.checkCallback) {
cmd.checkCallback(false);
} else if (cmd?.callback) {
cmd.callback();
} else {
app.commands.executeCommandById(commandId);
}
};
} else {
directorBtn.innerHTML = ea.obsidian.getIcon("info").outerHTML;
directorBtn.title = "Comic Strip Director recommended";
directorBtn.setAttribute("aria-label", "Comic Strip Director recommended");
directorBtn.onclick = () => {
const modal = new ea.obsidian.Modal(app);
modal.onOpen = () => {
const { contentEl } = modal;
contentEl.createEl("h3", { text: "Script Recommendation" });
contentEl.createEl("p", { text: "For a complete comic creation workflow, please install the 'Comic Strip Director' script from the Excalidraw script store." });
const btnContainer = contentEl.createDiv({ attr: { style: "display: flex; justify-content: flex-end; margin-top: 20px;" } });
const okBtn = btnContainer.createEl("button", { text: "OK", cls: "mod-cta" });
okBtn.onclick = () => modal.close();
};
modal.open();
};
}
}
// 2. Retrieve existing buttons or create them to avoid destroying DOM elements
// mid-click (which breaks focus events and causes double-click requirements)
let replaceBtn = localActionsContainer.querySelector(".comic-replace-btn");
if (!replaceBtn) {
@@ -2012,6 +2085,37 @@ async function main() {
const tab = await ea.createSidepanelTab("Comic Bubbles", true, true);
if (!tab) return;
// React to canvas selection changes automatically
ea.onSceneChangeHook = {
appStateKeys: ["selectedElementIds"],
trackElements: false,
triggerWhenInvisible: false,
callback: (elements, appState, files, view, hookEA) => {
// Ensure we are working with the correct view
if (view && view !== ea.targetView) {
ea.setView(view);
ea.clear();
}
// Check if selection actually translates to a different callout target
const oldTargetId = editTarget ? editTarget.polyId : null;
detectEditTarget();
const newTargetId = editTarget ? editTarget.polyId : null;
if (textAreaComp && textAreaComp.getValue() !== state.text) {
textAreaComp.setValue(state.text);
}
// Update UI configuration tabs if a completely new target shape was detected
if (oldTargetId !== newTargetId) {
renderTabsUI(tabsContainer);
}
buildActionButtons(previewWrapper);
scheduleUpdate(previewContainer);
}
};
tab.onOpen = () => {
buildPanelLayout(tab.contentEl);
scheduleUpdate(previewContainer);
@@ -2051,6 +2155,7 @@ async function main() {
};
tab.onClose = () => {
ea.onSceneChangeHook = null; // Unregister hook to free resources
savePrefs();
clearTimeout(previewTimeout);
};
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-square-sigma-icon lucide-square-sigma"><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M16 8.9V7H8l4 5-4 5h8v-1.9"/></svg>

After

Width:  |  Height:  |  Size: 334 B

File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-images-icon lucide-images"><path d="m22 11-1.296-1.296a2.4 2.4 0 0 0-3.408 0L11 16"/><path d="M4 8a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2"/><circle cx="13" cy="7" r="1" fill="currentColor"/><rect x="8" y="2" width="14" height="14" rx="2"/></svg>

After

Width:  |  Height:  |  Size: 456 B

+24 -2
View File
@@ -29,8 +29,8 @@ const HELP_TEXT = `
`;
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.19.1")) {
new Notice("Please update the Excalidraw Plugin to version 2.19.1 or higher.");
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.25.0")) {
new Notice("Please update the Excalidraw Plugin to version 2.25.0 or higher.");
return;
}
@@ -754,6 +754,25 @@ ea.createSidepanelTab("Shade Master", false, true).then(tab => {
processQueue();
};
// Register the scene change hook to listen for selection changes
ea.onSceneChangeHook = {
appStateKeys: ["selectedElementIds"],
trackElements: false,
triggerWhenInvisible: false,
callback: async (elements, appState, files, view, hookEA) => {
if (view && view !== ea.targetView) {
ea.setView(view);
ea.clear();
}
// Check if selection changed
const currentSelectionStr = ea.getViewSelectedElements().map(e => e.id).sort().join(",");
if (currentSelectionStr !== lastSelectionIds) {
await initializeAndRender();
}
}
};
tab.onOpen = async () => {
terminate = false;
// Initial load
@@ -774,6 +793,9 @@ ea.createSidepanelTab("Shade Master", false, true).then(tab => {
};
tab.onClose = async () => {
// Clean up the hook when closing the tab
ea.onSceneChangeHook = null;
terminate = true;
if (dirty) {
ea.setScriptSettings(settings);
+18 -2
View File
@@ -609,7 +609,7 @@
},
{
"fname": "Shade Master.md",
"mtime": 1779643017184
"mtime": 1783421040970
},
{
"fname": "Shade Master.svg",
@@ -681,10 +681,26 @@
},
{
"fname": "Comicbook Callout Editor.md",
"mtime": 1782550477836
"mtime": 1783363763625
},
{
"fname": "Comicbook Callout Editor.svg",
"mtime": 1781961241320
},
{
"fname": "Comic Strip Director.md",
"mtime": 1783403775437
},
{
"fname": "Comic Strip Director.svg",
"mtime": 1783367471938
},
{
"fname": "Icon Library.md",
"mtime": 1783537360980
},
{
"fname": "Icon Library.svg",
"mtime": 1783432036549
}
]
+16
View File
@@ -75,6 +75,8 @@ These are the scripts I use most often. I tried to order them by importance, but
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20Builder.svg"/></div>|[[#Mindmap Builder]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Capture%20Note.svg"/></div>|[[#Capture Note]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Comicbook%20Callout%20Editor.svg"/></div>|[[#Comicbook Callout Editor]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Comic%20Strip%20Director.svg"/></div>|[[#Comic Strip Director]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Icon%20Library.svg"/></div>|[[#Icon Library]]|
## Layout and Organization
**Keywords**: Design, Placement, Arrangement, Structure, Formatting, Alignment
@@ -176,6 +178,7 @@ These are the scripts I use most often. I tried to order them by importance, but
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Copy%20Selected%20Element%20Styles%20to%20Global.svg"/></div>|[[#Copy Selected Element Styles to Global]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/ExcaliAI.svg"/></div>|[[#ExcaliAI]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Excalidraw%20Writing%20Machine.svg"/></div>|[[#Excalidraw Writing Machine]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Icon%20Library.svg"/></div>|[[#Icon Library]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Palette%20loader.svg"/></div>|[[#Palette Loader]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Palm%20Guard.svg"/></div>|[[#Palm Guard]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/PDF%20Page%20Text%20to%20Clipboard.svg"/></div>|[[#PDF Page Text to Clipboard]]|
@@ -201,6 +204,7 @@ These are the scripts I use most often. I tried to order them by importance, but
| | |
|----|-----|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Add%20Next%20Step%20in%20Process.svg"/></div>|[[#Add Next Step in Process]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Comic%20Strip%20Director.svg"/></div>|[[#Comic Strip Director]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20freedraw%20to%20line.svg"/></div>|[[#Convert freedraw to line]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Deconstruct%20selected%20elements%20into%20new%20drawing.svg"/></div>|[[#Deconstruct selected elements into new drawing]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Full-Year%20Calendar%20Generator.svg"/></div>|[[#Full-Year Calendar Generator]]|
@@ -286,6 +290,12 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/iwanhoogendoorn'>@iwanhoogendoorn</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Color%20Scheme%20Manager.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Swap the entire Stroke and Background/Fill colour palettes between named, categorized themes (Cloud Providers, Code Editors, Tech Brands, Design Systems, Nature, and more) from a docked side panel. Applying a theme recolours your selection (or sets the active colour) and repaints the native picker — both the quick-pick rows and the extended 3×5 grid with shades. Create your own schemes, import from a flat hex list, a labelled STROKE/FILL text format, or a raw appState colorPalette JSON (paste or .txt/.json file), hand-pick a custom picker, and export the current palette. When the MindMap Builder script is installed, an optional toggle recolours mind maps branch-by-branch. The canvas background is always left white.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/color-scheme-manager.gif' style="width:560px;"></td></tr></table>
## Comic Strip Director
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Comic%20Strip%20Director.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/iwanhoogendoorn'>@iwanhoogendoorn</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Comic%20Strip%20Director.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Turn the canvas into a comic-strip studio: pick one of 30 page layouts (or generate one for any panel count — angled polygon panels included), split panels with action-beat cuts, then fill them from a who × costume × action character picker with real thumbnails. Painted POW!/BOOM!/ZAP! FX stamp straight into panels, and reserved callout zones hand off to the Comicbook Callout Editor for speech bubbles. A free 8-character starter cast (176 poses + 3 FX) installs with one click from inside the script; add-on packs import from .strippack files.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-comic-strip-director.jpg'></td></tr></table>
## Comicbook Callout Editor
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Comicbook%20Callout%20Editor.md
@@ -477,6 +487,12 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/simonperet'>@simonperet</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Full-Year%20Calendar%20Generator.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Generates a complete calendar for a specified year.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-full-year-calendar-exemple.excalidraw.png'></td></tr></table>
## Icon Library
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Icon%20Library.md
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Icon%20Library.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Adds a fast, searchable icon library to Excalidraw as a native side panel. Build your own library from Excalidraw drawings, SVGs, PNGs, JPGs, WebP images, and more. Automatically generate SVG thumbnails for Excalidraw files, organize icons using customizable regular-expression filters, search by keyword, and insert icons into Excalidraw or MindMap Builder with a single click. The panel supports lazy loading for large libraries, keyboard navigation, adjustable thumbnail sizes, configurable thumbnail backgrounds, and flexible insertion settings.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-icon-library.jpg'></td></tr></table>
## Image Occlusion
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Image%20Occlusion.md
Binary file not shown.

After

Width:  |  Height:  |  Size: 253 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.25.2-beta.0",
"version": "2.25.3-beta.2",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.25.1",
"version": "2.25.2",
"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.111",
"@zsviczian/excalidraw": "0.18.112",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -5261,9 +5261,9 @@
"license": "MIT"
},
"node_modules/@zsviczian/excalidraw": {
"version": "0.18.111",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.111.tgz",
"integrity": "sha512-Y0rHChvXRDVafpwxZ10CoKeV2U7EkhpNcC3xa4M29xEfFPH4fdFhbxwxODBg4aqMzBXD36MD1SSo+MDN3EXahg==",
"version": "0.18.112",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.112.tgz",
"integrity": "sha512-2DkMToE6L6yxgbEQJNWYZQLUVlt9DUACPHcFIX0Cy6pV2kUS27EPW+2fNaZsWHu3ihnyreaUeqUxk1VzQ4qIRA==",
"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.111",
"@zsviczian/excalidraw": "0.18.112",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
+14 -1
View File
@@ -156,8 +156,21 @@ const packageString = isLib
'let {react, reactDOM } = new Function(`${REACT_PACKAGES}; return {react: React, reactDOM: ReactDOM};`)();\n' +
'let excalidrawLib = {};\n' +
`const PLUGIN_LANGUAGES = {${LANGUAGES.map(lang => `"${lang}": "${compressLanguageFile(lang)}"`).join(",")}};\n` +
//deliberate use of main document instead of activeDocument
//These declarations were moved here because Obsidian code scanner incorrectly flags them with a warning,
//but without offering a proper resolution, or a stepout process to remove them from scanner results.
//for context you can read different issues I raised with the Obsidian team about these.
//Once there is a workable resolution I am moving them back to their original locations, since having them here
//is not at all ideal.
//https://github.com/obsidianmd/eslint-plugin/issues/175
`const getCaretRangeFromPoint = (doc, x, y) => doc.caretRangeFromPoint?.(x, y);\n` +
//There isn't a process for flagging deliberate use of main document instead of activeDocument
//The blanket rule by the eslint-plugin makes sense for many cases, but does not address special case needs
`const mainDocument = document;\n` +
//Fetch is the only valid approach in case of loading binary data such as fonts to dataURL (i.e. not network related)
//I've also had cases in the past where requestUrl failed with certain endpoints, for those cases I have
//fetch in the codebase as a fallback from requestUrl.
//https://github.com/obsidianmd/eslint-plugin/issues/176
`const deliberateFetch = async (payload, init) => await fetch(payload, init);\n` +
`const PLUGIN_VERSION="${manifest.version}";\n`;
const BASE_CONFIG = {
+40 -16
View File
@@ -23,17 +23,19 @@ Excalidraw-Obsidian is an Obsidian.md plugins that is built on the open source E
Read the information below and respond with I'm ready. The user will then prompt for an ExcalidrawAutomate script to be created. Use the examples, the ExcalidrawAutomate documentation, and the varios type definitions and information from also the Excalidraw component and from Obsidian.md to generate the script based on the user's requirements.
In addition to ExcalidrawAutomate, you can also use two other sources of functions:
- The Excalidraw API available via ea.getExcalidrawAPI(). Note: the API is only available if ea.targetView is set. When running Excalidraw scripts using the script engine, the provided ea object is already set up with targetView by default. Otherwise you need to first run ea.setView().
- window.ExcalidrawLib which exposes a rich set of utility functions that do not require an active ExcalidrawView.
- The Excalidraw API available via \`ea.getExcalidrawAPI()\`. Note: the API is only available if \`ea.targetView\` is set. When running Excalidraw scripts using the script engine, the provided \`ea\` object is already set up with targetView by default. Otherwise you need to first run \`ea.setView()\`.
- \`window.ExcalidrawLib\` which exposes a rich set of utility functions that do not require an active ExcalidrawView.
**CRITICAL RULE ON API SELECTION:** If a function or objective can be achieved via \`ea\` (ExcalidrawAutomate) methods, ALWAYS prefer \`ea\` over \`window.ExcalidrawLib\`. \`ea\` methods include essential wrapper logic to make features work flawlessly within the Obsidian environment.
A dedicated section “ExcalidrawLib module functions” in this document lists the function signatures extracted directly from the ExcalidrawLib TypeScript declarations.
- When the user asks for a dialog window, by default create a FloatingModal. Do not extend the FloatingModal class. Instead, define the modal's behavior by creating a new instance (e.g., const modal = new ea.FloatingModal(...)) and then assigning functions directly to the onOpen and onClose properties of that instance.
- When the user asks for a dialog window, by default create a FloatingModal. Do not extend the FloatingModal class. Instead, define the modal's behavior by creating a new instance (e.g., \`const modal = new ea.FloatingModal(...)\`) and then assigning functions directly to the \`onOpen\` and \`onClose\` properties of that instance.
For a reference, follow the implementation pattern used in the "Printable Layout Wizard.md" script.
- Elements have a customData property that can be used to store arbitrary data. To ensure the data the script adds to elements use the ea.addAppendUpdateCustomData function. This function ensures that existing customData is preserved when adding new data.
- Elements have a \`customData\` property that can be used to store arbitrary data. To ensure the data the script adds to elements use the \`ea.addAppendUpdateCustomData\` function. This function ensures that existing customData is preserved when adding new data.
- Elements can be hidden by setting their opacity to 0. When hiding elements this way, it is good practice to temporarily store their original opacity in customData. This allows for easy restoration of the original opacity later.
- Elements can be deleted from the scene by setting their isDeleted property to true.
- The Obsidian.md module is available on ea.obsidian.
- The Obsidian.md module is available on \`ea.obsidian\`.
**Sidepanels and multi-view tooling:**
- Sidepanels are for scripts that must stay open while users hop between multiple Excalidraw views. They should implement the SidepanelTab hooks (\`onOpen\`, \`onFocus(view)\`, \`onClose\`, \`onExcalidrawViewClosed\`) and manage their own \`ea.targetView\` explicitly.
@@ -116,15 +118,17 @@ To keep this training file concise, large external type definitions are not incl
* **Always Use \`ea.addAppendUpdateCustomData(id, newData)\`:** This is crucial. It safely adds or updates your key-value pairs without overwriting data that might have been stored by other scripts or the Excalidraw plugin itself.
* **Creating Configurable Scripts:** To make your script's behavior customizable by the user:
* Use \`ea.getScriptSettings()\` to retrieve saved settings.
* scriptSettings are stored with Excalidraw settings in Obsidian data.json. Keep this light. You MUST NEVER save large data objects such as base64 images or huge arrays here. Keep this lean and efficient.
* Check if settings exist, and if not, define the default structure.
* Use \`await ea.setScriptSettings(settings)\` to save any changes. This allows users to configure your script in the Excalidraw plugin settings pane.
#### **6. Best Practices and Advanced Techniques**
* **Script Overview Block:** Create, and consistently maintain with each update, a comprehensive comment block at the very beginning of the script. This block must explain the purpose of the script, its key features, and the high-level solution logic or architecture.
* **Strictly Modular Architecture (No loose code):** Avoid creating large monolithic blocks of code or leaving logic loose at the root level of the script. Instead, organize *everything* into relatively small, atomic functions. This includes UI components as well, if for example the UI includes sections, tabs, or panels, these should be rendered in sub functions. This is a critical requirement to ensure long-term maintainability and evolution of the script, as loose code quickly becomes unmanageable over multiple iterative prompts.
* **Script Overview Block (MANDATORY):** Create, and consistently maintain with each update, a comprehensive comment block at the very beginning of the script. This block must explain the purpose of the script, its key features, and the high-level solution logic or architecture.
* **Strictly Modular Architecture (NO LOOSE CODE):** Avoid creating large monolithic blocks of code or leaving logic loose at the root level of the script. Instead, organize *everything* into relatively small, atomic functions. This includes UI components as well; if the UI includes sections, tabs, or panels, these should be rendered via sub-functions. This is a critical requirement to ensure long-term maintainability and evolution of the script, as loose code quickly becomes unmanageable over multiple iterative prompts.
* **Evergreen JSDoc Headers and Comments:** Every function must have a proper JSDoc/Javadoc-style header containing parameter names, types, and a clear description of the function's purpose. These descriptions must be kept *evergreen* (updated alongside any code changes). Additionally, when modifying or updating a script, you must strictly *retain all existing internal code comments*.
* **Isolate Constants and User-Facing Strings:** *Do not embed hardcoded magic values, config parameters, or UI strings deep inside the logic.* You must separate all constants and language strings and collect them at the very top of the file. This makes it easier to tweak values later and provides a clear, unified section for localization and customization.
* **Icons:** Obsidian uses https://lucide.dev icons. These icons are available for scripts via \`ea.obsidian.getIcon("Icon Name")\`. For UI components prefer use of lucide.dev icons.
* **Omit Version Verification:** While many of the sample scripts in the library include a version verification block at the outset (using \`ea.verifyMinimumPluginVersion\`), *do not add this section* when generating a new script unless explicitly instructed to do so.
* **Embrace \`await\`:** Many EA functions are asynchronous and return a \`Promise\` (e.g., \`ea.addElementsToView()\`, \`ea.createSVG()\`, \`utils.inputPrompt()\`). **Always** use \`await\` when calling these functions to ensure your script executes in the correct order.
* **Accessing Obsidian API:** The full Obsidian API is available via \`ea.obsidian\`. For example, use \`new ea.obsidian.Notice("message")\` or \`ea.obsidian.normalizePath(filepath)\`.
@@ -134,12 +138,11 @@ To keep this training file concise, large external type definitions are not incl
* To permanently remove an element from the scene, set \`element.isDeleted = true\`.
* **Image Handling:** When dealing with image elements, use \`ea.getViewFileForImageElement(imageElement)\` to get the corresponding \`TFile\` from the Obsidian vault. This is necessary for any logic that needs to read or manipulate the source image file.
#### **9. Text Element**
* There are three text properties.
* **textElement.text** holds the wrapped, rendered text. This is what is displayed in the view. Excalidraw adds '\\n' linebreaks during dynamic wrapping.
* **textElement.originalText** holds the rendered, but unwrapped text. Any '\\n' character in originalText is an intentional linebreak by the user. Rendered means that for example [[wiki links]] are rendered without the square brackets.
* **textElement.rawText** holds the original raw text including intentional new line characters and the full markdown markup (thought currently only links are rendered, so markdown support is limited to these)
* When modifying element text from script, typically all 3 of these properties must be updated, though in case textElement.autoresize === true, or when a text element is bound in a container, excalidraw will update textElement.text following the size of the text element or the container.
#### **7. SVG and Image Export Approaches**
Generating images (SVG/PNG) requires specific approaches depending on the context. Follow these three rules strictly to avoid performance issues and missing assets:
1. **Exporting elements currently in the EA workbench:** Use \`await ea.createSVG(null, ...)\` or \`await ea.createPNG(null, ...)\` (passing \`null\` as the \`templatePath\`).
2. **Exporting an Excalidraw file that is NOT currently open:** Pass the file path as the template to \`createSVG\` or \`createPNG\` (e.g., \`await ea.createSVG(file.path, ...)\`). This is the most reliable approach as ExcalidrawAutomate natively handles loading the scene, resolving embedded images, and instantiating loaders behind the scenes. **Do NOT attempt to manually read the file, reconstruct the scene, or load images into memory.**
3. **Exporting the currently active \`ExcalidrawView\`:** Use \`await ea.createViewSVG(...)\`. This is specifically for the open view. You can use the \`elementsOverride\` parameter to inject temporary elements (like transparent sizing rectangles) into the exported image without modifying the actual scene.
#### **8. Custom Pens and Perfect Freehand**
@@ -230,6 +233,13 @@ Example freedraw element carrying \`customData.strokeOptions\`:
{"type":"excalidraw/clipboard","elements":[{"id":"...","type":"freedraw","strokeColor":"#3E6F8D","backgroundColor":"transparent","fillStyle":"hachure","strokeWidth":0.5,"roughness":0,"customData":{"strokeOptions":{"highlighter":false,"hasOutline":false,"outlineWidth":0,"constantPressure":true,"options":{"smoothing":0.4,"thinning":-0.5,"streamline":0.4,"easing":"linear","start":{"taper":5,"cap":false,"easing":"linear"},"end":{"taper":5,"cap":false,"easing":"linear"}}}}}],"files":{}}
\`\`\`
#### **9. Text Element**
* There are three text properties.
* **textElement.text** holds the wrapped, rendered text. This is what is displayed in the view. Excalidraw adds '\\n' linebreaks during dynamic wrapping.
* **textElement.originalText** holds the rendered, but unwrapped text. Any '\\n' character in originalText is an intentional linebreak by the user. Rendered means that for example [[wiki links]] are rendered without the square brackets.
* **textElement.rawText** holds the original raw text including intentional new line characters and the full markdown markup (thought currently only links are rendered, so markdown support is limited to these)
* When modifying element text from script, typically all 3 of these properties must be updated, though in case textElement.autoresize === true, or when a text element is bound in a container, excalidraw will update textElement.text following the size of the text element or the container.
`;
const SCRIPT_INTRO = `# Excalidraw Script Library Examples
@@ -543,15 +553,29 @@ function main() {
output += `<!-- BEGIN index-new.md -->\n${indexNewContent.trim()}\n<!-- END index-new.md -->\n\n`;
output += `---\n\n# Script Sources\n`;
// Collect *.md files (non-recursive) excluding index-new.md
// Read additional exclusions from command line arguments (skipping 'node' and 'script.mjs')
const args = process.argv.slice(2);
const cmdLineExcludes = args.map(arg => arg.toLowerCase());
// Define the default exclusions (all in lower case for comparison)
const defaultExcludes = [
'index-new.md',
'mindmap builder.md',
'color scheme manager.md',
'comic strip director.md'
];
// Combine both into a single Set for easy lookup
const exclusions = new Set([...defaultExcludes, ...cmdLineExcludes]);
// Collect *.md files (non-recursive) excluding our combined list
const files = fs
.readdirSync(EA_SCRIPTS_DIR, { withFileTypes: true })
.filter(
(d) =>
d.isFile() &&
(d.name.endsWith('.md') || d.name.toLowerCase() === "mindmap builder.js") &&
d.name.toLowerCase() !== 'index-new.md' &&
d.name.toLowerCase() !== 'mindmap builder.md'
!exclusions.has(d.name.toLowerCase())
)
.map((d) => d.name)
.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
+21 -6
View File
@@ -7,6 +7,7 @@ import {
isInstanceOfHTMLSelectElement,
isInstanceOfHTMLTextAreaElement,
} from "src/utils/typechecks";
import { errorlog } from "src/utils/coreUtils";
declare const mainDocument: Document;
@@ -33,6 +34,12 @@ function pointInRect(
);
}
declare const getCaretRangeFromPoint: (
doc: Document,
x: number,
y: number,
) => Range | null;
function isPointOnText(e: PointerEvent | TouchEvent, doc: Document): boolean {
const pt = getClientPoint(e);
if (!pt) {
@@ -48,8 +55,8 @@ function isPointOnText(e: PointerEvent | TouchEvent, doc: Document): boolean {
offsetNode = caretPos.offsetNode;
offset = typeof caretPos.offset === "number" ? caretPos.offset : null;
} else {
// Safari/WebKit
const caretRange = doc.caretRangeFromPoint?.(pt.x, pt.y);
// Safari/WebKit - see rollup.config.mjs for the declaration of getCaretRangeFromPoint
const caretRange = getCaretRangeFromPoint(doc, pt.x, pt.y);
if (caretRange?.startContainer) {
offsetNode = caretRange.startContainer;
offset =
@@ -253,8 +260,12 @@ export class FloatingModal extends Modal {
try {
// Release modal scope so focus and key handling can return to the workspace.
this.app.keymap.popScope(this.scope);
} catch (error) {
console.log(error);
} catch (error: unknown) {
errorlog({
where: "FloatingModal.open",
error,
message: "Failed to release modal scope",
});
}
// prevent automatic selection / focus restoration
this.shouldRestoreSelection = false;
@@ -333,8 +344,12 @@ export class FloatingModal extends Modal {
) {
try {
this.previousActive.focus({ preventScroll: true });
} catch (error) {
console.log(error);
} catch (error: unknown) {
errorlog({
where: "FloatingModal.close",
error,
message: "Failed to restore focus to previous element",
});
}
}
const { modalEl } = this;
+19 -4
View File
@@ -16,13 +16,28 @@ export const RELEASE_NOTES: { [k: string]: string } = {
I build this plugin as a labor of love. Curious about the philosophy behind it? Check out [📕 Sketch Your Mind](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_SYM}). Want to master Excalidraw? Join [Excalidraw Mastery](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}). If you find it valuable, say "Thank you", and
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
`,
"2.25.3": `
## Fixed
- Fixed custom pens with shared Perfect Freehand settings both appearing selected in the toolbar at the same time. [#2828](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2828)
- Plugin does not start. Changing dynamic styling setting to off, and to on again solves the issue. Added further safety checks to avoid plugin crash. [#2819](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2819)
## New in ExcalidrawAutomate
- Added \`ea.getCM6()\` to expose CodeMirror 6 and Lezer classes/functions (EditorView, EditorState, etc.) to the ScriptEngine environment without needing unstable require imports.
- Added \`ea.getMathEditorExtensions()\` to expose Excalidraw's pre-configured LaTeX editor extensions, natively supporting obsidian-latex-suite integration in custom sidepanel scripts.
`,
"2.25.2": `
One more small maintenance release with a few important fixes.
I'm now shifting my focus to the [SYM Community](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM}), where I'll be experimenting with some exciting new Visual PKM ideas. I'll also be taking a few weeks to recharge, so I don't expect another Excalidraw update until August.
I hope these fixes make for a stable release. Have a great summer, and see you in the community!
## Fixed
- YouTube embeddables did not render on Android devices
- Changing custom pen settings did not save correctly. Added Save and Cancel buttons to the Pen Settings page.
- Error generating image ID on mobile devices when uploading / pasting images to the scene
`,
- Fixed YouTube embeddables not rendering on Android devices.
- Fixed custom pen settings not being saved correctly. Added **Save** and **Cancel** buttons to the Pen Settings page.
- Fixed an error generating image IDs on mobile devices when uploading or pasting images into a scene.
`,
"2.25.1": `
This is a very minor update to fix a small regression in 2.25.0
+1 -1
View File
@@ -44,7 +44,7 @@ import { setStyle } from "src/utils/styleUtils";
* Minimal type for obsidian-latex-suite plugin.
* Only types the properties actually used by this codebase.
*/
interface LatexSuitePlugin {
export interface LatexSuitePlugin {
editorExtensions?: Extension | Extension[];
}
+12
View File
@@ -1350,6 +1350,18 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
desc: "If set, this callback is triggered whenever a drawing is exported to SVG. The string returned will replace the internal Obsidian link in the exported SVG.",
after: "",
},
{
field: "getCM6",
code: "getCM6(): {EditorView: typeof EditorView; EditorState: typeof EditorState; keymap: typeof keymap; defaultKeymap: typeof defaultKeymap; history: typeof history; historyKeymap: typeof historyKeymap; LRLanguage: typeof LRLanguage; Tree: typeof Tree; NodeType: typeof NodeType;};",
desc: "Returns CodeMirror 6 constructor classes and utilities for creating advanced embedded editors (EditorView, EditorState, keymap, LRLanguage, etc.).",
after: "",
},
{
field: "getMathEditorExtensions",
code: "getMathEditorExtensions(): (LRLanguage | Extension)[];",
desc: "Returns the pre-configured CodeMirror 6 extensions used by Excalidraw's LaTeX editor. Includes the internal math parser required to trigger 'obsidian-latex-suite'.",
after: "",
},
];
export const EXCALIDRAW_SCRIPTENGINE_INFO: SuggesterInfo[] = [
+7 -2
View File
@@ -75,6 +75,11 @@ import {
} from "src/utils/typechecks";
import { getSafeFrontmatter, strictArrayBuffer } from "src/utils/obsidianUtils";
//declared in rollup.config.mjs
declare const deliberateFetch: (
payload: RequestInfo | URL,
init?: RequestInit,
) => Promise<Response>;
declare const mainDocument: Document;
//An ugly workaround for the following situation.
//File A is a markdown file that has an embedded Excalidraw file B
@@ -1780,7 +1785,7 @@ const mjxScopedStyleCache = new Map<string, Promise<string>>();
const fetchFontAsDataURI = async (url: string): Promise<string | null> => {
if (url.startsWith("data:")) return url;
try {
const res = await fetch(url);
const res = await deliberateFetch(url);
if (!res.ok) return null;
const buf = await res.arrayBuffer();
const bytes = new Uint8Array(buf);
@@ -1945,7 +1950,7 @@ const replaceBlobWithBase64 = async (
const blobUrl = img.src;
try {
// fetch is the only way to read blob: URLs in browser/Obsidian context.
const response = await fetch(blobUrl);
const response = await deliberateFetch(blobUrl);
const blob = await response.blob();
const base64 = await blobToBase64(blob);
img.src = `data:${blob.type};base64,${base64}`;
+67 -1
View File
@@ -85,7 +85,7 @@ import {
} from "@zsviczian/excalidraw/types/excalidraw/types";
import { EmbeddedFile, EmbeddedFilesLoader } from "./EmbeddedFileLoader";
import { tex2dataURL } from "./LaTeX";
import { NewFileActions } from "src/shared/Dialogs/Prompt";
import { LatexSuitePlugin, NewFileActions } from "src/shared/Dialogs/Prompt";
import {
ConnectionPoint,
DeviceType,
@@ -175,6 +175,12 @@ import {
updateOrAddSVGColorInfo,
verifyMinimumPluginVersion,
} from "src/utils/excalidrawAutomateUtils";
import { EditorView, keymap } from "@codemirror/view";
import { EditorState, Extension } from "@codemirror/state";
import { defaultKeymap, history, historyKeymap } from "@codemirror/commands";
import { LRLanguage } from "@codemirror/language";
import { Tree, NodeType } from "@lezer/common";
import { parser as mathParser } from "./Dialogs/math-only";
type MutableElementMapEntry = Mutable<ExcalidrawElement> &
Record<string, unknown>;
@@ -4886,6 +4892,66 @@ export class ExcalidrawAutomate {
return true;
}
/**
* Returns CodeMirror 6 constructor classes and utilities for creating advanced embedded editors.
* Includes EditorView, EditorState, keymap, history, LRLanguage, Tree, and NodeType.
* Useful when building custom sidepanels or modals that require rich text editing features.
* @returns {Object} An object containing CodeMirror 6 and Lezer classes/functions.
*/
public getCM6(): {
EditorView: typeof EditorView;
EditorState: typeof EditorState;
keymap: typeof keymap;
defaultKeymap: typeof defaultKeymap;
history: typeof history;
historyKeymap: typeof historyKeymap;
LRLanguage: typeof LRLanguage;
Tree: typeof Tree;
NodeType: typeof NodeType;
} {
return {
EditorView,
EditorState,
keymap,
defaultKeymap,
history,
historyKeymap,
LRLanguage,
Tree,
NodeType,
};
}
/**
* Returns the pre-configured CodeMirror 6 extensions used by Excalidraw's native LaTeX editor.
* Includes the internal math parser required to trick 'obsidian-latex-suite' into thinking
* it is operating inside a math block, along with standard history and default keymaps.
* @returns { (LRLanguage | Extension)[]} An array of CodeMirror 6 extensions ready to be passed to EditorState.create().
*/
public getMathEditorExtensions(): (LRLanguage | Extension)[] {
const minimalSetup = [
history(),
keymap.of([...defaultKeymap, ...historyKeymap]),
];
const language = LRLanguage.define({ parser: mathParser });
const extensions = [
obsidian_module.editorLivePreviewField.init(() => false),
EditorView.editorAttributes.of({ class: "multi-select-container" }),
minimalSetup,
language,
];
const latexSuite = this.plugin.app.plugins.plugins[
"obsidian-latex-suite"
] as LatexSuitePlugin;
if (latexSuite?.editorExtensions) {
extensions.push(latexSuite.editorExtensions);
}
return extensions;
}
/**
* Destroys the ExcalidrawAutomate instance, clearing all references and data.
*/
+307 -221
View File
@@ -6,6 +6,30 @@ import { cloneElement } from "./excalidrawViewHelpers";
import { ExcalidrawFrameElement } from "@zsviczian/excalidraw/types/element/src/types";
import { addAppendUpdateCustomData } from "./utils";
import { CaptureUpdateAction } from "src/constants/constants";
import { errorlog } from "./coreUtils";
import { removeStyle, setStyle } from "./styleUtils";
const applyToolsPanelStyle = (
toolsPanel: HTMLDivElement,
styleObject: Record<string, string>,
) => {
// Never rely on parsing inline style text. `style` can be absent or altered by themes/plugins.
setStyle(toolsPanel, styleObject);
};
const clearToolsPanelDynamicStyle = (
toolsPanel: HTMLDivElement,
styleObject: Record<string, string>,
) => {
removeStyle(toolsPanel, Object.keys(styleObject));
};
const isFrameElement = (el: unknown): el is ExcalidrawFrameElement => {
if (!el || typeof el !== "object" || !("type" in el)) {
return false;
}
return (el as { type: string }).type === "frame";
};
export const setDynamicStyle = (
ea: ExcalidrawAutomate,
@@ -14,235 +38,297 @@ export const setDynamicStyle = (
dynamicStyle: DynamicStyle,
textBackgroundColor?: string,
) => {
color = color ?? "white";
if (dynamicStyle === "none") {
//view.excalidrawContainer?.removeAttribute("style");
window.setTimeout(() =>
view.updateScene({
appState: { dynamicStyle: {} },
captureUpdate: CaptureUpdateAction.NEVER,
}),
);
try {
color = color ?? "white";
// Minimal style contract used to clean up dynamic variables when styling is turned off.
const emptyStyleObject: Record<string, string> = {
backgroundColor: "",
"--color-primary": "",
"--color-surface-low": "",
"--color-surface-mid": "",
"--color-surface-lowest": "",
"--color-warning": "",
"--color-surface-high": "",
"--color-on-primary-container": "",
"--color-surface-primary-container": "",
"--bold-color": "",
"--color-primary-darker": "",
"--color-brand-hover": "",
"--color-primary-darkest": "",
"--button-bg-color": "",
"--button-gray-1": "",
"--button-gray-2": "",
"--input-border-color": "",
"--input-bg-color": "",
"--input-label-color": "",
"--island-bg-color": "",
"--popup-secondary-bg-color": "",
"--icon-fill-color": "",
"--text-primary-color": "",
"--overlay-bg-color": "",
"--popup-bg-color": "",
"--color-on-surface": "",
"--default-border-color": "",
"--color-gray-40": "",
"--color-surface-highlight": "",
"--color-gray-20": "",
"--sidebar-border-color": "",
"--color-primary-light": "",
"--button-hover-bg": "",
"--sidebar-bg-color": "",
"--sidebar-shadow": "",
"--popup-text-color": "",
"--code-normal": "",
"--code-background": "",
"--h1-color": "",
"--h2-color": "",
"--h3-color": "",
"--h4-color": "",
color: "",
"--excalidraw-caret-color": "",
"--select-highlight-color": "",
"--color-gray-90": "",
"--color-gray-80": "",
"--color-gray-70": "",
"--default-bg-color": "",
"--color-gray-50": "",
};
const toolspanel = view.toolsPanelRef?.current?.containerRef?.current;
if (toolspanel) {
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2810
let toolsStyle = toolspanel.getAttribute("style") ?? "";
toolsStyle = toolsStyle.replace(/--color-primary.*/, "");
toolspanel.setAttribute("style", toolsStyle);
}
return;
}
//const doc = view.ownerDocument;
const st = view?.excalidrawAPI?.getAppState?.();
const isLightTheme = st?.theme === "light" || st?.theme === "light";
if (color === "transparent") {
color = "#ffffff";
}
const darker = "#101010";
const lighter = "#f0f0f0";
const step = 10;
const mixRatio = 0.9;
const invertColor = (c: string) => {
const cm = ea.getCM(c);
const lightness = cm.lightness;
return cm.lightnessTo(Math.abs(lightness - 100));
};
const cmBG = () => (isLightTheme ? ea.getCM(color) : invertColor(color));
const bgLightness = cmBG().lightness;
const isDark = cmBG().darkerBy(step).isDark();
const isGray = dynamicStyle === "gray";
const accentColorString = view.app.getAccentColor();
const accent = () =>
isGray
? ea.getCM(accentColorString)
: ea.getCM(accentColorString).mix({ color: cmBG(), ratio: 0.2 });
const cmBlack = () => ea.getCM("#000000").lightnessTo(bgLightness);
const cmDarkRed = () => ea.getCM("#8B0000").lightnessTo(bgLightness);
const gray1 = () =>
isGray
? isDark
? cmBlack().lighterBy(12)
: cmBlack().darkerBy(12)
: isDark
? cmBG().lighterBy(10).mix({ color: cmBlack(), ratio: 0.5 })
: cmBG().darkerBy(10).mix({ color: cmBlack(), ratio: 0.5 });
const gray2 = () =>
isGray
? isDark
? cmBlack().lighterBy(8)
: cmBlack().darkerBy(8)
: isDark
? cmBG().lighterBy(4).mix({ color: cmBlack(), ratio: 0.5 })
: cmBG().darkerBy(4).mix({ color: cmBlack(), ratio: 0.5 });
const gray3 = () =>
isGray
? isDark
? cmBlack().lighterBy(4)
: cmBlack().darkerBy(4)
: isDark
? cmBG().mix({ color: cmBlack(), ratio: 0.5 })
: cmBG().mix({ color: cmBlack(), ratio: 0.5 });
const warning = () =>
isGray
? isDark
? cmBlack().lighterBy(2)
: cmBlack().darkerBy(2)
: isDark
? cmBG().lighterBy(2).mix({ color: cmDarkRed(), ratio: 0.5 })
: cmBG().darkerBy(2).mix({ color: cmDarkRed(), ratio: 0.5 });
const text = () =>
cmBG().mix({ color: isDark ? lighter : darker, ratio: mixRatio });
const str = (cm: ColorMaster) => cm.stringHEX({ alpha: false });
const styleObject: { [x: string]: string } = {
["backgroundColor"]: str(cmBG()),
[`--color-primary`]: str(accent()),
[`--color-surface-low`]: str(gray1()),
[`--color-surface-mid`]: str(gray1()),
[`--color-surface-lowest`]: str(gray2()),
[`--color-warning`]: str(warning()),
[`--color-surface-high`]: str(gray1().lighterBy(step)),
[`--color-on-primary-container`]: str(
!isDark ? accent().darkerBy(15) : accent().lighterBy(15),
),
[`--color-surface-primary-container`]: str(
isDark ? accent().darkerBy(step) : accent().lighterBy(step),
),
[`--bold-color`]: str(
!isDark ? accent().darkerBy(15) : accent().lighterBy(15),
),
[`--color-primary-darker`]: str(accent().darkerBy(step)),
[`--color-brand-hover`]: str(accent().darkerBy(step)),
[`--color-primary-darkest`]: str(accent().darkerBy(2 * step)),
["--button-bg-color"]: str(gray1()),
[`--button-gray-1`]: str(gray1()),
[`--button-gray-2`]: str(gray2()),
[`--input-border-color`]: str(gray1()),
[`--input-bg-color`]: str(gray2()),
[`--input-label-color`]: str(text()),
[`--island-bg-color`]: gray3().alphaTo(0.93).stringHEX(),
[`--popup-secondary-bg-color`]: gray2().alphaTo(0.93).stringHEX(),
[`--icon-fill-color`]: str(text()),
[`--text-primary-color`]: str(text()),
[`--overlay-bg-color`]: gray2().alphaTo(0.6).stringHEX(),
[`--popup-bg-color`]: str(gray1()),
[`--color-on-surface`]: str(text()),
[`--default-border-color`]: str(gray1()),
//[`--color-gray-100`]: str(text()),
[`--color-gray-40`]: str(
isDark ? text().darkerBy(30) : text().lighterBy(30),
), //frame
[`--color-surface-highlight`]: str(gray1()),
[`--color-gray-20`]: str(gray1()),
[`--sidebar-border-color`]: str(gray1()),
[`--color-primary-light`]: str(accent().lighterBy(step)),
[`--button-hover-bg`]: str(gray1()),
[`--sidebar-bg-color`]: gray2().alphaTo(0.93).stringHEX(),
[`--sidebar-shadow`]: str(gray1()),
[`--popup-text-color`]: str(text()),
[`--code-normal`]: str(text()),
[`--code-background`]: str(gray2()),
[`--h1-color`]: str(text()),
[`--h2-color`]: str(text()),
[`--h3-color`]: str(text()),
[`--h4-color`]: str(text()),
[`color`]: str(text()),
["--excalidraw-caret-color"]: textBackgroundColor
? str(
isLightTheme
? invertColor(textBackgroundColor)
: ea.getCM(textBackgroundColor),
)
: isLightTheme
? str(invertColor(color))
: color,
[`--select-highlight-color`]: str(gray1()),
[`--color-gray-90`]: str(isDark ? text().darkerBy(5) : text().lighterBy(5)), //search background
[`--color-gray-80`]: str(
isDark ? text().darkerBy(9) : text().lighterBy(10),
), //frame
[`--color-gray-70`]: str(
isDark ? text().darkerBy(13) : text().lighterBy(15),
), //frame
[`--default-bg-color`]: str(
isDark ? text().darkerBy(20) : text().lighterBy(20),
), //search background,
[`--color-gray-50`]: str(
isDark ? text().darkerBy(20) : text().lighterBy(25),
),
};
const styleString = Object.keys(styleObject)
.map((property) => `${property}: ${styleObject[property]}`)
.join("; ");
/*view.excalidrawContainer?.setAttribute(
"style",
styleString
)*/
const toolspanel = view.toolsPanelRef?.current?.containerRef?.current;
if (toolspanel) {
let toolsStyle = toolspanel.getAttribute("style") ?? "";
toolsStyle = toolsStyle.replace(/--color-primary.*/, "");
toolspanel.setAttribute("style", toolsStyle + styleString);
}
window.setTimeout(() => {
const api = view.excalidrawAPI;
if (!api) {
view = null;
ea = null;
color = null;
dynamicStyle = null;
if (dynamicStyle === "none") {
window.setTimeout(() =>
view.updateScene({
appState: { dynamicStyle: {} },
captureUpdate: CaptureUpdateAction.NEVER,
}),
);
if (toolspanel) {
clearToolsPanelDynamicStyle(toolspanel, emptyStyleObject);
}
return;
}
const frameColor = {
stroke: str(isDark ? gray2().lighterBy(15) : gray2().darkerBy(15)),
fill: str(
(isDark ? gray2().lighterBy(30) : gray2().darkerBy(30)).alphaTo(0.2),
),
nameColor: str(isDark ? gray2().lighterBy(50) : gray2().darkerBy(50)),
//const doc = view.ownerDocument;
const st = view?.excalidrawAPI?.getAppState?.();
const isLightTheme = st?.theme === "light" || st?.theme === "light";
if (color === "transparent") {
color = "#ffffff";
}
const darker = "#101010";
const lighter = "#f0f0f0";
const step = 10;
const mixRatio = 0.9;
const invertColor = (c: string) => {
const cm = ea.getCM(c);
const lightness = cm.lightness;
return cm.lightnessTo(Math.abs(lightness - 100));
};
const scene = api.getSceneElements();
scene
.filter((el) => el.type === "frame")
.forEach((e: ExcalidrawFrameElement) => {
const f = cloneElement(e);
addAppendUpdateCustomData(f, { frameColor });
if (
e.customData &&
e.customData.frameColor &&
e.customData.frameColor.stroke === frameColor.stroke &&
e.customData.frameColor.fill === frameColor.fill &&
e.customData.frameColor.nameColor === frameColor.nameColor
) {
const cmBG = () => (isLightTheme ? ea.getCM(color) : invertColor(color));
const bgLightness = cmBG().lightness;
const isDark = cmBG().darkerBy(step).isDark();
const isGray = dynamicStyle === "gray";
const accentColorString = view.app.getAccentColor();
const accent = () =>
isGray
? ea.getCM(accentColorString)
: ea.getCM(accentColorString).mix({ color: cmBG(), ratio: 0.2 });
const cmBlack = () => ea.getCM("#000000").lightnessTo(bgLightness);
const cmDarkRed = () => ea.getCM("#8B0000").lightnessTo(bgLightness);
const gray1 = () =>
isGray
? isDark
? cmBlack().lighterBy(12)
: cmBlack().darkerBy(12)
: isDark
? cmBG().lighterBy(10).mix({ color: cmBlack(), ratio: 0.5 })
: cmBG().darkerBy(10).mix({ color: cmBlack(), ratio: 0.5 });
const gray2 = () =>
isGray
? isDark
? cmBlack().lighterBy(8)
: cmBlack().darkerBy(8)
: isDark
? cmBG().lighterBy(4).mix({ color: cmBlack(), ratio: 0.5 })
: cmBG().darkerBy(4).mix({ color: cmBlack(), ratio: 0.5 });
const gray3 = () =>
isGray
? isDark
? cmBlack().lighterBy(4)
: cmBlack().darkerBy(4)
: isDark
? cmBG().mix({ color: cmBlack(), ratio: 0.5 })
: cmBG().mix({ color: cmBlack(), ratio: 0.5 });
const warning = () =>
isGray
? isDark
? cmBlack().lighterBy(2)
: cmBlack().darkerBy(2)
: isDark
? cmBG().lighterBy(2).mix({ color: cmDarkRed(), ratio: 0.5 })
: cmBG().darkerBy(2).mix({ color: cmDarkRed(), ratio: 0.5 });
const text = () =>
cmBG().mix({ color: isDark ? lighter : darker, ratio: mixRatio });
const str = (cm: ColorMaster) => cm.stringHEX({ alpha: false });
const styleObject: { [x: string]: string } = {
["backgroundColor"]: str(cmBG()),
[`--color-primary`]: str(accent()),
[`--color-surface-low`]: str(gray1()),
[`--color-surface-mid`]: str(gray1()),
[`--color-surface-lowest`]: str(gray2()),
[`--color-warning`]: str(warning()),
[`--color-surface-high`]: str(gray1().lighterBy(step)),
[`--color-on-primary-container`]: str(
!isDark ? accent().darkerBy(15) : accent().lighterBy(15),
),
[`--color-surface-primary-container`]: str(
isDark ? accent().darkerBy(step) : accent().lighterBy(step),
),
[`--bold-color`]: str(
!isDark ? accent().darkerBy(15) : accent().lighterBy(15),
),
[`--color-primary-darker`]: str(accent().darkerBy(step)),
[`--color-brand-hover`]: str(accent().darkerBy(step)),
[`--color-primary-darkest`]: str(accent().darkerBy(2 * step)),
["--button-bg-color"]: str(gray1()),
[`--button-gray-1`]: str(gray1()),
[`--button-gray-2`]: str(gray2()),
[`--input-border-color`]: str(gray1()),
[`--input-bg-color`]: str(gray2()),
[`--input-label-color`]: str(text()),
[`--island-bg-color`]: gray3().alphaTo(0.93).stringHEX(),
[`--popup-secondary-bg-color`]: gray2().alphaTo(0.93).stringHEX(),
[`--icon-fill-color`]: str(text()),
[`--text-primary-color`]: str(text()),
[`--overlay-bg-color`]: gray2().alphaTo(0.6).stringHEX(),
[`--popup-bg-color`]: str(gray1()),
[`--color-on-surface`]: str(text()),
[`--default-border-color`]: str(gray1()),
//[`--color-gray-100`]: str(text()),
[`--color-gray-40`]: str(
isDark ? text().darkerBy(30) : text().lighterBy(30),
), //frame
[`--color-surface-highlight`]: str(gray1()),
[`--color-gray-20`]: str(gray1()),
[`--sidebar-border-color`]: str(gray1()),
[`--color-primary-light`]: str(accent().lighterBy(step)),
[`--button-hover-bg`]: str(gray1()),
[`--sidebar-bg-color`]: gray2().alphaTo(0.93).stringHEX(),
[`--sidebar-shadow`]: str(gray1()),
[`--popup-text-color`]: str(text()),
[`--code-normal`]: str(text()),
[`--code-background`]: str(gray2()),
[`--h1-color`]: str(text()),
[`--h2-color`]: str(text()),
[`--h3-color`]: str(text()),
[`--h4-color`]: str(text()),
[`color`]: str(text()),
["--excalidraw-caret-color"]: textBackgroundColor
? str(
isLightTheme
? invertColor(textBackgroundColor)
: ea.getCM(textBackgroundColor),
)
: isLightTheme
? str(invertColor(color))
: color,
[`--select-highlight-color`]: str(gray1()),
[`--color-gray-90`]: str(
isDark ? text().darkerBy(5) : text().lighterBy(5),
), //search background
[`--color-gray-80`]: str(
isDark ? text().darkerBy(9) : text().lighterBy(10),
), //frame
[`--color-gray-70`]: str(
isDark ? text().darkerBy(13) : text().lighterBy(15),
), //frame
[`--default-bg-color`]: str(
isDark ? text().darkerBy(20) : text().lighterBy(20),
), //search background,
[`--color-gray-50`]: str(
isDark ? text().darkerBy(20) : text().lighterBy(25),
),
};
/*view.excalidrawContainer?.setAttribute(
"style",
styleString
)*/
if (toolspanel) {
applyToolsPanelStyle(toolspanel, styleObject);
}
window.setTimeout(() => {
try {
const api = view.excalidrawAPI;
if (!api) {
view = null;
ea = null;
color = null;
dynamicStyle = null;
return;
}
view.excalidrawAPI.mutateElement(e, { customData: f.customData });
});
const frameColor = {
stroke: str(isDark ? gray2().lighterBy(15) : gray2().darkerBy(15)),
fill: str(
(isDark ? gray2().lighterBy(30) : gray2().darkerBy(30)).alphaTo(
0.2,
),
),
nameColor: str(isDark ? gray2().lighterBy(50) : gray2().darkerBy(50)),
};
const scene = api.getSceneElements() as unknown[];
scene.filter(isFrameElement).forEach((e) => {
const f = cloneElement(e);
addAppendUpdateCustomData(f, { frameColor });
if (
e.customData &&
e.customData.frameColor &&
e.customData.frameColor.stroke === frameColor.stroke &&
e.customData.frameColor.fill === frameColor.fill &&
e.customData.frameColor.nameColor === frameColor.nameColor
) {
return;
}
view.excalidrawAPI.mutateElement(e, { customData: f.customData });
});
view.updateScene({
appState: {
frameColor,
dynamicStyle: styleObject,
},
captureUpdate: CaptureUpdateAction.NEVER,
view.updateScene({
appState: {
frameColor,
dynamicStyle: styleObject,
},
captureUpdate: CaptureUpdateAction.NEVER,
});
} catch (error: unknown) {
errorlog({
where: "setDynamicStyle.window.setTimeout",
error,
message: "Dynamic styling deferred update failed",
});
} finally {
view = null;
ea = null;
color = null;
dynamicStyle = null;
}
});
view = null;
ea = null;
color = null;
dynamicStyle = null;
});
} catch (error: unknown) {
errorlog({
where: "setDynamicStyle",
error,
message: "Dynamic styling failed",
});
}
};
const colorsCache: Map<string, string> = new Map();
+15 -5
View File
@@ -187,6 +187,12 @@ export const getMimeType = (extension: string): MimeType => {
}
};
//declared in rollup.config.mjs
declare const deliberateFetch: (
payload: RequestInfo | URL,
init?: RequestInit,
) => Promise<Response>;
// Using fetch as primary for maximum compatibility with CORS/image endpoints.
// fetch is used here because requestUrl sometimes fails for certain endpoints (e.g. Firebase Storage, see comment below).
// This is a network request, not a vault or blob:app:// read.
@@ -202,7 +208,7 @@ const getFileFromURL = async (
// fetch is used here for broad compatibility with image endpoints, including those that fail with requestUrl.
const response = await Promise.race([
fetch(url, { mode: "no-cors" }), // CORS error cannot be caught
deliberateFetch(url, { mode: "no-cors" }), // CORS error cannot be caught
timeoutPromise,
]);
@@ -224,8 +230,12 @@ const getFileFromURL = async (
json: null,
text: null,
};
} catch (error) {
console.log("unexpected error in getFileFromURL", getFileFromURL, error);
} catch (error: unknown) {
errorlog({
where: getFileFromURL,
error,
message: "unexpected error in getFileFromURL",
});
return null;
}
};
@@ -765,7 +775,7 @@ export async function exportImageToFile(
excalidrawFile: view.file,
action: "export",
}) ?? path;
} catch (e) {
} catch (e: unknown) {
errorlog({
where: "fileUtils.exportImageToFile",
fn: ea.onImageExportPathHook,
@@ -791,7 +801,7 @@ export async function importFileToVault(
currentImageName: fname,
drawingFilePath: excalidrawFile.path,
});
} catch (e) {
} catch (e: unknown) {
errorlog({
where: "fileUtils.importFileToVault",
fn: ea.onImageFilePathHook,
+47 -17
View File
@@ -137,6 +137,8 @@ export function resetStrokeOptions(
export class ObsidianMenu {
private clickTimestamp: number[];
private activePens: Record<number, PenStyle> = {};
private activePenIndex: number | null = null;
private pendingPenActivation = false;
private longpressTimeout: { [key: number]: number } = {};
private prevClickTimestamp: number = 0;
constructor(
@@ -155,6 +157,23 @@ export class ObsidianMenu {
this.activePens = {};
}
private getValidatedActivePenIndex(customPensCount: number): number | null {
if (customPensCount <= 0) {
return this.activePenIndex;
}
if (
this.activePenIndex === null ||
this.activePenIndex < 0 ||
this.activePenIndex >= customPensCount
) {
this.activePenIndex = null;
return null;
}
return this.activePenIndex;
}
private actionCustomPenLabelClick(index: number, pen: PenStyle) {
const now = Date.now();
const dblClick = now - this.clickTimestamp[index] < 500;
@@ -171,20 +190,23 @@ export class ObsidianMenu {
const api = this.view.excalidrawAPI;
const st = api.getAppState();
const activePenIndex = this.getValidatedActivePenIndex(
st.customPens?.length ?? this.plugin.settings.numberOfCustomPens,
);
// Deep compare objects to bypass Excalidraw's immutable reference updates
const isPenActive =
JSON.stringify(st.currentStrokeOptions ?? null) ===
JSON.stringify(pen.penOptions ?? null);
const isPenActive = activePenIndex === index;
//single second click to reset freedraw to default
if (isPenActive && st.activeTool.type === "freedraw") {
this.activePenIndex = null;
resetStrokeOptions(st.resetCustomPen as ResetCustomPenState, api, true);
return;
}
//apply pen settings to canvas
this.activePens[index] = this.activePens[index] ?? { ...pen };
this.activePenIndex = index;
this.pendingPenActivation = true;
setPen(this.activePens[index], api);
api.setActiveTool({ type: "freedraw" });
}
@@ -268,20 +290,28 @@ export class ObsidianMenu {
}
public renderCustomPens(isMobile: boolean, appState: AppState) {
if (this.pendingPenActivation && appState.activeTool.type === "freedraw") {
this.pendingPenActivation = false;
}
const activePenIndex = this.getValidatedActivePenIndex(
appState.customPens?.length ?? 0,
);
return appState.customPens?.map((_, index) => {
const pen = this.plugin.settings.customPens[index];
const activePen = this.activePens[index] ?? pen;
const isPenActive =
JSON.stringify(appState.currentStrokeOptions ?? null) ===
JSON.stringify(pen.penOptions ?? null);
const isPenActive = activePenIndex === index;
//Reset stroke setting when changing to a different tool
if (
pen.freedrawOnly && // Enforce freedrawOnly so global pens do not auto-reset upon changing tools
appState.resetCustomPen &&
appState.activeTool.type !== "freedraw" &&
!this.pendingPenActivation &&
isPenActive
) {
this.activePenIndex = null;
window.setTimeout(() =>
resetStrokeOptions(
appState.resetCustomPen as ResetCustomPenState,
@@ -298,9 +328,7 @@ export class ObsidianMenu {
isPenActive &&
pen.freedrawOnly
) {
window.setTimeout(() =>
setPen(this.activePens[index] ?? pen, this.view.excalidrawAPI),
);
window.setTimeout(() => setPen(activePen, this.view.excalidrawAPI));
}
if (
@@ -309,8 +337,8 @@ export class ObsidianMenu {
isPenActive &&
pen.freedrawOnly
) {
const activePen = this.activePens[index] ?? { ...pen };
activePen.strokeWidth = getFreedrawStrokeWidthByKey(
const updatedActivePen = this.activePens[index] ?? { ...pen };
updatedActivePen.strokeWidth = getFreedrawStrokeWidthByKey(
appState.currentItemStrokeWidthKey as
| "extraThin"
| "thin"
@@ -319,12 +347,12 @@ export class ObsidianMenu {
| "extraBold",
appState.currentItemStrokeWidth,
);
activePen.backgroundColor = appState.currentItemBackgroundColor;
activePen.strokeColor = appState.currentItemStrokeColor;
activePen.fillStyle =
updatedActivePen.backgroundColor = appState.currentItemBackgroundColor;
updatedActivePen.strokeColor = appState.currentItemStrokeColor;
updatedActivePen.fillStyle =
appState.currentItemFillStyle as ExtendedFillStyle;
activePen.roughness = appState.currentItemRoughness;
this.activePens[index] = activePen;
updatedActivePen.roughness = appState.currentItemRoughness;
this.activePens[index] = updatedActivePen;
}
return (
@@ -438,6 +466,8 @@ export class ObsidianMenu {
);
this.longpressTimeout = {};
this.activePens = {};
this.activePenIndex = null;
this.pendingPenActivation = false;
this.plugin = null;
this.toolsRef = null;
this.view = null;