Compare commits

...
6 Commits
Author SHA1 Message Date
zsviczian a214941abc 2.25.1 2026-07-04 20:06:39 +02:00
zsviczian 48f1fbaf2c added onSceneChangeHook example 2026-07-04 18:59:28 +02:00
zsviczian 55a2672ed7 updated llm training file 2026-07-04 18:45:02 +02:00
zsviczian b198020b2d initialization message 2026-07-04 17:55:26 +02:00
zsviczian d164be8ee5 extra bottom padding for tablet controls 2026-07-04 08:05:05 +02:00
zsviczian 6aa7d1f75c excalidrawLoading viewtype fixed 2026-07-04 07:59:04 +02:00
14 changed files with 777 additions and 246 deletions

No files matched your search

@@ -1667,7 +1667,7 @@ export type ImageInfo = {
isHyperLink?: boolean;
hyperlink?: string;
file?: string | TFile;
hasSVGwithBitmap: boolean;
hasSVGwithBitmap?: boolean;
latex?: string;
size?: Size;
colorMap?: ColorMap;
+158 -114
View File
@@ -12,7 +12,7 @@ Content structure:
2. The curated script overview (index-new.md)
3. Raw source of every *.md script in /ea-scripts (each fenced code block is auto-closed to ensure well-formed aggregation)
Generated on: 2026-06-30T13:12:00.813Z
Generated on: 2026-07-04T16:58:43.617Z
---
@@ -2219,7 +2219,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 VERSION = "v.260703";
const FRAME_MARGIN = 10;
if (!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.23.8")) {
@@ -2737,15 +2737,28 @@ async function ensureTargetFileExists(folder, filename, fname, opt, noteType) {
// Resolves the Obsidian leaf behavior and explicitly waits for load instantiation
async function openAndResolveTargetLeaf(file, originView, openNoteBBehavior) {
let noteBWorkspaceLeaf;
if (openNoteBBehavior === "adjacent pane") {
noteBWorkspaceLeaf = ea.openFileInNewOrAdjacentLeaf(file);
} else if (openNoteBBehavior === "new tab") {
noteBWorkspaceLeaf = app.workspace.getLeaf("tab");
await noteBWorkspaceLeaf.openFile(file, { active: true });
let noteBWorkspaceLeaf = null;
// Check if the file is already open in any existing leaf
app.workspace.iterateAllLeaves((leaf) => {
if (leaf.view && leaf.view.file && leaf.view.file.path === file.path) {
noteBWorkspaceLeaf = leaf;
}
});
if (noteBWorkspaceLeaf) {
app.workspace.setActiveLeaf(noteBWorkspaceLeaf, { focus: true });
} else {
noteBWorkspaceLeaf = originView.leaf;
await noteBWorkspaceLeaf.openFile(file, { active: true });
// Standard logic if it is not open yet
if (openNoteBBehavior === "adjacent pane") {
noteBWorkspaceLeaf = ea.openFileInNewOrAdjacentLeaf(file);
} else if (openNoteBBehavior === "new tab") {
noteBWorkspaceLeaf = app.workspace.getLeaf("tab");
await noteBWorkspaceLeaf.openFile(file, { active: true });
} else {
noteBWorkspaceLeaf = originView.leaf;
await noteBWorkspaceLeaf.openFile(file, { active: true });
}
}
// Explicitly wait until the target leaf has fully instantiated its File representation
@@ -3468,11 +3481,23 @@ async function start() {
const captureData = await openCaptureModal(initialLinkText);
if (!captureData) return;
const { filename, noteType, format, ontologyAction, actionType, openNoteBBehavior, folder: customFolder } = captureData;
const { filename, noteType, format, ontologyAction, actionType, openNoteBBehavior, folder: customFolder, sidepanelWasVisible } = captureData;
// Inline cleanup helper attached to visibility flag
const closeSidepanelIfNeeded = () => {
if (!sidepanelWasVisible) {
const sidepanelLeaf = ea.getSidepanelLeaf();
if (sidepanelLeaf && sidepanelLeaf.view.containerEl.offsetParent !== null) {
ea.toggleSidepanelView();
}
}
};
const opt = settings.noteTypes[noteType];
if (!opt) {
new Notice("Error: Note Type configuration is missing. Open Settings to configure Note Types.");
closeSidepanelIfNeeded();
return;
}
@@ -3524,7 +3549,10 @@ async function start() {
if (!hasNoteType) {
const conflictDecision = await resolveExistingFileConflict(fileTarget, hasNoteType, hasPrefix, opt.prefix);
if (!conflictDecision) return;
if (!conflictDecision) {
closeSidepanelIfNeeded();
return;
}
if (conflictDecision.action === "CREATE_NEW") {
fileTarget = null;
@@ -3569,6 +3597,7 @@ async function start() {
ea.addText(0, 0, targetWikiLink);
await ea.addElementsToView(true, true, true);
ea.clear();
closeSidepanelIfNeeded();
return;
}
@@ -3583,6 +3612,7 @@ async function start() {
ea.clear();
}
new Notice(`Created file: ${file.basename}`);
closeSidepanelIfNeeded();
return;
}
@@ -3603,7 +3633,10 @@ async function start() {
// 9. Ensure Target View is Excalidraw and get API
const target_ea = await prepareTargetExcalidrawView(noteBWorkspaceLeaf);
if (!target_ea) return;
if (!target_ea) {
closeSidepanelIfNeeded();
return;
}
// 10. Calculate insertion bounds on Target Note
const bElements = target_ea.getViewElements();
@@ -3626,39 +3659,15 @@ async function start() {
// 12. Final Focus / Zoom
await handleFinalActionFocus(actionType, originView, noteBWorkspaceLeaf, embeddedElementId, target_ea, format, preGeneratedFrameID, clonedTemplateElementIds, mmAPI);
// 13. Sidepanel cleanup
closeSidepanelIfNeeded();
}
// -------------------------------------------------------------
// 5. UI: Capture Note Modal (Refactored)
// -------------------------------------------------------------
function setupCaptureModalEscapeHandler(modal) {
const escapeKey = modal.scope.keys.find(k => k.key === "Escape");
if (escapeKey) {
const originalFunc = escapeKey.func;
escapeKey.func = (e) => {
// Block modal closure if a child suggester was just closed
if (suppressEscape) return false;
// Block modal closure if custom dropdown is open
const customDropdown = modal.modalEl.querySelector(".mindmap-search-results");
if (customDropdown && customDropdown.style.display === "block") {
customDropdown.style.display = "none";
return false;
}
// Block modal closure if any standard Obsidian suggester is currently open
const suggests = document.body.querySelectorAll('.suggestion-container');
for (const s of suggests) {
if (s.style.display !== "none") {
return false;
}
}
return originalFunc(e);
};
}
}
function injectCaptureModalStyles(contentEl) {
contentEl.createEl("style", {
text: `
@@ -3673,42 +3682,31 @@ function injectCaptureModalStyles(contentEl) {
.mindmap-search-item.is-selected { background-color: var(--background-modifier-hover); }
.link-type-row-control { display: flex; align-items: center; gap: 8px; width: 100%; justify-content: flex-end; }
/* Modal Restyling for single-row / responsive layouts */
/* Fluid Container-Agnostic Layout (No @media queries needed) */
.excalidraw-capture-note-modal .setting-item {
display: flex;
flex-wrap: wrap;
flex-wrap: wrap; /* Allows wrapping when sidepanel is thin */
align-items: center;
justify-content: space-between;
gap: 12px;
gap: 8px;
padding: 8px 0; /* Shrink vertical padding */
min-height: auto; /* Override native Obsidian large min-height on mobile */
border-top: none;
}
.excalidraw-capture-note-modal .setting-item-info {
flex: 0 1 auto;
white-space: nowrap;
min-width: max-content;
flex: 1 1 120px; /* Base width of 120px, grows if space permits */
white-space: normal;
margin-top: 4px;
}
.excalidraw-capture-note-modal .setting-item-control {
flex: 1 1 200px;
flex: 2 1 200px; /* Base width of 200px. If container < 320px, it wraps to next line */
justify-content: flex-end;
min-width: 200px;
width: 100%; /* Expands to full width when wrapped */
}
.excalidraw-capture-note-modal .setting-item-control input[type="text"],
.excalidraw-capture-note-modal .setting-item-control select {
width: 100%;
}
@media (max-width: 450px) {
.excalidraw-capture-note-modal .setting-item {
flex-direction: column;
align-items: flex-start;
gap: 4px;
}
.excalidraw-capture-note-modal .setting-item-control {
width: 100%;
justify-content: stretch;
}
.excalidraw-capture-note-modal .setting-item-info {
white-space: normal;
}
}
`
});
}
@@ -3959,7 +3957,7 @@ function buildCaptureSearchBox(contentEl, state, callbacks) {
}
}
function buildCaptureLinkTypeSelector(contentEl, state, callbacks) {
function buildCaptureLinkTypeSelector(contentEl, state, callbacks, tab) {
const noteTypeKeys = Object.keys(settings.noteTypes).sort();
let selectedNoteType = state.selectedNoteType;
if (!selectedNoteType || !noteTypeKeys.includes(selectedNoteType)) {
@@ -4046,18 +4044,12 @@ function buildCaptureLinkTypeSelector(contentEl, state, callbacks) {
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();
if(tab && typeof tab.onOpen === "function") {
tab.onOpen(); // Re-render the capture tab inline
}
}, true);
});
});
@@ -4113,12 +4105,16 @@ function buildCaptureOntologySelector(contentEl, state, callbacks) {
});
}
function buildCaptureFooter(contentEl, state, modal) {
function buildCaptureFooter(contentEl, state, tab) {
// Footer is a normal non-wrapping flex row. `align-items: flex-end` forces the cog down when the button group expands vertically.
const footer = contentEl.createDiv({
attr: { style: "display: flex; justify-content: space-between; align-items: center; margin-top: 20px; flex-direction: row-reverse;" }
attr: { style: "display: flex; justify-content: space-between; align-items: flex-end; margin-top: 20px; gap: 10px; margin-bottom: 30px;" }
});
const buttonGroup = footer.createDiv({ attr: { style: "display: flex; gap: 8px; flex-direction: row-reverse;" } });
// buttonGroup gets CSS order 2 so it sits on the right visually
const buttonGroup = footer.createDiv({
attr: { style: "display: flex; gap: 8px; flex-wrap: wrap; justify-content: flex-end; flex: 1 1 auto; order: 2;" }
});
const handleAction = (actionType) => {
const val = state.ui.searchInput.getValue().trim();
@@ -4129,62 +4125,92 @@ function buildCaptureFooter(contentEl, state, modal) {
state.finalData = {
filename: val,
folder: folderVal,
useRelativeFolder: state.useRelativeFolder, // Append relative setting state
useRelativeFolder: state.useRelativeFolder,
noteType: state.selectedNoteType,
format: state.selectedFormat,
ontologyAction: state.selectedOntology,
actionType,
openNoteBBehavior: state.openNoteBBehavior
openNoteBBehavior: state.openNoteBBehavior,
sidepanelWasVisible: state.sidepanelWasVisible
};
modal.close();
tab.close();
};
const captureBtn = buttonGroup.createEl("button", { text: "Capture Note", cls: "mod-cta" });
// Assign CSS `order` so visual LTR layout matches standard wrap behavior
// (Items with higher order appear further right, and will drop to the bottom line first when wrapped)
const captureBtn = buttonGroup.createEl("button", {
text: "Capture",
cls: "mod-cta",
attr: {
style: "order: 4;",
"aria-label": "Create the note, add backlinks/embeds, and open it for editing."
}
});
captureBtn.addEventListener("click", () => handleAction("CAPTURE"));
const linkOnlyBtn = buttonGroup.createEl("button", { text: "Link Only" });
const linkOnlyBtn = buttonGroup.createEl("button", {
text: "Link",
attr: {
style: "order: 3;",
"aria-label": "Link to an item without creating the note and without opening it for editing."
}
});
linkOnlyBtn.addEventListener("click", () => handleAction("ADD_LINK_ONLY"));
const linkCreateBtn = buttonGroup.createEl("button", { text: "Link & Create" });
const linkCreateBtn = buttonGroup.createEl("button", {
text: "Link + File",
attr: {
style: "order: 2;",
"aria-label": "Link to the item and create its note/file in the background (but do not open for note taking)."
}
});
linkCreateBtn.addEventListener("click", () => handleAction("ADD_LINK_CREATE"));
const captureHereBtn = buttonGroup.createEl("button", { text: "Capture Here" });
const captureHereBtn = buttonGroup.createEl("button", { text: "Capture Here", attr: { style: "order: 1;" } });
captureHereBtn.style.display = state.selectedFormat === "Markdown" ? "" : "none";
captureHereBtn.addEventListener("click", () => handleAction("CAPTURE_HERE"));
state.ui.captureHereBtnReference = captureHereBtn;
const cogBtn = footer.createEl("button", { cls: "clickable-icon" });
// Cog gets CSS order 1 in the main footer container so it sits on the left visually
const cogBtn = footer.createEl("button", { cls: "clickable-icon", attr: { style: "order: 1; margin: auto;" } });
cogBtn.innerHTML = ea.obsidian.getIcon("settings").outerHTML;
cogBtn.addEventListener("click", () => {
window.ExcalidrawCaptureNoteScript.tempSearchValue = state.ui.searchInput.getValue().trim();
modal.close();
openSettingsModal();
// Crucially: Do not call tab.close() here.
openSettingsModal(tab);
});
}
async function openCaptureModal(initialSearchValue) {
return new Promise(resolve => {
const modal = new ea.FloatingModal(app);
modal.enableKeyCapture();
return new Promise(async resolve => {
setupCaptureModalEscapeHandler(modal);
// Assess visibility state before grabbing the tab
const sidepanelLeaf = ea.getSidepanelLeaf();
let sidepanelWasVisible = false;
if (sidepanelLeaf && sidepanelLeaf.view.containerEl.offsetParent !== null) {
sidepanelWasVisible = true;
}
modal.modalEl.style.width = "480px";
modal.modalEl.style.maxWidth = "100%";
modal.modalEl.classList.add("excalidraw-capture-note-modal");
const tab = await ea.createSidepanelTab("Capture Contextual Note", false, true);
if (!tab) {
resolve(null);
return;
}
tab.containerEl.classList.add("excalidraw-capture-note-modal");
// 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%";
tab.titleEl.empty();
tab.titleEl.style.display = "flex";
tab.titleEl.style.justifyContent = "space-between";
tab.titleEl.style.alignItems = "center";
tab.titleEl.style.width = "100%";
// Add Main Title
modal.titleEl.createSpan({ text: "Capture Contextual Note" });
tab.titleEl.createSpan({ text: "Capture Contextual Note" });
// Add right-aligned Version string
modal.titleEl.createSpan({
tab.titleEl.createSpan({
text: VERSION,
attr: { style: "font-size: 0.5em; color: var(--text-muted); font-weight: normal; margin-right: 8px;" }
});
@@ -4264,6 +4290,7 @@ async function openCaptureModal(initialSearchValue) {
selectedOntology: "",
allFiles: allFiles,
searchItems: searchItems,
sidepanelWasVisible: sidepanelWasVisible, // Include visibility state
ui: {}
};
@@ -4339,25 +4366,34 @@ async function openCaptureModal(initialSearchValue) {
}
};
modal.onOpen = () => {
const { contentEl } = modal;
tab.onOpen = () => {
const { contentEl } = tab;
contentEl.empty();
injectCaptureModalStyles(contentEl);
buildCaptureFolderBox(contentEl, state);
buildCaptureSearchBox(contentEl, state, callbacks);
buildCaptureLinkTypeSelector(contentEl, state, callbacks);
buildCaptureLinkTypeSelector(contentEl, state, callbacks, tab);
buildCaptureFormatSelector(contentEl, state);
buildCaptureOpenBehaviorSelector(contentEl, state);
buildCaptureOntologySelector(contentEl, state, callbacks);
buildCaptureFooter(contentEl, state, modal);
buildCaptureFooter(contentEl, state, tab);
// Allow normal folder resets to happen on subsequent typing
state.isInitializing = false;
};
modal.onClose = () => resolve(state.finalData);
modal.open();
tab.onClose = () => {
// Clean up the sidepanel if we revealed it just for this script but it didn't complete
if (!state.finalData && !state.sidepanelWasVisible) {
const sidepanelLeaf = ea.getSidepanelLeaf();
if (sidepanelLeaf && sidepanelLeaf.view.containerEl.offsetParent !== null) {
ea.toggleSidepanelView();
}
}
resolve(state.finalData);
};
tab.open();
});
}
@@ -4365,7 +4401,7 @@ async function openCaptureModal(initialSearchValue) {
// 6. UI: Settings & Multi-tier Configuration Modal (Refactored)
// -------------------------------------------------------------
function buildSettingsHeader(contentEl, modal) {
function buildSettingsHeader(contentEl, modal, captureTab) {
const headerContainer = contentEl.createDiv({ cls: "settings-header-container" });
headerContainer.createEl("h2", { text: "DNP Workflows Configuration Panel", attr: { style: "margin:0;" } });
@@ -4373,7 +4409,14 @@ function buildSettingsHeader(contentEl, modal) {
topSaveBtn.addEventListener("click", () => {
ea.setScriptSettings(settings);
modal.close();
start();
// Instead of calling start() and creating an orphaned secondary sidepanel context,
// we instruct the current sidepanel to safely re-paint itself inline.
if (captureTab && typeof captureTab.onOpen === "function") {
captureTab.onOpen();
} else {
start();
}
});
}
@@ -4726,7 +4769,7 @@ function buildNoteTypesSection(contentEl) {
// -------------------------------------------------------------
// Settings Orchestrator
// -------------------------------------------------------------
function openSettingsModal() {
function openSettingsModal(captureTab = null) {
const modal = new ea.obsidian.Modal(app);
modal.titleEl.setText("");
@@ -4748,7 +4791,7 @@ function openSettingsModal() {
`
});
buildSettingsHeader(contentEl, modal);
buildSettingsHeader(contentEl, modal, captureTab);
buildVisualSizingSection(contentEl);
buildVisualTemplateSection(contentEl);
buildPropertyInjectionSection(contentEl);
@@ -19220,8 +19263,8 @@ const extractConfigFromGlobals = () => ({
fillSweep,
branchScale,
baseStrokeWidth,
customPalette: JSON.parse(JSON.stringify(customPalette)),
layoutSettings: JSON.parse(JSON.stringify(layoutSettings))
customPalette: JSON.parse(JSON.stringify(customPalette || { enabled: false, random: false, colors: [] })),
layoutSettings: JSON.parse(JSON.stringify(layoutSettings || {}))
});
let mapPresets = getVal(K_PRESETS, {
@@ -19345,8 +19388,8 @@ const applyPresetToGlobals = (presetName) => {
fillSweep = n.fillSweep;
branchScale = n.branchScale;
baseStrokeWidth = n.baseStrokeWidth;
customPalette = JSON.parse(JSON.stringify(n.customPalette));
layoutSettings = JSON.parse(JSON.stringify(n.layoutSettings));
customPalette = JSON.parse(JSON.stringify(n.customPalette || { enabled: false, random: false, colors: [] }));
layoutSettings = JSON.parse(JSON.stringify(n.layoutSettings || {}));
setVal(K_GROWTH, currentModalGrowthMode);
setVal(K_ARROW_TYPE, arrowType);
@@ -27088,7 +27131,7 @@ const updateUI = (sel) => {
if (cd.customPalette) {
customPalette = JSON.parse(JSON.stringify(cd.customPalette));
} else {
customPalette = getVal(K_PALETTE, { enabled: false, random: false, colors: [] });
customPalette = getVal(K_PALETTE, { enabled: false, random: false, colors: [] }) || { enabled: false, random: false, colors: [] };
}
setVal(K_PALETTE, customPalette, true);
@@ -35779,6 +35822,7 @@ const precision = [1,2,2,3];
const minLigtness = 1/Math.pow(10,precision[2]);
const maxLightness = 100 - minLigtness;
const minSaturation = 1/Math.pow(10,precision[2]);
let dirty = false;
let settings = ea.getScriptSettings();
//set default values on first run
@@ -1884,7 +1884,7 @@ export type ImageInfo = {
isHyperLink?: boolean;
hyperlink?: string;
file?: string | TFile;
hasSVGwithBitmap: boolean;
hasSVGwithBitmap?: boolean;
latex?: string;
size?: Size;
colorMap?: ColorMap;
@@ -4594,7 +4594,7 @@ Content structure:
2. The curated script overview (index-new.md)
3. Raw source of every *.md script in /ea-scripts (each fenced code block is auto-closed to ensure well-formed aggregation)
Generated on: 2026-06-30T13:12:00.813Z
Generated on: 2026-07-04T16:58:43.617Z
---
@@ -6801,7 +6801,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 VERSION = "v.260703";
const FRAME_MARGIN = 10;
if (!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.23.8")) {
@@ -7319,15 +7319,28 @@ async function ensureTargetFileExists(folder, filename, fname, opt, noteType) {
// Resolves the Obsidian leaf behavior and explicitly waits for load instantiation
async function openAndResolveTargetLeaf(file, originView, openNoteBBehavior) {
let noteBWorkspaceLeaf;
if (openNoteBBehavior === "adjacent pane") {
noteBWorkspaceLeaf = ea.openFileInNewOrAdjacentLeaf(file);
} else if (openNoteBBehavior === "new tab") {
noteBWorkspaceLeaf = app.workspace.getLeaf("tab");
await noteBWorkspaceLeaf.openFile(file, { active: true });
let noteBWorkspaceLeaf = null;
// Check if the file is already open in any existing leaf
app.workspace.iterateAllLeaves((leaf) => {
if (leaf.view && leaf.view.file && leaf.view.file.path === file.path) {
noteBWorkspaceLeaf = leaf;
}
});
if (noteBWorkspaceLeaf) {
app.workspace.setActiveLeaf(noteBWorkspaceLeaf, { focus: true });
} else {
noteBWorkspaceLeaf = originView.leaf;
await noteBWorkspaceLeaf.openFile(file, { active: true });
// Standard logic if it is not open yet
if (openNoteBBehavior === "adjacent pane") {
noteBWorkspaceLeaf = ea.openFileInNewOrAdjacentLeaf(file);
} else if (openNoteBBehavior === "new tab") {
noteBWorkspaceLeaf = app.workspace.getLeaf("tab");
await noteBWorkspaceLeaf.openFile(file, { active: true });
} else {
noteBWorkspaceLeaf = originView.leaf;
await noteBWorkspaceLeaf.openFile(file, { active: true });
}
}
// Explicitly wait until the target leaf has fully instantiated its File representation
@@ -8050,11 +8063,23 @@ async function start() {
const captureData = await openCaptureModal(initialLinkText);
if (!captureData) return;
const { filename, noteType, format, ontologyAction, actionType, openNoteBBehavior, folder: customFolder } = captureData;
const { filename, noteType, format, ontologyAction, actionType, openNoteBBehavior, folder: customFolder, sidepanelWasVisible } = captureData;
// Inline cleanup helper attached to visibility flag
const closeSidepanelIfNeeded = () => {
if (!sidepanelWasVisible) {
const sidepanelLeaf = ea.getSidepanelLeaf();
if (sidepanelLeaf && sidepanelLeaf.view.containerEl.offsetParent !== null) {
ea.toggleSidepanelView();
}
}
};
const opt = settings.noteTypes[noteType];
if (!opt) {
new Notice("Error: Note Type configuration is missing. Open Settings to configure Note Types.");
closeSidepanelIfNeeded();
return;
}
@@ -8106,7 +8131,10 @@ async function start() {
if (!hasNoteType) {
const conflictDecision = await resolveExistingFileConflict(fileTarget, hasNoteType, hasPrefix, opt.prefix);
if (!conflictDecision) return;
if (!conflictDecision) {
closeSidepanelIfNeeded();
return;
}
if (conflictDecision.action === "CREATE_NEW") {
fileTarget = null;
@@ -8151,6 +8179,7 @@ async function start() {
ea.addText(0, 0, targetWikiLink);
await ea.addElementsToView(true, true, true);
ea.clear();
closeSidepanelIfNeeded();
return;
}
@@ -8165,6 +8194,7 @@ async function start() {
ea.clear();
}
new Notice(`Created file: ${file.basename}`);
closeSidepanelIfNeeded();
return;
}
@@ -8185,7 +8215,10 @@ async function start() {
// 9. Ensure Target View is Excalidraw and get API
const target_ea = await prepareTargetExcalidrawView(noteBWorkspaceLeaf);
if (!target_ea) return;
if (!target_ea) {
closeSidepanelIfNeeded();
return;
}
// 10. Calculate insertion bounds on Target Note
const bElements = target_ea.getViewElements();
@@ -8208,39 +8241,15 @@ async function start() {
// 12. Final Focus / Zoom
await handleFinalActionFocus(actionType, originView, noteBWorkspaceLeaf, embeddedElementId, target_ea, format, preGeneratedFrameID, clonedTemplateElementIds, mmAPI);
// 13. Sidepanel cleanup
closeSidepanelIfNeeded();
}
// -------------------------------------------------------------
// 5. UI: Capture Note Modal (Refactored)
// -------------------------------------------------------------
function setupCaptureModalEscapeHandler(modal) {
const escapeKey = modal.scope.keys.find(k => k.key === "Escape");
if (escapeKey) {
const originalFunc = escapeKey.func;
escapeKey.func = (e) => {
// Block modal closure if a child suggester was just closed
if (suppressEscape) return false;
// Block modal closure if custom dropdown is open
const customDropdown = modal.modalEl.querySelector(".mindmap-search-results");
if (customDropdown && customDropdown.style.display === "block") {
customDropdown.style.display = "none";
return false;
}
// Block modal closure if any standard Obsidian suggester is currently open
const suggests = document.body.querySelectorAll('.suggestion-container');
for (const s of suggests) {
if (s.style.display !== "none") {
return false;
}
}
return originalFunc(e);
};
}
}
function injectCaptureModalStyles(contentEl) {
contentEl.createEl("style", {
text: `
@@ -8255,42 +8264,31 @@ function injectCaptureModalStyles(contentEl) {
.mindmap-search-item.is-selected { background-color: var(--background-modifier-hover); }
.link-type-row-control { display: flex; align-items: center; gap: 8px; width: 100%; justify-content: flex-end; }
/* Modal Restyling for single-row / responsive layouts */
/* Fluid Container-Agnostic Layout (No @media queries needed) */
.excalidraw-capture-note-modal .setting-item {
display: flex;
flex-wrap: wrap;
flex-wrap: wrap; /* Allows wrapping when sidepanel is thin */
align-items: center;
justify-content: space-between;
gap: 12px;
gap: 8px;
padding: 8px 0; /* Shrink vertical padding */
min-height: auto; /* Override native Obsidian large min-height on mobile */
border-top: none;
}
.excalidraw-capture-note-modal .setting-item-info {
flex: 0 1 auto;
white-space: nowrap;
min-width: max-content;
flex: 1 1 120px; /* Base width of 120px, grows if space permits */
white-space: normal;
margin-top: 4px;
}
.excalidraw-capture-note-modal .setting-item-control {
flex: 1 1 200px;
flex: 2 1 200px; /* Base width of 200px. If container < 320px, it wraps to next line */
justify-content: flex-end;
min-width: 200px;
width: 100%; /* Expands to full width when wrapped */
}
.excalidraw-capture-note-modal .setting-item-control input[type="text"],
.excalidraw-capture-note-modal .setting-item-control select {
width: 100%;
}
@media (max-width: 450px) {
.excalidraw-capture-note-modal .setting-item {
flex-direction: column;
align-items: flex-start;
gap: 4px;
}
.excalidraw-capture-note-modal .setting-item-control {
width: 100%;
justify-content: stretch;
}
.excalidraw-capture-note-modal .setting-item-info {
white-space: normal;
}
}
`
});
}
@@ -8541,7 +8539,7 @@ function buildCaptureSearchBox(contentEl, state, callbacks) {
}
}
function buildCaptureLinkTypeSelector(contentEl, state, callbacks) {
function buildCaptureLinkTypeSelector(contentEl, state, callbacks, tab) {
const noteTypeKeys = Object.keys(settings.noteTypes).sort();
let selectedNoteType = state.selectedNoteType;
if (!selectedNoteType || !noteTypeKeys.includes(selectedNoteType)) {
@@ -8628,18 +8626,12 @@ function buildCaptureLinkTypeSelector(contentEl, state, callbacks) {
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();
if(tab && typeof tab.onOpen === "function") {
tab.onOpen(); // Re-render the capture tab inline
}
}, true);
});
});
@@ -8695,12 +8687,16 @@ function buildCaptureOntologySelector(contentEl, state, callbacks) {
});
}
function buildCaptureFooter(contentEl, state, modal) {
function buildCaptureFooter(contentEl, state, tab) {
// Footer is a normal non-wrapping flex row. `align-items: flex-end` forces the cog down when the button group expands vertically.
const footer = contentEl.createDiv({
attr: { style: "display: flex; justify-content: space-between; align-items: center; margin-top: 20px; flex-direction: row-reverse;" }
attr: { style: "display: flex; justify-content: space-between; align-items: flex-end; margin-top: 20px; gap: 10px; margin-bottom: 30px;" }
});
const buttonGroup = footer.createDiv({ attr: { style: "display: flex; gap: 8px; flex-direction: row-reverse;" } });
// buttonGroup gets CSS order 2 so it sits on the right visually
const buttonGroup = footer.createDiv({
attr: { style: "display: flex; gap: 8px; flex-wrap: wrap; justify-content: flex-end; flex: 1 1 auto; order: 2;" }
});
const handleAction = (actionType) => {
const val = state.ui.searchInput.getValue().trim();
@@ -8711,62 +8707,92 @@ function buildCaptureFooter(contentEl, state, modal) {
state.finalData = {
filename: val,
folder: folderVal,
useRelativeFolder: state.useRelativeFolder, // Append relative setting state
useRelativeFolder: state.useRelativeFolder,
noteType: state.selectedNoteType,
format: state.selectedFormat,
ontologyAction: state.selectedOntology,
actionType,
openNoteBBehavior: state.openNoteBBehavior
openNoteBBehavior: state.openNoteBBehavior,
sidepanelWasVisible: state.sidepanelWasVisible
};
modal.close();
tab.close();
};
const captureBtn = buttonGroup.createEl("button", { text: "Capture Note", cls: "mod-cta" });
// Assign CSS `order` so visual LTR layout matches standard wrap behavior
// (Items with higher order appear further right, and will drop to the bottom line first when wrapped)
const captureBtn = buttonGroup.createEl("button", {
text: "Capture",
cls: "mod-cta",
attr: {
style: "order: 4;",
"aria-label": "Create the note, add backlinks/embeds, and open it for editing."
}
});
captureBtn.addEventListener("click", () => handleAction("CAPTURE"));
const linkOnlyBtn = buttonGroup.createEl("button", { text: "Link Only" });
const linkOnlyBtn = buttonGroup.createEl("button", {
text: "Link",
attr: {
style: "order: 3;",
"aria-label": "Link to an item without creating the note and without opening it for editing."
}
});
linkOnlyBtn.addEventListener("click", () => handleAction("ADD_LINK_ONLY"));
const linkCreateBtn = buttonGroup.createEl("button", { text: "Link & Create" });
const linkCreateBtn = buttonGroup.createEl("button", {
text: "Link + File",
attr: {
style: "order: 2;",
"aria-label": "Link to the item and create its note/file in the background (but do not open for note taking)."
}
});
linkCreateBtn.addEventListener("click", () => handleAction("ADD_LINK_CREATE"));
const captureHereBtn = buttonGroup.createEl("button", { text: "Capture Here" });
const captureHereBtn = buttonGroup.createEl("button", { text: "Capture Here", attr: { style: "order: 1;" } });
captureHereBtn.style.display = state.selectedFormat === "Markdown" ? "" : "none";
captureHereBtn.addEventListener("click", () => handleAction("CAPTURE_HERE"));
state.ui.captureHereBtnReference = captureHereBtn;
const cogBtn = footer.createEl("button", { cls: "clickable-icon" });
// Cog gets CSS order 1 in the main footer container so it sits on the left visually
const cogBtn = footer.createEl("button", { cls: "clickable-icon", attr: { style: "order: 1; margin: auto;" } });
cogBtn.innerHTML = ea.obsidian.getIcon("settings").outerHTML;
cogBtn.addEventListener("click", () => {
window.ExcalidrawCaptureNoteScript.tempSearchValue = state.ui.searchInput.getValue().trim();
modal.close();
openSettingsModal();
// Crucially: Do not call tab.close() here.
openSettingsModal(tab);
});
}
async function openCaptureModal(initialSearchValue) {
return new Promise(resolve => {
const modal = new ea.FloatingModal(app);
modal.enableKeyCapture();
return new Promise(async resolve => {
setupCaptureModalEscapeHandler(modal);
// Assess visibility state before grabbing the tab
const sidepanelLeaf = ea.getSidepanelLeaf();
let sidepanelWasVisible = false;
if (sidepanelLeaf && sidepanelLeaf.view.containerEl.offsetParent !== null) {
sidepanelWasVisible = true;
}
modal.modalEl.style.width = "480px";
modal.modalEl.style.maxWidth = "100%";
modal.modalEl.classList.add("excalidraw-capture-note-modal");
const tab = await ea.createSidepanelTab("Capture Contextual Note", false, true);
if (!tab) {
resolve(null);
return;
}
tab.containerEl.classList.add("excalidraw-capture-note-modal");
// 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%";
tab.titleEl.empty();
tab.titleEl.style.display = "flex";
tab.titleEl.style.justifyContent = "space-between";
tab.titleEl.style.alignItems = "center";
tab.titleEl.style.width = "100%";
// Add Main Title
modal.titleEl.createSpan({ text: "Capture Contextual Note" });
tab.titleEl.createSpan({ text: "Capture Contextual Note" });
// Add right-aligned Version string
modal.titleEl.createSpan({
tab.titleEl.createSpan({
text: VERSION,
attr: { style: "font-size: 0.5em; color: var(--text-muted); font-weight: normal; margin-right: 8px;" }
});
@@ -8846,6 +8872,7 @@ async function openCaptureModal(initialSearchValue) {
selectedOntology: "",
allFiles: allFiles,
searchItems: searchItems,
sidepanelWasVisible: sidepanelWasVisible, // Include visibility state
ui: {}
};
@@ -8921,25 +8948,34 @@ async function openCaptureModal(initialSearchValue) {
}
};
modal.onOpen = () => {
const { contentEl } = modal;
tab.onOpen = () => {
const { contentEl } = tab;
contentEl.empty();
injectCaptureModalStyles(contentEl);
buildCaptureFolderBox(contentEl, state);
buildCaptureSearchBox(contentEl, state, callbacks);
buildCaptureLinkTypeSelector(contentEl, state, callbacks);
buildCaptureLinkTypeSelector(contentEl, state, callbacks, tab);
buildCaptureFormatSelector(contentEl, state);
buildCaptureOpenBehaviorSelector(contentEl, state);
buildCaptureOntologySelector(contentEl, state, callbacks);
buildCaptureFooter(contentEl, state, modal);
buildCaptureFooter(contentEl, state, tab);
// Allow normal folder resets to happen on subsequent typing
state.isInitializing = false;
};
modal.onClose = () => resolve(state.finalData);
modal.open();
tab.onClose = () => {
// Clean up the sidepanel if we revealed it just for this script but it didn't complete
if (!state.finalData && !state.sidepanelWasVisible) {
const sidepanelLeaf = ea.getSidepanelLeaf();
if (sidepanelLeaf && sidepanelLeaf.view.containerEl.offsetParent !== null) {
ea.toggleSidepanelView();
}
}
resolve(state.finalData);
};
tab.open();
});
}
@@ -8947,7 +8983,7 @@ async function openCaptureModal(initialSearchValue) {
// 6. UI: Settings & Multi-tier Configuration Modal (Refactored)
// -------------------------------------------------------------
function buildSettingsHeader(contentEl, modal) {
function buildSettingsHeader(contentEl, modal, captureTab) {
const headerContainer = contentEl.createDiv({ cls: "settings-header-container" });
headerContainer.createEl("h2", { text: "DNP Workflows Configuration Panel", attr: { style: "margin:0;" } });
@@ -8955,7 +8991,14 @@ function buildSettingsHeader(contentEl, modal) {
topSaveBtn.addEventListener("click", () => {
ea.setScriptSettings(settings);
modal.close();
start();
// Instead of calling start() and creating an orphaned secondary sidepanel context,
// we instruct the current sidepanel to safely re-paint itself inline.
if (captureTab && typeof captureTab.onOpen === "function") {
captureTab.onOpen();
} else {
start();
}
});
}
@@ -9308,7 +9351,7 @@ function buildNoteTypesSection(contentEl) {
// -------------------------------------------------------------
// Settings Orchestrator
// -------------------------------------------------------------
function openSettingsModal() {
function openSettingsModal(captureTab = null) {
const modal = new ea.obsidian.Modal(app);
modal.titleEl.setText("");
@@ -9330,7 +9373,7 @@ function openSettingsModal() {
`
});
buildSettingsHeader(contentEl, modal);
buildSettingsHeader(contentEl, modal, captureTab);
buildVisualSizingSection(contentEl);
buildVisualTemplateSection(contentEl);
buildPropertyInjectionSection(contentEl);
@@ -23802,8 +23845,8 @@ const extractConfigFromGlobals = () => ({
fillSweep,
branchScale,
baseStrokeWidth,
customPalette: JSON.parse(JSON.stringify(customPalette)),
layoutSettings: JSON.parse(JSON.stringify(layoutSettings))
customPalette: JSON.parse(JSON.stringify(customPalette || { enabled: false, random: false, colors: [] })),
layoutSettings: JSON.parse(JSON.stringify(layoutSettings || {}))
});
let mapPresets = getVal(K_PRESETS, {
@@ -23927,8 +23970,8 @@ const applyPresetToGlobals = (presetName) => {
fillSweep = n.fillSweep;
branchScale = n.branchScale;
baseStrokeWidth = n.baseStrokeWidth;
customPalette = JSON.parse(JSON.stringify(n.customPalette));
layoutSettings = JSON.parse(JSON.stringify(n.layoutSettings));
customPalette = JSON.parse(JSON.stringify(n.customPalette || { enabled: false, random: false, colors: [] }));
layoutSettings = JSON.parse(JSON.stringify(n.layoutSettings || {}));
setVal(K_GROWTH, currentModalGrowthMode);
setVal(K_ARROW_TYPE, arrowType);
@@ -31670,7 +31713,7 @@ const updateUI = (sel) => {
if (cd.customPalette) {
customPalette = JSON.parse(JSON.stringify(cd.customPalette));
} else {
customPalette = getVal(K_PALETTE, { enabled: false, random: false, colors: [] });
customPalette = getVal(K_PALETTE, { enabled: false, random: false, colors: [] }) || { enabled: false, random: false, colors: [] };
}
setVal(K_PALETTE, customPalette, true);
@@ -40361,6 +40404,7 @@ const precision = [1,2,2,3];
const minLigtness = 1/Math.pow(10,precision[2]);
const maxLightness = 100 - minLigtness;
const minSaturation = 1/Math.pow(10,precision[2]);
let dirty = false;
let settings = ea.getScriptSettings();
//set default values on first run
@@ -44808,6 +44852,49 @@ Two files follow. First the template startup script with documenation comments,
*/
//ea.onCanvasColorChangeHook = (ea, view, color) => {};
/**
* If set, this callback is triggered when the scene changes in the target view.
* You can use this to react to appState or element changes. Any script can sign up for updates via this hook.
*
* ⚠️ WARNING: PERFORMANCE IMPACT ⚠️
* Because this hook fires extremely frequently (dozens of times per second during drawing/panning),
* you MUST specify the appState keys you want to track (e.g., ['zoom', 'scrollX', 'scrollY'])
* OR set trackElements to true.
* If trackElements is falsy and appStateKeys is empty or undefined, the hook is ignored to prevent severe performance degradation.
*
* For sidepanel tabs, there is an additional filter: if triggerWhenInvisible is false,
* the callback will only trigger when the sidepanel is visible and the tab is active.
*
* Signature:
* onSceneChangeHook: {
* appStateKeys?: (keyof AppState)[];
* trackElements?: boolean;
* triggerWhenInvisible?: boolean;
* callback: (
* elements: readonly ExcalidrawElement[],
* appState: AppState,
* files: BinaryFiles,
* //Note: the ea object will not be set to the view and might be dirty
* //best practice: `ea.setView(view); ea.clear();`
* view: ExcalidrawView,
* ea: ExcalidrawAutomate
* ) => void;
* } | null = null;
*/
// ea.onSceneChangeHook = {
// appStateKeys: ["zoom", "scrollX", "scrollY"],
// trackElements: true,
// triggerWhenInvisible: false,
// callback: (elements, appState, files, view, hookEA) => {
// console.log(`Scene changed in ${view.file?.basename}:`, {
// zoom: appState.zoom.value,
// scrollX: appState.scrollX,
// scrollY: appState.scrollY,
// elementCount: elements.length
// });
// }
// };
<!-- docs/AITrainingData/ExcalidrawStartupExample.md -->
/*
#exclude
@@ -45536,3 +45623,161 @@ ea.onTriggerAutoexportHook = (data) => {
// const decodedObsidianURI = decodeURIComponent(data.obsidianLink);
//};
/**
* If set, this callback is triggered when the scene changes in the target view.
* You can use this to react to appState or element changes. Any script can sign up for updates via this hook.
*
* ⚠️ WARNING: PERFORMANCE IMPACT ⚠️
* Because this hook fires extremely frequently (dozens of times per second during drawing/panning),
* you MUST specify the appState keys you want to track (e.g., ['zoom', 'scrollX', 'scrollY'])
* OR set trackElements to true.
* If trackElements is falsy and appStateKeys is empty or undefined, the hook is ignored to prevent severe performance degradation.
*
* For sidepanel tabs, there is an additional filter: if triggerWhenInvisible is false,
* the callback will only trigger when the sidepanel is visible and the tab is active.
*
* Signature:
* onSceneChangeHook: {
* appStateKeys?: (keyof AppState)[];
* trackElements?: boolean;
* triggerWhenInvisible?: boolean;
* callback: (
* elements: readonly ExcalidrawElement[],
* appState: AppState,
* files: BinaryFiles,
* //Note: the ea object will not be set to the view and might be dirty
* //best practice: `ea.setView(view); ea.clear();`
* view: ExcalidrawView,
* ea: ExcalidrawAutomate
* ) => void;
* } | null = null;
*/
// ea.onSceneChangeHook = {
// appStateKeys: ["zoom", "scrollX", "scrollY"],
// trackElements: true,
// triggerWhenInvisible: false,
// callback: (elements, appState, files, view, hookEA) => {
// console.log(`Scene changed in ${view.file?.basename}:`, {
// zoom: appState.zoom.value,
// scrollX: appState.scrollX,
// scrollY: appState.scrollY,
// elementCount: elements.length
// });
// }
// };
// 1. Define the tools that should remember their own distinct styles.
// (We exclude tools like "selection", "eraser", or "laser" where persistent styling doesn't apply)
const STYLED_TOOLS = [
"freedraw",
"arrow",
"line",
"rectangle",
"ellipse",
"diamond",
"text"
];
// 2. Define all the specific AppState style properties we want to track and persist
const STYLES_TO_TRACK = [
"currentItemStrokeColor",
"currentItemBackgroundColor",
"currentItemFillStyle",
"currentItemStrokeWidth",
"currentItemStrokeWidthKey",
"currentItemStrokeStyle",
"currentItemRoughness",
"currentItemStrokeVariability",
"currentItemOpacity",
"currentItemFontFamily",
"currentItemFontSize",
"currentItemTextAlign",
"currentItemStartArrowhead",
"currentItemEndArrowhead",
"currentItemRoundness",
"currentItemArrowType",
"currentStrokeOptions" // Used by Custom Pens
];
// 3. Initialize the global cache, loading from localStorage so settings survive app restarts
if (!window.ExcalidrawToolStyleCache) {
const saved = localStorage.getItem("ExcalidrawToolStyleCache");
window.ExcalidrawToolStyleCache = saved ? JSON.parse(saved) : {};
}
// 4. Register the Hook
ea.onSceneChangeHook = {
// Only trigger the hook when the active tool or one of our tracked styles changes
appStateKeys: ["activeTool", ...STYLES_TO_TRACK],
trackElements: false,
triggerWhenInvisible: false,
callback: (elements, appState, files, view, ea) => {
const activeTool = appState.activeTool?.type;
if (!activeTool) return;
ea.setView(view);
ea.clear();
const cache = window.ExcalidrawToolStyleCache;
// We store the "last tool" state locally on the view instance.
// This prevents bugs if you have multiple Excalidraw panes open side-by-side.
const lastTool = view.excalidrawToolStyle_lastActiveTool;
// --- SCENARIO A: The User Switched Tools ---
if (activeTool !== lastTool) {
view.excalidrawToolStyle_lastActiveTool = activeTool;
// If the new tool is one of our managed drawing tools, restore its stored style
if (STYLED_TOOLS.includes(activeTool)) {
const storedStyle = cache[activeTool];
if (storedStyle) {
// Flag that we are applying a style programmatically so we don't treat it as a user modification
view.excalidrawToolStyle_applyingStyle = true;
ea.getExcalidrawAPI().updateScene({
appState: storedStyle
});
}
}
}
// --- SCENARIO B: The Tool Stayed the Same (User is tweaking styles) ---
else {
// Ignore the onSceneChange that gets fired immediately after we programmatically restore a style
if (view.excalidrawToolStyle_applyingStyle) {
view.excalidrawToolStyle_applyingStyle = false;
return;
}
// If we are actively using a drawing tool, track its style changes and update the cache
if (STYLED_TOOLS.includes(activeTool)) {
const currentStyle = {};
let styleChanged = false;
const storedStyle = cache[activeTool] || {};
for (const key of STYLES_TO_TRACK) {
currentStyle[key] = appState[key];
const val1 = currentStyle[key];
const val2 = storedStyle[key];
// Deep compare objects (like Roundness or Custom Pens settings), direct compare primitives
if (typeof val1 === "object" || typeof val2 === "object") {
if (JSON.stringify(val1) !== JSON.stringify(val2)) {
styleChanged = true;
}
} else if (val1 !== val2) {
styleChanged = true;
}
}
// If a change was detected, update the cache and persist it to localStorage
if (styleChanged) {
cache[activeTool] = currentStyle;
localStorage.setItem("ExcalidrawToolStyleCache", JSON.stringify(cache));
}
}
}
}
};
@@ -725,3 +725,160 @@ ea.onTriggerAutoexportHook = (data) => {
// const decodedObsidianURI = decodeURIComponent(data.obsidianLink);
//};
/**
* If set, this callback is triggered when the scene changes in the target view.
* You can use this to react to appState or element changes. Any script can sign up for updates via this hook.
*
* ⚠️ WARNING: PERFORMANCE IMPACT ⚠️
* Because this hook fires extremely frequently (dozens of times per second during drawing/panning),
* you MUST specify the appState keys you want to track (e.g., ['zoom', 'scrollX', 'scrollY'])
* OR set trackElements to true.
* If trackElements is falsy and appStateKeys is empty or undefined, the hook is ignored to prevent severe performance degradation.
*
* For sidepanel tabs, there is an additional filter: if triggerWhenInvisible is false,
* the callback will only trigger when the sidepanel is visible and the tab is active.
*
* Signature:
* onSceneChangeHook: {
* appStateKeys?: (keyof AppState)[];
* trackElements?: boolean;
* triggerWhenInvisible?: boolean;
* callback: (
* elements: readonly ExcalidrawElement[],
* appState: AppState,
* files: BinaryFiles,
* //Note: the ea object will not be set to the view and might be dirty
* //best practice: `ea.setView(view); ea.clear();`
* view: ExcalidrawView,
* ea: ExcalidrawAutomate
* ) => void;
* } | null = null;
*/
// ea.onSceneChangeHook = {
// appStateKeys: ["zoom", "scrollX", "scrollY"],
// trackElements: true,
// triggerWhenInvisible: false,
// callback: (elements, appState, files, view, hookEA) => {
// console.log(`Scene changed in ${view.file?.basename}:`, {
// zoom: appState.zoom.value,
// scrollX: appState.scrollX,
// scrollY: appState.scrollY,
// elementCount: elements.length
// });
// }
// };
// 1. Define the tools that should remember their own distinct styles.
// (We exclude tools like "selection", "eraser", or "laser" where persistent styling doesn't apply)
const STYLED_TOOLS = [
"freedraw",
"arrow",
"line",
"rectangle",
"ellipse",
"diamond",
"text"
];
// 2. Define all the specific AppState style properties we want to track and persist
const STYLES_TO_TRACK = [
"currentItemStrokeColor",
"currentItemBackgroundColor",
"currentItemFillStyle",
"currentItemStrokeWidth",
"currentItemStrokeWidthKey",
"currentItemStrokeStyle",
"currentItemRoughness",
"currentItemStrokeVariability",
"currentItemOpacity",
"currentItemFontFamily",
"currentItemFontSize",
"currentItemTextAlign",
"currentItemStartArrowhead",
"currentItemEndArrowhead",
"currentItemRoundness",
"currentItemArrowType",
"currentStrokeOptions" // Used by Custom Pens
];
// 3. Initialize the global cache, loading from localStorage so settings survive app restarts
if (!window.ExcalidrawToolStyleCache) {
const saved = localStorage.getItem("ExcalidrawToolStyleCache");
window.ExcalidrawToolStyleCache = saved ? JSON.parse(saved) : {};
}
// 4. Register the Hook
ea.onSceneChangeHook = {
// Only trigger the hook when the active tool or one of our tracked styles changes
appStateKeys: ["activeTool", ...STYLES_TO_TRACK],
trackElements: false,
triggerWhenInvisible: false,
callback: (elements, appState, files, view, ea) => {
const activeTool = appState.activeTool?.type;
if (!activeTool) return;
ea.setView(view);
ea.clear();
const cache = window.ExcalidrawToolStyleCache;
// We store the "last tool" state locally on the view instance.
// This prevents bugs if you have multiple Excalidraw panes open side-by-side.
const lastTool = view.excalidrawToolStyle_lastActiveTool;
// --- SCENARIO A: The User Switched Tools ---
if (activeTool !== lastTool) {
view.excalidrawToolStyle_lastActiveTool = activeTool;
// If the new tool is one of our managed drawing tools, restore its stored style
if (STYLED_TOOLS.includes(activeTool)) {
const storedStyle = cache[activeTool];
if (storedStyle) {
// Flag that we are applying a style programmatically so we don't treat it as a user modification
view.excalidrawToolStyle_applyingStyle = true;
ea.getExcalidrawAPI().updateScene({
appState: storedStyle
});
}
}
}
// --- SCENARIO B: The Tool Stayed the Same (User is tweaking styles) ---
else {
// Ignore the onSceneChange that gets fired immediately after we programmatically restore a style
if (view.excalidrawToolStyle_applyingStyle) {
view.excalidrawToolStyle_applyingStyle = false;
return;
}
// If we are actively using a drawing tool, track its style changes and update the cache
if (STYLED_TOOLS.includes(activeTool)) {
const currentStyle = {};
let styleChanged = false;
const storedStyle = cache[activeTool] || {};
for (const key of STYLES_TO_TRACK) {
currentStyle[key] = appState[key];
const val1 = currentStyle[key];
const val2 = storedStyle[key];
// Deep compare objects (like Roundness or Custom Pens settings), direct compare primitives
if (typeof val1 === "object" || typeof val2 === "object") {
if (JSON.stringify(val1) !== JSON.stringify(val2)) {
styleChanged = true;
}
} else if (val1 !== val2) {
styleChanged = true;
}
}
// If a change was detected, update the cache and persist it to localStorage
if (styleChanged) {
cache[activeTool] = currentStyle;
localStorage.setItem("ExcalidrawToolStyleCache", JSON.stringify(cache));
}
}
}
}
};
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.25.1-beta.0",
"version": "2.25.1",
"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.0",
"version": "2.25.1",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+41
View File
@@ -277,3 +277,44 @@
* ) => void = null;
*/
//ea.onCanvasColorChangeHook = (ea, view, color) => {};
/**
* If set, this callback is triggered when the scene changes in any of the Excalidraw Views.
* You can use this to react to appState or element changes.
* Note, the ea object the callback receives is not guaranteed to have its targetView set to view, and the EA workbench might be dirty.
* As best practice, if you want to write back to the sending view, I recommend initializing ExcalidrawView first inside the callback:
* ea.setView(view); ea.clear();
*
* WARNING: PERFORMANCE IMPACT
* Because this hook fires extremely frequently (dozens of times per second during drawing/panning),
* you MUST specify the appState keys you want to track (e.g., ['zoom', 'scrollX', 'scrollY'])
* OR set trackElements to true.
* If trackElements is falsy and appStateKeys is empty or undefined, the hook is ignored to prevent severe performance degradation.
*
* Signature:
* onSceneChangeHook: {
* appStateKeys?: (keyof AppState)[];
* trackElements?: boolean;
* triggerWhenInvisible?: boolean;
* callback: (
* elements: readonly ExcalidrawElement[],
* appState: AppState,
* files: BinaryFiles,
* view: ExcalidrawView,
* ea: ExcalidrawAutomate
* ) => void;
* } | null = null;
*/
// ea.onSceneChangeHook = {
// appStateKeys: ["zoom", "scrollX", "scrollY"],
// trackElements: true,
// triggerWhenInvisible: false,
// callback: (elements, appState, files, view, hookEA) => {
// console.log(`Scene changed in ${view.file?.basename}:`, {
// zoom: appState.zoom.value,
// scrollX: appState.scrollX,
// scrollY: appState.scrollY,
// elementCount: elements.length
// });
// }
// };
+2 -2
View File
@@ -9,5 +9,5 @@ console.log("String copied to clipboard");
export const startupScript = () =>
atob(
"LyoKI2V4Y2x1ZGUKYGBganMqLwovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCB3aGVuIH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ICovCi8vZWEub25QYXN0ZUhvb2sgPSAoZGF0YSkgPT4ge307CgovKioKICogaWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCwgd2hlbiBhbiBFeGNhbGlkcmF3IGZpbGUgaXLine truncated
);
+4 -3
View File
@@ -912,7 +912,7 @@ export default class ExcalidrawPlugin extends Plugin {
}
this.logStartupEvent("Styles manager initialized");
this.updatePhoneFooterSafeAreaPadding();
this.updateFooterSafeAreaPadding();
try {
this.scriptEngine = new ScriptEngine(this);
@@ -1162,13 +1162,14 @@ export default class ExcalidrawPlugin extends Plugin {
});
}
public updatePhoneFooterSafeAreaPadding() {
public updateFooterSafeAreaPadding() {
const documents = new Set<Document>([
mainDocument,
...this.getOpenObsidianDocuments(),
]);
const shouldEnable =
DEVICE.isPhone && this.settings?.phoneFooterSafeAreaPadding;
(DEVICE.isPhone && this.settings?.phoneFooterSafeAreaPadding) ||
(DEVICE.isTablet && this.settings?.tabletFooterSafeAreaPadding);
documents.forEach((ownerDocument) => {
const existingStylesheet = ownerDocument.getElementById(
+16 -1
View File
@@ -78,6 +78,7 @@ export interface ExcalidrawSettings {
copyFrameLinkByName: boolean;
disableDoubleClickTextEditing: boolean;
phoneFooterSafeAreaPadding: boolean;
tabletFooterSafeAreaPadding: boolean;
folder: string;
cropFolder: string;
annotateFolder: string;
@@ -562,6 +563,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
copyFrameLinkByName: false,
disableDoubleClickTextEditing: false,
phoneFooterSafeAreaPadding: false,
tabletFooterSafeAreaPadding: false,
folder: "Excalidraw",
cropFolder: "",
annotateFolder: "",
@@ -2663,7 +2665,20 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setValue(this.plugin.settings.phoneFooterSafeAreaPadding)
.onChange(async (value) => {
this.plugin.settings.phoneFooterSafeAreaPadding = value;
this.plugin.updatePhoneFooterSafeAreaPadding();
this.plugin.updateFooterSafeAreaPadding();
this.applySettingsUpdate();
}),
);
new Setting(detailsEl)
.setName(t("TABLET_FOOTER_SAFE_AREA_PADDING_NAME"))
.setDesc(fragWithHTML(t("TABLET_FOOTER_SAFE_AREA_PADDING_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.tabletFooterSafeAreaPadding)
.onChange(async (value) => {
this.plugin.settings.tabletFooterSafeAreaPadding = value;
this.plugin.updateFooterSafeAreaPadding();
this.applySettingsUpdate();
}),
);
+6
View File
@@ -16,6 +16,8 @@ declare const PLUGIN_VERSION: string;
// English
export default {
INITIALIZATION_MESSAGE:
"Excalidraw is waiting for Obsidian to initialize all of your plugins...",
// Sugester
SELECT_FILE_TO_INSERT: "Select a file to insert",
// main.ts
@@ -621,6 +623,10 @@ export default {
"Extra bottom padding for phone controls",
PHONE_FOOTER_SAFE_AREA_PADDING_DESC:
"Adds extra bottom padding to the Excalidraw footer controls so zoom and undo buttons stay above the system navigation bar on phones. This setting only applies on phones.",
TABLET_FOOTER_SAFE_AREA_PADDING_NAME:
"Extra bottom padding for tablet controls",
TABLET_FOOTER_SAFE_AREA_PADDING_DESC:
"Adds extra bottom padding to the Excalidraw footer controls so zoom and undo buttons stay above the system navigation bar on tablets. This setting only applies on tablets.",
DEFAULT_PEN_MODE_NAME: "Pen mode",
DEFAULT_PEN_MODE_DESC:
"Should pen mode be automatically enabled when opening Excalidraw?",
+7 -1
View File
@@ -17,9 +17,15 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
`,
"2.25.1": `
"2.25.1": `
This is a very minor update to fix a small regression in 2.25.0
## Fixed
- Excalidraw Automate Color Picker component used in Shade Master broke in 2.25.0. It is now restored.
## New
- Separate setting to enable extra bottom padding for tablet controls. This is useful for tablets with a system navigation bar that overlaps the Excalidraw footer controls. [#2833](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2833)
- Added \`onSceneChangeHook\` to Excalidraw Startup Script template.
`,
"2.25.0": `
${getYouTubeDiv("aqt5NJE2sJ8")}
+22 -6
View File
@@ -1,11 +1,17 @@
import { App, FileView, WorkspaceLeaf } from "obsidian";
import { DEVICE, VIEW_TYPE_EXCALIDRAW_LOADING } from "src/constants/constants";
import { DEVICE, VIEW_TYPE_EXCALIDRAW } from "src/constants/constants";
import ExcalidrawPlugin from "src/core/main";
import { t } from "src/lang/helpers";
import { setElementDisplay } from "src/utils/htmlUtils";
import { isUnwantedLeaf, setExcalidrawView } from "src/utils/obsidianUtils";
import { isUnwantedLeaf } from "src/utils/obsidianUtils";
export async function switchToExcalidraw(app: App) {
const leaves = app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW_LOADING);
const leaves: WorkspaceLeaf[] = [];
app.workspace.iterateAllLeaves((leaf) => {
if (leaf.view instanceof ExcalidrawLoading) {
leaves.push(leaf);
}
});
for (const leaf of leaves) {
await (leaf.view as ExcalidrawLoading)?.switchToExcalidraw();
}
@@ -26,7 +32,17 @@ export class ExcalidrawLoading extends FileView {
public async switchToExcalidraw() {
const prevLeaf = this.app.workspace.getLeaf();
await setExcalidrawView(this.leaf);
const state = this.leaf.view.getState();
// Force a fresh view instance: switching to the same type can be a no-op.
await this.leaf.setViewState({
type: "empty",
state: {},
});
await this.leaf.setViewState({
type: VIEW_TYPE_EXCALIDRAW,
state,
});
if (DEVICE.isDesktop) {
return;
}
@@ -45,11 +61,11 @@ export class ExcalidrawLoading extends FileView {
}
getViewType(): string {
return VIEW_TYPE_EXCALIDRAW_LOADING;
return VIEW_TYPE_EXCALIDRAW;
}
getDisplayText() {
return `Loading Excalidraw... ${this.file?.basename ?? ""}`;
return `${t("INITIALIZATION_MESSAGE")} ${this.file?.basename ?? ""}`;
}
private displayLoadingText() {
+1 -1
View File
@@ -2303,7 +2303,7 @@ export default class ExcalidrawView
private displayLoadingText() {
// Create a div element for displaying the text
const loadingTextEl = this.contentEl.createDiv({
text: `Loading Excalidraw... ${this.file?.basename ?? ""}`,
text: `${t("INITIALIZATION_MESSAGE")} ${this.file?.basename ?? ""}`,
});
// Apply styling to center the text