mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-12-03 06:43:35 +00:00
Compare commits
40
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
13e58fb005 | ||
|
|
c8daa43221 | ||
|
|
27b2dae94f | ||
|
|
8dda9317b5 | ||
|
|
1f181f3ce1 | ||
|
|
8ef705689d | ||
|
|
6552132e38 | ||
|
|
c72cd2d241 | ||
|
|
9d870489e2 | ||
|
|
0aab180dd7 | ||
|
|
3c308100cd | ||
|
|
b911272116 | ||
|
|
e0563598c4 | ||
|
|
847433b1fe | ||
|
|
1bfbf1f91c | ||
|
|
b47f90ad77 | ||
|
|
8719f585b6 | ||
|
|
0e23dd0d28 | ||
|
|
942a1540a0 | ||
|
|
6c0cfd48b0 | ||
|
|
44259770be | ||
|
|
0ec2db3c3c | ||
|
|
c6303edc7e | ||
|
|
1dcd7a3229 | ||
|
|
11fffb559f | ||
|
|
e56bc1d7f9 | ||
|
|
71c4257aed | ||
|
|
ddcdc03b1f | ||
|
|
51a770fd00 | ||
|
|
7e745599f3 | ||
|
|
3a953818b1 | ||
|
|
9c034b9f51 | ||
|
|
392088fed5 | ||
|
|
e97f123a83 | ||
|
|
a214941abc | ||
|
|
48f1fbaf2c | ||
|
|
55a2672ed7 | ||
|
|
b198020b2d | ||
|
|
d164be8ee5 | ||
|
|
6aa7d1f75c |
No files matched your search
@@ -97,6 +97,7 @@ Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particula
|
||||
## Mobile
|
||||
|
||||
- Don't assume desktop-only behavior unless `isDesktopOnly` is `true`.
|
||||
- Avoid using desktop only objects and functions such as Node Buffer, SharedArrayBuffer, etc. For the special case when this is required, make proper mobile safe guards.
|
||||
- Avoid large in-memory structures; be mindful of memory and storage constraints.
|
||||
|
||||
## Agent do/don't
|
||||
|
||||
@@ -1667,7 +1667,7 @@ export type ImageInfo = {
|
||||
isHyperLink?: boolean;
|
||||
hyperlink?: string;
|
||||
file?: string | TFile;
|
||||
hasSVGwithBitmap: boolean;
|
||||
hasSVGwithBitmap?: boolean;
|
||||
latex?: string;
|
||||
size?: Size;
|
||||
colorMap?: ColorMap;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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 |
@@ -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
@@ -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
@@ -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 |
@@ -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);
|
||||
|
||||
@@ -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
|
||||
}
|
||||
]
|
||||
@@ -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
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.25.1-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
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.25.0",
|
||||
"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",
|
||||
|
||||
Generated
+4
-4
@@ -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
@@ -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
@@ -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 = {
|
||||
|
||||
@@ -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' }));
|
||||
|
||||
@@ -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
|
||||
// });
|
||||
// }
|
||||
// };
|
||||
@@ -9,5 +9,5 @@ console.log("String copied to clipboard");
|
||||
|
||||
export const startupScript = () =>
|
||||
atob(
|
||||
"LyoKI2V4Y2x1ZGUKYGBganMqLwovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCB3aGVuIHRoZSB1c2VyIGNsb3NlcyBhbiBFeGNhbGlkcmF3IHZpZXcuCiAqICAgb25WaWV3VW5sb2FkSG9vazogKHZpZXc6IEV4Y2FsaWRyYXdWaWV3KSA9PiB2b2lkID0gbnVsbDsKICovCi8vZWEub25WaWV3VW5sb2FkSG9vayA9ICh2aWV3KSA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+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
@@ -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();
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -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?",
|
||||
@@ -1616,4 +1622,93 @@ Thank you & Enjoy!
|
||||
EXTRAS_GATEWAY_UPDATE_TITLE:
|
||||
"Excalidraw requires a new version of the Extras plugin",
|
||||
EXTRAS_GATEWAY_UPDATE_BTN: "Open Community Plugins",
|
||||
// PenSettingsModal.ts
|
||||
PEN_SETTINGS_TITLE: "Pen Settings",
|
||||
PEN_SETTINGS_HEADING: "Pen settings",
|
||||
PEN_SETTINGS_TYPE_NAME: "Pen type",
|
||||
PEN_SETTINGS_TYPE_DESC: "Select type of pen",
|
||||
PEN_SETTINGS_TYPE_DEFAULT: "Excalidraw Default",
|
||||
PEN_SETTINGS_TYPE_HIGHLIGHTER: "Highlighter",
|
||||
PEN_SETTINGS_TYPE_FINETIP: "Fine tip pen",
|
||||
PEN_SETTINGS_TYPE_FOUNTAIN: "Fountain pen",
|
||||
PEN_SETTINGS_TYPE_MARKER: "Marker with Outline",
|
||||
PEN_SETTINGS_TYPE_THICK_THIN: "Mindmap Thick-Thin",
|
||||
PEN_SETTINGS_TYPE_THIN_THICK_THIN: "Mindmap Thin-Thick-Thin",
|
||||
PEN_SETTINGS_APPLY: "Apply New Template",
|
||||
PEN_SETTINGS_SCOPE_FREEDRAW_ONLY:
|
||||
"Stroke & fill applies to: <b>Freedraw only</b>",
|
||||
PEN_SETTINGS_SCOPE_ALL_SHAPES: "Stroke & fill applies to: <b>All shapes</b>",
|
||||
PEN_SETTINGS_SCOPE_DESC: `<b>"All shapes"</b> means that if for example, you select a blue pen with dashed fill and then switch to a different tool (e.g. to a line, a circle, an arrow - i.e. not the freedraw tool), those will all have the same blue line and dashed fill.<br><b>"Only applies to the freedraw line"</b> means that if for example you are writing black text, and you select a custom pen (e.g. a yellow highlighter), then after using the highlighter you switch to another tool, the previous settings (e.g. black stroke color) will apply to the new shape.`,
|
||||
PEN_SETTINGS_STROKE_CURRENT: "Stroke color: <b>Current</b>",
|
||||
PEN_SETTINGS_STROKE_PRESET: "Stroke color: <b>Preset color</b>",
|
||||
PEN_SETTINGS_STROKE_DESC:
|
||||
"Use <b>current</b> stroke color of the canvas, or set a specific <b>preset color</b> for the pen",
|
||||
PEN_SETTINGS_STROKE_SELECT: "Select stroke color",
|
||||
PEN_SETTINGS_USE_CANVAS_CURRENT: "Use Canvas Current",
|
||||
PEN_SETTINGS_BG_CURRENT: "Background color: <b>Current</b>",
|
||||
PEN_SETTINGS_BG_PRESET: "Background color: <b>Preset color</b>",
|
||||
PEN_SETTINGS_BG_DESC:
|
||||
"Toggle to use the <b>current background color</b> of the canvas; or a <b>preset color</b>",
|
||||
PEN_SETTINGS_BG_TRANSPARENT: "Background: <b>Transparent</b>",
|
||||
PEN_SETTINGS_BG_COLOR_PRESET: "Color: <b>Preset color</b>",
|
||||
PEN_SETTINGS_BG_TRANSPARENT_DESC: "Background has color or is transparent",
|
||||
PEN_SETTINGS_BG_COLOR: "Background color",
|
||||
PEN_SETTINGS_FILL_STYLE: "Fill Style",
|
||||
PEN_SETTINGS_FILL_UNSET: "Unset",
|
||||
PEN_SETTINGS_FILL_DOTS: "Dots (⚠ VERY SLOW performance on large objects!)",
|
||||
PEN_SETTINGS_FILL_ZIGZAG: "Zigzag",
|
||||
PEN_SETTINGS_FILL_ZIGZAG_LINE: "Zigzag-line",
|
||||
PEN_SETTINGS_FILL_DASHED: "Dashed",
|
||||
PEN_SETTINGS_FILL_HACHURE: "Hachure",
|
||||
PEN_SETTINGS_FILL_CROSS_HATCH: "Cross-hatch",
|
||||
PEN_SETTINGS_FILL_SOLID: "Solid",
|
||||
PEN_SETTINGS_SLOPPINESS: "Sloppiness:",
|
||||
PEN_SETTINGS_NOT_SET: "Not Set",
|
||||
PEN_SETTINGS_SLOPPINESS_ARCHITECT: "Architect",
|
||||
PEN_SETTINGS_SLOPPINESS_ARTIST: "Artist",
|
||||
PEN_SETTINGS_SLOPPINESS_CARTOONIST: "Cartoonist",
|
||||
PEN_SETTINGS_SLOPPINESS_DESC: "Line sloppiness of the shape fill pattern",
|
||||
PEN_SETTINGS_STROKE_WIDTH: "Stroke Width",
|
||||
PEN_SETTINGS_STROKE_PRESET_UNSET: "---",
|
||||
PEN_SETTINGS_STROKE_PRESET_EXTRA_THIN: "Extra thin",
|
||||
PEN_SETTINGS_STROKE_PRESET_THIN: "Thin",
|
||||
PEN_SETTINGS_STROKE_PRESET_MEDIUM: "Medium",
|
||||
PEN_SETTINGS_STROKE_PRESET_BOLD: "Bold",
|
||||
PEN_SETTINGS_STROKE_PRESET_EXTRA_BOLD: "Extra bold",
|
||||
PEN_SETTINGS_HIGHLIGHTER: "Highlighter pen?",
|
||||
PEN_SETTINGS_PRESSURE: "Pressure sensitive pen?",
|
||||
PEN_SETTINGS_PRESSURE_DESC:
|
||||
"<b>toggle on</b>: pressure sensitive<br><b>toggle off</b>: constant pressure",
|
||||
PEN_SETTINGS_OUTLINE_NONE: "No outline",
|
||||
PEN_SETTINGS_OUTLINE_WIDTH: "Outline width",
|
||||
PEN_SETTINGS_OUTLINE_DESC:
|
||||
"If the stroke has an outline, this will mean the stroke color is the outline color, and the background color is the pen stroke's fill color. If the pen does not have an outline then the pen color is the stroke color. The Fill Style setting applies to the fill style of the enclosed shape, not of the line itself. The line can only have solid fill.",
|
||||
PEN_SETTINGS_PF_HEADING: "Perfect Freehand settings",
|
||||
PEN_SETTINGS_PF_DOCS: `Read the Perfect Freehand documentation following <a href="${URLs.GITHUB_COM_STEVERUIZOK_PERFECT_FREEHAND}" target="_blank">this link</a>.`,
|
||||
PEN_SETTINGS_PF_THINNING: "Thinning",
|
||||
PEN_SETTINGS_PF_THINNING_DESC: `The effect of pressure on the stroke's size.<br>To create a stroke with a steady line, set the thinning option to 0.<br>To create a stroke that gets thinner with pressure instead of thicker, use a negative number for the thinning option.`,
|
||||
PEN_SETTINGS_PF_SMOOTHING: "Smoothing",
|
||||
PEN_SETTINGS_PF_SMOOTHING_DESC: "How much to soften the stroke's edges.",
|
||||
PEN_SETTINGS_PF_STREAMLINE: "Streamline",
|
||||
PEN_SETTINGS_PF_STREAMLINE_DESC: "How much to streamline the stroke.",
|
||||
PEN_SETTINGS_EASING: "Easing function",
|
||||
PEN_SETTINGS_EASING_DESC: `An easing function for the tapering effect. For more info <a href="${URLs.EASINGS_NET}" target="_blank">click here</a>`,
|
||||
PEN_SETTINGS_SIMULATE_PRESSURE: "Simulate Pressure",
|
||||
PEN_SETTINGS_SIMULATE_PRESSURE_DESC:
|
||||
"Whether to simulate pressure based on velocity.",
|
||||
PEN_SETTINGS_SIMULATE_PRESSURE_ALWAYS: "Always",
|
||||
PEN_SETTINGS_SIMULATE_PRESSURE_NEVER: "Never",
|
||||
PEN_SETTINGS_SIMULATE_PRESSURE_MOUSE: "Yes for mouse, No for pen",
|
||||
PEN_SETTINGS_START_HEADING: "Start",
|
||||
PEN_SETTINGS_START_DESC: "Tapering options for the start of the line.",
|
||||
PEN_SETTINGS_CAP_START: "Cap Start",
|
||||
PEN_SETTINGS_CAP_DESC: "Whether to draw a cap",
|
||||
PEN_SETTINGS_TAPER: "Taper:",
|
||||
PEN_SETTINGS_TAPER_DESC:
|
||||
"The distance to taper. If set to true, the taper will be the total length of the stroke.",
|
||||
PEN_SETTINGS_END_HEADING: "End",
|
||||
PEN_SETTINGS_END_DESC: "Tapering options for the end of the line.",
|
||||
PEN_SETTINGS_CAP_END: "Cap End",
|
||||
PEN_SETTINGS_SAVE: "Save Changes",
|
||||
PEN_SETTINGS_CANCEL: "Cancel",
|
||||
};
|
||||
@@ -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;
|
||||
|
||||
@@ -17,9 +17,36 @@ 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.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
|
||||
- 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
|
||||
|
||||
## 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")}
|
||||
|
||||
@@ -1,23 +1,26 @@
|
||||
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import {
|
||||
ColorComponent,
|
||||
DropdownComponent,
|
||||
Modal,
|
||||
Setting,
|
||||
SliderComponent,
|
||||
TextComponent,
|
||||
ToggleComponent,
|
||||
} from "obsidian";
|
||||
import type { StrokeWidthKey } from "@zsviczian/excalidraw/types/common/src/constants";
|
||||
import { COLOR_NAMES } from "src/constants/constants";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { setPen } from "src/view/components/menu/ObsidianMenu";
|
||||
import { ExtendedFillStyle, PenType } from "src/types/penTypes";
|
||||
import { ExtendedFillStyle, PenType, PenStyle } from "src/types/penTypes";
|
||||
import { getExcalidrawViews } from "src/utils/obsidianUtils";
|
||||
import { PENS } from "src/utils/pens";
|
||||
import { fragWithHTML } from "src/utils/utils";
|
||||
import { setSanitizedHtml } from "src/utils/htmlUtils";
|
||||
import { showColorPicker } from "./ColorPicker";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { hideElement, showElement } from "src/utils/styleUtils";
|
||||
import { t } from "src/lang/helpers";
|
||||
|
||||
const EASINGFUNCTIONS: Record<string, string> = {
|
||||
linear: "linear",
|
||||
@@ -53,9 +56,28 @@ const EASINGFUNCTIONS: Record<string, string> = {
|
||||
easeInOutBounce: "easeInOutBounce",
|
||||
};
|
||||
|
||||
const FREEDRAW_STROKE_WIDTH_PRESETS: Readonly<Record<StrokeWidthKey, number>> =
|
||||
{
|
||||
extraThin: 0.25,
|
||||
thin: 0.5,
|
||||
medium: 1,
|
||||
bold: 2,
|
||||
extraBold: 4,
|
||||
};
|
||||
|
||||
const getStrokeWidthPresetKey = (strokeWidth: number): StrokeWidthKey | "" => {
|
||||
const normalizedStrokeWidth = Math.round(strokeWidth * 100) / 100;
|
||||
const matchedPreset = (
|
||||
Object.entries(FREEDRAW_STROKE_WIDTH_PRESETS) as [StrokeWidthKey, number][]
|
||||
).find(([, value]) => value === normalizedStrokeWidth);
|
||||
return matchedPreset?.[0] ?? "";
|
||||
};
|
||||
|
||||
export class PenSettingsModal extends Modal {
|
||||
private api: ExcalidrawImperativeAPI;
|
||||
private dirty: boolean = false;
|
||||
private shouldSave: boolean = false;
|
||||
private isDirty: boolean = false;
|
||||
private tempPenSettings: PenStyle;
|
||||
|
||||
constructor(
|
||||
private plugin: ExcalidrawPlugin,
|
||||
@@ -64,20 +86,28 @@ export class PenSettingsModal extends Modal {
|
||||
) {
|
||||
super(plugin.app);
|
||||
this.api = view.excalidrawAPI;
|
||||
// Clone the settings so changes aren't applied unless saved
|
||||
this.tempPenSettings = JSON.parse(
|
||||
JSON.stringify(this.plugin.settings.customPens[this.pen]),
|
||||
) as PenStyle;
|
||||
}
|
||||
|
||||
onOpen(): void {
|
||||
this.containerEl.classList.add("excalidraw-release");
|
||||
this.titleEl.setText(`Pen Settings`);
|
||||
this.titleEl.setText(t("PEN_SETTINGS_TITLE"));
|
||||
void this.createForm();
|
||||
}
|
||||
|
||||
onClose() {
|
||||
if (this.dirty) {
|
||||
if (this.shouldSave && this.isDirty) {
|
||||
// Overwrite actual settings with temp settings
|
||||
this.plugin.settings.customPens[this.pen] = this.tempPenSettings;
|
||||
void this.plugin.saveSettings();
|
||||
|
||||
getExcalidrawViews(this.app, true).forEach((excalidrawView) =>
|
||||
excalidrawView.updatePinnedCustomPens(),
|
||||
);
|
||||
|
||||
const pen = this.plugin.settings.customPens[this.pen];
|
||||
const api = this.view.excalidrawAPI;
|
||||
setPen(pen, api);
|
||||
@@ -85,6 +115,27 @@ export class PenSettingsModal extends Modal {
|
||||
}
|
||||
}
|
||||
|
||||
private addActionButtons(container: HTMLElement) {
|
||||
const actionContainer = container.createDiv(
|
||||
"excalidraw-pen-settings-floating-actions",
|
||||
);
|
||||
new Setting(actionContainer)
|
||||
.addButton((bt) =>
|
||||
bt
|
||||
.setButtonText(t("PEN_SETTINGS_SAVE"))
|
||||
.setCta()
|
||||
.onClick(() => {
|
||||
this.shouldSave = true;
|
||||
this.close();
|
||||
}),
|
||||
)
|
||||
.addButton((bt) =>
|
||||
bt.setButtonText(t("PEN_SETTINGS_CANCEL")).onClick(() => {
|
||||
this.close();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async createForm() {
|
||||
const hexColor = (color: string): [string, string] => {
|
||||
let opacity = "";
|
||||
@@ -119,39 +170,39 @@ export class PenSettingsModal extends Modal {
|
||||
return [null, opacity];
|
||||
};
|
||||
|
||||
const ps = this.plugin.settings.customPens[this.pen];
|
||||
const ps = this.tempPenSettings;
|
||||
const ce = this.contentEl;
|
||||
ce.empty();
|
||||
|
||||
ce.createEl("h1", { text: "Pen settings" });
|
||||
ce.createEl("h1", { text: t("PEN_SETTINGS_HEADING") });
|
||||
|
||||
new Setting(ce)
|
||||
.setName("Pen type")
|
||||
.setDesc("Select type of pen")
|
||||
.setName(t("PEN_SETTINGS_TYPE_NAME"))
|
||||
.setDesc(t("PEN_SETTINGS_TYPE_DESC"))
|
||||
.addDropdown((dropdown) => {
|
||||
dropdown
|
||||
.addOption("default", "Excalidraw Default")
|
||||
.addOption("highlighter", "Highlighter")
|
||||
.addOption("finetip", "Fine tip pen")
|
||||
.addOption("fountain", "Fountain pen")
|
||||
.addOption("marker", "Marker with Outline")
|
||||
.addOption("thick-thin", "Mindmap Thick-Thin")
|
||||
.addOption("thin-thick-thin", "Mindmap Thin-Thick-Thin")
|
||||
.addOption("default", t("PEN_SETTINGS_TYPE_DEFAULT"))
|
||||
.addOption("highlighter", t("PEN_SETTINGS_TYPE_HIGHLIGHTER"))
|
||||
.addOption("finetip", t("PEN_SETTINGS_TYPE_FINETIP"))
|
||||
.addOption("fountain", t("PEN_SETTINGS_TYPE_FOUNTAIN"))
|
||||
.addOption("marker", t("PEN_SETTINGS_TYPE_MARKER"))
|
||||
.addOption("thick-thin", t("PEN_SETTINGS_TYPE_THICK_THIN"))
|
||||
.addOption("thin-thick-thin", t("PEN_SETTINGS_TYPE_THIN_THICK_THIN"))
|
||||
.setValue(ps.type)
|
||||
.onChange((value: PenType) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.type = value;
|
||||
});
|
||||
})
|
||||
.addButton((button) =>
|
||||
button.setButtonText("Apply").onClick(() => {
|
||||
this.dirty = true;
|
||||
button.setButtonText(t("PEN_SETTINGS_APPLY")).onClick(() => {
|
||||
this.isDirty = true;
|
||||
ps.strokeColor = PENS[ps.type].strokeColor;
|
||||
ps.backgroundColor = PENS[ps.type].backgroundColor;
|
||||
ps.fillStyle = PENS[ps.type].fillStyle;
|
||||
ps.strokeWidth = PENS[ps.type].strokeWidth;
|
||||
ps.roughness = PENS[ps.type].roughness;
|
||||
ps.penOptions = { ...PENS[ps.type].penOptions };
|
||||
ce.empty();
|
||||
void this.createForm();
|
||||
}),
|
||||
);
|
||||
@@ -160,23 +211,19 @@ export class PenSettingsModal extends Modal {
|
||||
.setName(
|
||||
fragWithHTML(
|
||||
ps.freedrawOnly
|
||||
? "Stroke & fill applies to: <b>Freedraw only</b>"
|
||||
: "Stroke & fill applies to: <b>All shapes</b>",
|
||||
),
|
||||
)
|
||||
.setDesc(
|
||||
fragWithHTML(
|
||||
`<b>"All shapes"</b> means that if for example, you select a blue pen with dashed fill and then switch to a different tool (e.g. to a line, a circle, an arrow - i.e. not the freedraw tool), those will all have the same blue line and dashed fill.<br><b>"Only applies to the freedraw line"</b> means that if for example you are writing black text, and you select a custom pen (e.g. a yellow highlighter), then after using the highlighter you switch to another tool, the previous settings (e.g. black stroke color) will apply to the new shape.`,
|
||||
? t("PEN_SETTINGS_SCOPE_FREEDRAW_ONLY")
|
||||
: t("PEN_SETTINGS_SCOPE_ALL_SHAPES"),
|
||||
),
|
||||
)
|
||||
.setDesc(fragWithHTML(t("PEN_SETTINGS_SCOPE_DESC")))
|
||||
.addToggle((toggle) =>
|
||||
toggle.setValue(ps.freedrawOnly).onChange((value) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
scopeSetting.setName(
|
||||
fragWithHTML(
|
||||
value
|
||||
? "Stroke & fill applies to: <b>Freedraw only</b>"
|
||||
: "Stroke & fill applies to: <b>All shapes</b>",
|
||||
? t("PEN_SETTINGS_SCOPE_FREEDRAW_ONLY")
|
||||
: t("PEN_SETTINGS_SCOPE_ALL_SHAPES"),
|
||||
),
|
||||
);
|
||||
ps.freedrawOnly = value;
|
||||
@@ -193,19 +240,15 @@ export class PenSettingsModal extends Modal {
|
||||
.setName(
|
||||
fragWithHTML(
|
||||
!ps.strokeColor
|
||||
? "Stroke color: <b>Current</b>"
|
||||
: "Stroke color: <b>Preset color</b>",
|
||||
),
|
||||
)
|
||||
.setDesc(
|
||||
fragWithHTML(
|
||||
"Use <b>current</b> stroke color of the canvas, or set a specific <b>preset color</b> for the pen",
|
||||
? t("PEN_SETTINGS_STROKE_CURRENT")
|
||||
: t("PEN_SETTINGS_STROKE_PRESET"),
|
||||
),
|
||||
)
|
||||
.setDesc(fragWithHTML(t("PEN_SETTINGS_STROKE_DESC")))
|
||||
.addToggle((toggle) => {
|
||||
strokeUseCurrentToggle = toggle;
|
||||
toggle.setValue(!ps.strokeColor).onChange((value) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
if (value) {
|
||||
hideElement(scSetting.settingEl);
|
||||
} else {
|
||||
@@ -214,8 +257,8 @@ export class PenSettingsModal extends Modal {
|
||||
strokeSetting.setName(
|
||||
fragWithHTML(
|
||||
value
|
||||
? "Stroke color: <b>Current</b>"
|
||||
: "Stroke color: <b>Preset color</b>",
|
||||
? t("PEN_SETTINGS_STROKE_CURRENT")
|
||||
: t("PEN_SETTINGS_STROKE_PRESET"),
|
||||
),
|
||||
);
|
||||
if (value) {
|
||||
@@ -232,26 +275,28 @@ export class PenSettingsModal extends Modal {
|
||||
});
|
||||
|
||||
const scSetting = new Setting(ce)
|
||||
.setName("Select stroke color")
|
||||
.setName(t("PEN_SETTINGS_STROKE_SELECT"))
|
||||
.addButton((button) =>
|
||||
button.setButtonText("Use Canvas Current").onClick(() => {
|
||||
const st = this.api.getAppState();
|
||||
const color =
|
||||
st.resetCustomPen?.currentItemStrokeColor ??
|
||||
st.currentItemStrokeColor;
|
||||
[sHex, sOpacity] = hexColor(color);
|
||||
ps.strokeColor = color;
|
||||
this.dirty = true;
|
||||
sctComponent.setValue(color);
|
||||
sChangeBounce = true;
|
||||
sccpComponent.setValue(sHex);
|
||||
}),
|
||||
button
|
||||
.setButtonText(t("PEN_SETTINGS_USE_CANVAS_CURRENT"))
|
||||
.onClick(() => {
|
||||
const st = this.api.getAppState();
|
||||
const color =
|
||||
st.resetCustomPen?.currentItemStrokeColor ??
|
||||
st.currentItemStrokeColor;
|
||||
[sHex, sOpacity] = hexColor(color);
|
||||
ps.strokeColor = color;
|
||||
this.isDirty = true;
|
||||
sctComponent.setValue(color);
|
||||
sChangeBounce = true;
|
||||
sccpComponent.setValue(sHex);
|
||||
}),
|
||||
)
|
||||
.addText((text) => {
|
||||
sctComponent = text;
|
||||
text.setValue(ps.strokeColor).onChange((value) => {
|
||||
sChangeBounce = true;
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.strokeColor = value;
|
||||
[sHex, sOpacity] = hexColor(value);
|
||||
if (sHex) {
|
||||
@@ -266,7 +311,7 @@ export class PenSettingsModal extends Modal {
|
||||
sChangeBounce = false;
|
||||
return;
|
||||
}
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.strokeColor = value + sOpacity;
|
||||
sctComponent.setValue(value + sOpacity);
|
||||
});
|
||||
@@ -282,6 +327,7 @@ export class PenSettingsModal extends Modal {
|
||||
if (!selected) {
|
||||
return;
|
||||
}
|
||||
this.isDirty = true;
|
||||
strokeUseCurrentToggle?.setValue(false);
|
||||
sChangeBounce = true;
|
||||
[sHex, sOpacity] = hexColor(selected);
|
||||
@@ -309,24 +355,20 @@ export class PenSettingsModal extends Modal {
|
||||
.setName(
|
||||
fragWithHTML(
|
||||
!ps.backgroundColor
|
||||
? "Background color: <b>Current</b>"
|
||||
: "Background color: <b>Preset color</b>",
|
||||
),
|
||||
)
|
||||
.setDesc(
|
||||
fragWithHTML(
|
||||
"Toggle to use the <b>current background color</b> of the canvas; or a <b>preset color</b>",
|
||||
? t("PEN_SETTINGS_BG_CURRENT")
|
||||
: t("PEN_SETTINGS_BG_PRESET"),
|
||||
),
|
||||
)
|
||||
.setDesc(fragWithHTML(t("PEN_SETTINGS_BG_DESC")))
|
||||
.addToggle((toggle) => {
|
||||
bgUseCurrentToggle = toggle;
|
||||
toggle.setValue(!ps.backgroundColor).onChange((value) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
bgSetting.setName(
|
||||
fragWithHTML(
|
||||
value
|
||||
? "Background color: <b>Current</b>"
|
||||
: "Background color: <b>Preset color</b>",
|
||||
? t("PEN_SETTINGS_BG_CURRENT")
|
||||
: t("PEN_SETTINGS_BG_PRESET"),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -358,17 +400,17 @@ export class PenSettingsModal extends Modal {
|
||||
.setName(
|
||||
fragWithHTML(
|
||||
ps.backgroundColor === "transparent"
|
||||
? "Background: <b>Transparent</b>"
|
||||
: "Color: <b>Preset color</b>",
|
||||
? t("PEN_SETTINGS_BG_TRANSPARENT")
|
||||
: t("PEN_SETTINGS_BG_COLOR_PRESET"),
|
||||
),
|
||||
)
|
||||
.setDesc("Background has color or is transparent")
|
||||
.setDesc(t("PEN_SETTINGS_BG_TRANSPARENT_DESC"))
|
||||
.addToggle((toggle) => {
|
||||
bgtComponent = toggle;
|
||||
toggle
|
||||
.setValue(ps.backgroundColor === "transparent")
|
||||
.onChange((value) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
if (value) {
|
||||
hideElement(bgcSetting.settingEl);
|
||||
hideElement(fsSetting.settingEl);
|
||||
@@ -379,8 +421,8 @@ export class PenSettingsModal extends Modal {
|
||||
bgctSetting.setName(
|
||||
fragWithHTML(
|
||||
value
|
||||
? "Background: <b>Transparent</b>"
|
||||
: "Color: <b>Preset color</b>",
|
||||
? t("PEN_SETTINGS_BG_TRANSPARENT")
|
||||
: t("PEN_SETTINGS_BG_COLOR_PRESET"),
|
||||
),
|
||||
);
|
||||
ps.backgroundColor = value
|
||||
@@ -396,26 +438,28 @@ export class PenSettingsModal extends Modal {
|
||||
}
|
||||
let bgChangeBounce: boolean = false;
|
||||
const bgcSetting = new Setting(ce)
|
||||
.setName("Background color")
|
||||
.setName(t("PEN_SETTINGS_BG_COLOR"))
|
||||
.addButton((button) =>
|
||||
button.setButtonText("Use Canvas Current").onClick(() => {
|
||||
const st = this.api.getAppState();
|
||||
const color =
|
||||
st.resetCustomPen?.currentItemBackgroundColor ??
|
||||
st.currentItemBackgroundColor;
|
||||
[bgHex, bgOpacity] = hexColor(color);
|
||||
ps.backgroundColor = color;
|
||||
this.dirty = true;
|
||||
bgctComponent.setValue(color);
|
||||
bgChangeBounce = true;
|
||||
bgcpComponent.setValue(bgHex);
|
||||
}),
|
||||
button
|
||||
.setButtonText(t("PEN_SETTINGS_USE_CANVAS_CURRENT"))
|
||||
.onClick(() => {
|
||||
const st = this.api.getAppState();
|
||||
const color =
|
||||
st.resetCustomPen?.currentItemBackgroundColor ??
|
||||
st.currentItemBackgroundColor;
|
||||
[bgHex, bgOpacity] = hexColor(color);
|
||||
ps.backgroundColor = color;
|
||||
this.isDirty = true;
|
||||
bgctComponent.setValue(color);
|
||||
bgChangeBounce = true;
|
||||
bgcpComponent.setValue(bgHex);
|
||||
}),
|
||||
)
|
||||
.addText((text) => {
|
||||
bgctComponent = text;
|
||||
text.setValue(ps.backgroundColor).onChange((value) => {
|
||||
bgChangeBounce = true;
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.backgroundColor = value;
|
||||
[bgHex, bgOpacity] = hexColor(value);
|
||||
if (bgHex) {
|
||||
@@ -430,7 +474,7 @@ export class PenSettingsModal extends Modal {
|
||||
bgChangeBounce = false;
|
||||
return;
|
||||
}
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.backgroundColor = value + bgOpacity;
|
||||
bgctComponent.setValue(value + bgOpacity);
|
||||
});
|
||||
@@ -446,6 +490,7 @@ export class PenSettingsModal extends Modal {
|
||||
if (!selected) {
|
||||
return;
|
||||
}
|
||||
this.isDirty = true;
|
||||
bgUseCurrentToggle?.setValue(false);
|
||||
bgtComponent?.setValue(false);
|
||||
bgChangeBounce = true;
|
||||
@@ -465,20 +510,20 @@ export class PenSettingsModal extends Modal {
|
||||
}
|
||||
|
||||
const fsSetting = new Setting(ce)
|
||||
.setName("Fill Style")
|
||||
.setName(t("PEN_SETTINGS_FILL_STYLE"))
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOption("", "Unset")
|
||||
.addOption("dots", "Dots (⚠ VERY SLOW performance on large objects!)")
|
||||
.addOption("zigzag", "Zigzag")
|
||||
.addOption("zigzag-line", "Zigzag-line")
|
||||
.addOption("dashed", "Dashed")
|
||||
.addOption("hachure", "Hachure")
|
||||
.addOption("cross-hatch", "Cross-hatch")
|
||||
.addOption("solid", "Solid")
|
||||
.addOption("", t("PEN_SETTINGS_FILL_UNSET"))
|
||||
.addOption("dots", t("PEN_SETTINGS_FILL_DOTS"))
|
||||
.addOption("zigzag", t("PEN_SETTINGS_FILL_ZIGZAG"))
|
||||
.addOption("zigzag-line", t("PEN_SETTINGS_FILL_ZIGZAG_LINE"))
|
||||
.addOption("dashed", t("PEN_SETTINGS_FILL_DASHED"))
|
||||
.addOption("hachure", t("PEN_SETTINGS_FILL_HACHURE"))
|
||||
.addOption("cross-hatch", t("PEN_SETTINGS_FILL_CROSS_HATCH"))
|
||||
.addOption("solid", t("PEN_SETTINGS_FILL_SOLID"))
|
||||
.setValue(ps.fillStyle)
|
||||
.onChange((value: ExtendedFillStyle) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.fillStyle = value;
|
||||
}),
|
||||
);
|
||||
@@ -488,66 +533,111 @@ export class PenSettingsModal extends Modal {
|
||||
showElement(fsSetting.settingEl);
|
||||
}
|
||||
|
||||
const getSloppinessName = (roughness: number | null) => {
|
||||
if (roughness === null) return t("PEN_SETTINGS_NOT_SET");
|
||||
if (roughness <= 0.5)
|
||||
return `${t("PEN_SETTINGS_SLOPPINESS_ARCHITECT")} (${roughness})`;
|
||||
if (roughness <= 1.5)
|
||||
return `${t("PEN_SETTINGS_SLOPPINESS_ARTIST")} (${roughness})`;
|
||||
return `${t("PEN_SETTINGS_SLOPPINESS_CARTOONIST")} (${roughness})`;
|
||||
};
|
||||
|
||||
const rSetting = new Setting(ce)
|
||||
.setName(
|
||||
fragWithHTML(
|
||||
`Sloppiness: <b>${ps.roughness === null ? "Not Set" : ps.roughness <= 0.5 ? "Architect (" : ps.roughness <= 1.5 ? "Artist (" : "Cartoonist ("}${ps.roughness === null ? "" : `${ps.roughness})`}</b>`,
|
||||
`${t("PEN_SETTINGS_SLOPPINESS")} <b>${getSloppinessName(ps.roughness)}</b>`,
|
||||
),
|
||||
)
|
||||
.setDesc("Line sloppiness of the shape fill pattern")
|
||||
.setDesc(t("PEN_SETTINGS_SLOPPINESS_DESC"))
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(-0.5, 3, 0.5)
|
||||
.setValue(ps.roughness === null ? -0.5 : ps.roughness)
|
||||
.onChange((value) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.roughness = value === -0.5 ? null : value;
|
||||
rSetting.setName(
|
||||
fragWithHTML(
|
||||
`Sloppiness: <b>${ps.roughness === null ? "Not Set" : ps.roughness <= 0.5 ? "Architect (" : ps.roughness <= 1.5 ? "Artist (" : "Cartoonist ("}${ps.roughness === null ? "" : `${ps.roughness})`}</b>`,
|
||||
`${t("PEN_SETTINGS_SLOPPINESS")} <b>${getSloppinessName(ps.roughness)}</b>`,
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
let strokeWidthSlider: SliderComponent;
|
||||
let strokeWidthPresetDropdown: DropdownComponent;
|
||||
let strokeWidthPresetUpdateInProgress = false;
|
||||
|
||||
const swSetting = new Setting(ce)
|
||||
.setName(
|
||||
fragWithHTML(
|
||||
`Stroke Width <b>${ps.strokeWidth === 0 ? "Not Set" : ps.strokeWidth}</b>`,
|
||||
`${t("PEN_SETTINGS_STROKE_WIDTH")} <b>${ps.strokeWidth === 0 ? t("PEN_SETTINGS_NOT_SET") : ps.strokeWidth}</b>`,
|
||||
),
|
||||
)
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(0.1, 8, 0.1)
|
||||
.setValue(ps.strokeWidth)
|
||||
.onChange((value) => {
|
||||
this.dirty = true;
|
||||
ps.strokeWidth = value;
|
||||
.addDropdown((dropdown) => {
|
||||
strokeWidthPresetDropdown = dropdown;
|
||||
dropdown
|
||||
.addOption("", t("PEN_SETTINGS_STROKE_PRESET_UNSET"))
|
||||
.addOption("extraThin", t("PEN_SETTINGS_STROKE_PRESET_EXTRA_THIN"))
|
||||
.addOption("thin", t("PEN_SETTINGS_STROKE_PRESET_THIN"))
|
||||
.addOption("medium", t("PEN_SETTINGS_STROKE_PRESET_MEDIUM"))
|
||||
.addOption("bold", t("PEN_SETTINGS_STROKE_PRESET_BOLD"))
|
||||
.addOption("extraBold", t("PEN_SETTINGS_STROKE_PRESET_EXTRA_BOLD"))
|
||||
.setValue(getStrokeWidthPresetKey(ps.strokeWidth))
|
||||
.onChange((value: StrokeWidthKey | "") => {
|
||||
this.isDirty = true;
|
||||
if (!value) {
|
||||
return;
|
||||
}
|
||||
const presetStrokeWidth = FREEDRAW_STROKE_WIDTH_PRESETS[value];
|
||||
ps.strokeWidth = presetStrokeWidth;
|
||||
strokeWidthPresetUpdateInProgress = true;
|
||||
strokeWidthSlider?.setValue(presetStrokeWidth);
|
||||
swSetting.setName(
|
||||
fragWithHTML(
|
||||
`Stroke Width <b>${ps.strokeWidth === 0 ? "Not Set" : ps.strokeWidth}</b>`,
|
||||
`${t("PEN_SETTINGS_STROKE_WIDTH")} <b>${ps.strokeWidth === 0 ? t("PEN_SETTINGS_NOT_SET") : ps.strokeWidth}</b>`,
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
})
|
||||
.addSlider((slider) => {
|
||||
strokeWidthSlider = slider;
|
||||
slider
|
||||
.setLimits(0.05, 8, 0.05)
|
||||
.setValue(ps.strokeWidth)
|
||||
.onChange((value) => {
|
||||
this.isDirty = true;
|
||||
ps.strokeWidth = value;
|
||||
|
||||
new Setting(ce).setName("Highlighter pen?").addToggle((toggle) =>
|
||||
if (strokeWidthPresetUpdateInProgress) {
|
||||
strokeWidthPresetUpdateInProgress = false;
|
||||
} else {
|
||||
strokeWidthPresetDropdown.setValue(
|
||||
getStrokeWidthPresetKey(value),
|
||||
);
|
||||
}
|
||||
|
||||
swSetting.setName(
|
||||
fragWithHTML(
|
||||
`${t("PEN_SETTINGS_STROKE_WIDTH")} <b>${ps.strokeWidth === 0 ? t("PEN_SETTINGS_NOT_SET") : ps.strokeWidth}</b>`,
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
new Setting(ce).setName(t("PEN_SETTINGS_HIGHLIGHTER")).addToggle((toggle) =>
|
||||
toggle.setValue(ps.penOptions.highlighter).onChange((value) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.penOptions.highlighter = value;
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(ce)
|
||||
.setName("Pressure sensitive pen?")
|
||||
.setDesc(
|
||||
fragWithHTML(
|
||||
`<b>toggle on</b>: pressure sensitive<br><b>toggle off</b>: constant pressure`,
|
||||
),
|
||||
)
|
||||
.setName(t("PEN_SETTINGS_PRESSURE"))
|
||||
.setDesc(fragWithHTML(t("PEN_SETTINGS_PRESSURE_DESC")))
|
||||
.addToggle((toggle) =>
|
||||
toggle.setValue(!ps.penOptions.constantPressure).onChange((value) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.penOptions.constantPressure = !value;
|
||||
if (ps.penOptions.constantPressure) {
|
||||
hideElement(spSetting.settingEl);
|
||||
@@ -559,127 +649,128 @@ export class PenSettingsModal extends Modal {
|
||||
|
||||
if (ps.penOptions.hasOutline && ps.penOptions.outlineWidth === 0) {
|
||||
ps.penOptions.outlineWidth = 0.5;
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
}
|
||||
|
||||
if (!ps.penOptions.hasOutline && ps.penOptions.outlineWidth > 0) {
|
||||
ps.penOptions.outlineWidth = 0;
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
}
|
||||
|
||||
const owSetting = new Setting(ce)
|
||||
.setName(
|
||||
fragWithHTML(
|
||||
ps.penOptions.outlineWidth === 0
|
||||
? `No outline`
|
||||
: `Outline width <b>${ps.penOptions.outlineWidth}</b>`,
|
||||
? t("PEN_SETTINGS_OUTLINE_NONE")
|
||||
: `${t("PEN_SETTINGS_OUTLINE_WIDTH")} <b>${ps.penOptions.outlineWidth}</b>`,
|
||||
),
|
||||
)
|
||||
.setDesc(
|
||||
"If the stroke has an outline, this will mean the stroke color is the outline color, and the background color is the pen stroke's fill color. If the pen does not have an outline then the pen color is the stroke color. The Fill Style setting applies to the fill style of the enclosed shape, not of the line itself. The line can only have solid fill.",
|
||||
)
|
||||
.setDesc(t("PEN_SETTINGS_OUTLINE_DESC"))
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(0, 8, 0.1)
|
||||
.setValue(ps.penOptions.outlineWidth)
|
||||
.onChange((value) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.penOptions.outlineWidth = value;
|
||||
ps.penOptions.hasOutline = value > 0;
|
||||
owSetting.setName(
|
||||
fragWithHTML(
|
||||
ps.penOptions.outlineWidth === 0
|
||||
? `No outline`
|
||||
: `Outline width <b>${ps.penOptions.outlineWidth}</b>`,
|
||||
? t("PEN_SETTINGS_OUTLINE_NONE")
|
||||
: `${t("PEN_SETTINGS_OUTLINE_WIDTH")} <b>${ps.penOptions.outlineWidth}</b>`,
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
ce.createEl("h2", { text: "Perfect Freehand settings" });
|
||||
ce.createEl("h2", { text: t("PEN_SETTINGS_PF_HEADING") });
|
||||
const p = ce.createEl("p");
|
||||
setSanitizedHtml(
|
||||
p,
|
||||
`Read the Perfect Freehand documentation following <a href="${URLs.GITHUB_COM_STEVERUIZOK_PERFECT_FREEHAND}" target="_blank">this link</a>.`,
|
||||
);
|
||||
setSanitizedHtml(p, t("PEN_SETTINGS_PF_DOCS"));
|
||||
|
||||
const tSetting = new Setting(ce)
|
||||
.setName(
|
||||
fragWithHTML(`Thinnning <b>${ps.penOptions.options.thinning}</b>`),
|
||||
)
|
||||
.setDesc(
|
||||
fragWithHTML(
|
||||
`The effect of pressure on the stroke's size.<br>To create a stroke with a steady line, set the thinning option to 0.<br>To create a stroke that gets thinner with pressure instead of thicker, use a negative number for the thinning option.`,
|
||||
`${t("PEN_SETTINGS_PF_THINNING")} <b>${ps.penOptions.options.thinning}</b>`,
|
||||
),
|
||||
)
|
||||
.setDesc(fragWithHTML(t("PEN_SETTINGS_PF_THINNING_DESC")))
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(-1, 1, 0.05)
|
||||
.setValue(ps.penOptions.options.thinning)
|
||||
.onChange((value) => {
|
||||
this.dirty = true;
|
||||
tSetting.setName(fragWithHTML(`Thinnning <b>${value}</b>`));
|
||||
this.isDirty = true;
|
||||
tSetting.setName(
|
||||
fragWithHTML(`${t("PEN_SETTINGS_PF_THINNING")} <b>${value}</b>`),
|
||||
);
|
||||
ps.penOptions.options.thinning = value;
|
||||
}),
|
||||
);
|
||||
|
||||
const sSetting = new Setting(ce)
|
||||
.setName(
|
||||
fragWithHTML(`Smoothing <b>${ps.penOptions.options.smoothing}</b>`),
|
||||
fragWithHTML(
|
||||
`${t("PEN_SETTINGS_PF_SMOOTHING")} <b>${ps.penOptions.options.smoothing}</b>`,
|
||||
),
|
||||
)
|
||||
.setDesc(fragWithHTML(`How much to soften the stroke's edges.`))
|
||||
.setDesc(fragWithHTML(t("PEN_SETTINGS_PF_SMOOTHING_DESC")))
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(0, 1, 0.05)
|
||||
.setValue(ps.penOptions.options.smoothing)
|
||||
.onChange((value) => {
|
||||
this.dirty = true;
|
||||
sSetting.setName(fragWithHTML(`Smoothing <b>${value}</b>`));
|
||||
this.isDirty = true;
|
||||
sSetting.setName(
|
||||
fragWithHTML(`${t("PEN_SETTINGS_PF_SMOOTHING")} <b>${value}</b>`),
|
||||
);
|
||||
ps.penOptions.options.smoothing = value;
|
||||
}),
|
||||
);
|
||||
|
||||
const slSetting = new Setting(ce)
|
||||
.setName(
|
||||
fragWithHTML(`Streamline <b>${ps.penOptions.options.streamline}</b>`),
|
||||
fragWithHTML(
|
||||
`${t("PEN_SETTINGS_PF_STREAMLINE")} <b>${ps.penOptions.options.streamline}</b>`,
|
||||
),
|
||||
)
|
||||
.setDesc(fragWithHTML(` How much to streamline the stroke.`))
|
||||
.setDesc(fragWithHTML(t("PEN_SETTINGS_PF_STREAMLINE_DESC")))
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(0, 1, 0.05)
|
||||
.setValue(ps.penOptions.options.streamline)
|
||||
.onChange((value) => {
|
||||
this.dirty = true;
|
||||
slSetting.setName(fragWithHTML(`Streamline <b>${value}</b>`));
|
||||
this.isDirty = true;
|
||||
slSetting.setName(
|
||||
fragWithHTML(
|
||||
`${t("PEN_SETTINGS_PF_STREAMLINE")} <b>${value}</b>`,
|
||||
),
|
||||
);
|
||||
ps.penOptions.options.streamline = value;
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(ce)
|
||||
.setName("Easing function")
|
||||
.setDesc(
|
||||
fragWithHTML(
|
||||
`An easing function for the tapering effect. For more info <a href="${URLs.EASINGS_NET}" target="_blank">click here</a>`,
|
||||
),
|
||||
)
|
||||
.setName(t("PEN_SETTINGS_EASING"))
|
||||
.setDesc(fragWithHTML(t("PEN_SETTINGS_EASING_DESC")))
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOptions(EASINGFUNCTIONS)
|
||||
.setValue(ps.penOptions.options.easing)
|
||||
.onChange((value) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.penOptions.options.easing = value;
|
||||
}),
|
||||
);
|
||||
|
||||
const spSetting = new Setting(ce)
|
||||
.setName("Simulate Pressure")
|
||||
.setDesc("Whether to simulate pressure based on velocity.")
|
||||
.setName(t("PEN_SETTINGS_SIMULATE_PRESSURE"))
|
||||
.setDesc(t("PEN_SETTINGS_SIMULATE_PRESSURE_DESC"))
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOption("true", "Always")
|
||||
.addOption("false", "Never")
|
||||
.addOption("", "Yes for mouse, No for pen")
|
||||
.addOption("true", t("PEN_SETTINGS_SIMULATE_PRESSURE_ALWAYS"))
|
||||
.addOption("false", t("PEN_SETTINGS_SIMULATE_PRESSURE_NEVER"))
|
||||
.addOption("", t("PEN_SETTINGS_SIMULATE_PRESSURE_MOUSE"))
|
||||
.setValue(
|
||||
ps.penOptions.options.simulatePressure === true
|
||||
? "true"
|
||||
@@ -688,7 +779,7 @@ export class PenSettingsModal extends Modal {
|
||||
: "",
|
||||
)
|
||||
.onChange((value) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
switch (value) {
|
||||
case "true":
|
||||
ps.penOptions.options.simulatePressure = true;
|
||||
@@ -708,15 +799,15 @@ export class PenSettingsModal extends Modal {
|
||||
showElement(spSetting.settingEl);
|
||||
}
|
||||
|
||||
ce.createEl("h3", { text: "Start" });
|
||||
ce.createEl("p", { text: "Tapering options for the start of the line." });
|
||||
ce.createEl("h3", { text: t("PEN_SETTINGS_START_HEADING") });
|
||||
ce.createEl("p", { text: t("PEN_SETTINGS_START_DESC") });
|
||||
|
||||
new Setting(ce)
|
||||
.setName("Cap Start")
|
||||
.setDesc("Whether to draw a cap")
|
||||
.setName(t("PEN_SETTINGS_CAP_START"))
|
||||
.setDesc(t("PEN_SETTINGS_CAP_DESC"))
|
||||
.addToggle((toggle) =>
|
||||
toggle.setValue(ps.penOptions.options.start.cap).onChange((value) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.penOptions.options.start.cap = value;
|
||||
}),
|
||||
);
|
||||
@@ -724,12 +815,10 @@ export class PenSettingsModal extends Modal {
|
||||
const stSetting = new Setting(ce)
|
||||
.setName(
|
||||
fragWithHTML(
|
||||
`Taper: <b>${ps.penOptions.options.start.taper === true ? "true" : ps.penOptions.options.start.taper}</b>`,
|
||||
`${t("PEN_SETTINGS_TAPER")} <b>${ps.penOptions.options.start.taper === true ? "true" : ps.penOptions.options.start.taper}</b>`,
|
||||
),
|
||||
)
|
||||
.setDesc(
|
||||
"The distance to taper. If set to true, the taper will be the total length of the stroke.",
|
||||
)
|
||||
.setDesc(t("PEN_SETTINGS_TAPER_DESC"))
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(0, 151, 1)
|
||||
@@ -739,42 +828,38 @@ export class PenSettingsModal extends Modal {
|
||||
: ps.penOptions.options.start.taper,
|
||||
)
|
||||
.onChange((value) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.penOptions.options.start.taper = value === 151 ? true : value;
|
||||
stSetting.setName(
|
||||
fragWithHTML(
|
||||
`Taper: <b>${ps.penOptions.options.start.taper === true ? "true" : ps.penOptions.options.start.taper}</b>`,
|
||||
`${t("PEN_SETTINGS_TAPER")} <b>${ps.penOptions.options.start.taper === true ? "true" : ps.penOptions.options.start.taper}</b>`,
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(ce)
|
||||
.setName("Easing function")
|
||||
.setDesc(
|
||||
fragWithHTML(
|
||||
`An easing function for the tapering effect. For more info <a href="${URLs.EASINGS_NET}" target="_blank">click here</a>`,
|
||||
),
|
||||
)
|
||||
.setName(t("PEN_SETTINGS_EASING"))
|
||||
.setDesc(fragWithHTML(t("PEN_SETTINGS_EASING_DESC")))
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOptions(EASINGFUNCTIONS)
|
||||
.setValue(ps.penOptions.options.start.easing)
|
||||
.onChange((value) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.penOptions.options.start.easing = value;
|
||||
}),
|
||||
);
|
||||
|
||||
ce.createEl("h3", { text: "End" });
|
||||
ce.createEl("p", { text: "Tapering options for the end of the line." });
|
||||
ce.createEl("h3", { text: t("PEN_SETTINGS_END_HEADING") });
|
||||
ce.createEl("p", { text: t("PEN_SETTINGS_END_DESC") });
|
||||
|
||||
new Setting(ce)
|
||||
.setName("Cap End")
|
||||
.setDesc("Whether to draw a cap")
|
||||
.setName(t("PEN_SETTINGS_CAP_END"))
|
||||
.setDesc(t("PEN_SETTINGS_CAP_DESC"))
|
||||
.addToggle((toggle) =>
|
||||
toggle.setValue(ps.penOptions.options.end.cap).onChange((value) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.penOptions.options.end.cap = value;
|
||||
}),
|
||||
);
|
||||
@@ -782,12 +867,10 @@ export class PenSettingsModal extends Modal {
|
||||
const etSetting = new Setting(ce)
|
||||
.setName(
|
||||
fragWithHTML(
|
||||
`Taper: <b>${ps.penOptions.options.end.taper === true ? "true" : ps.penOptions.options.end.taper}</b>`,
|
||||
`${t("PEN_SETTINGS_TAPER")} <b>${ps.penOptions.options.end.taper === true ? "true" : ps.penOptions.options.end.taper}</b>`,
|
||||
),
|
||||
)
|
||||
.setDesc(
|
||||
"The distance to taper. If set to true, the taper will be the total length of the stroke.",
|
||||
)
|
||||
.setDesc(t("PEN_SETTINGS_TAPER_DESC"))
|
||||
.addSlider((slider) =>
|
||||
slider
|
||||
.setLimits(0, 151, 1)
|
||||
@@ -797,31 +880,30 @@ export class PenSettingsModal extends Modal {
|
||||
: ps.penOptions.options.end.taper,
|
||||
)
|
||||
.onChange((value) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.penOptions.options.end.taper = value === 151 ? true : value;
|
||||
etSetting.setName(
|
||||
fragWithHTML(
|
||||
`Taper: <b>${ps.penOptions.options.end.taper === true ? "true" : ps.penOptions.options.end.taper}</b>`,
|
||||
`${t("PEN_SETTINGS_TAPER")} <b>${ps.penOptions.options.end.taper === true ? "true" : ps.penOptions.options.end.taper}</b>`,
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(ce)
|
||||
.setName("Easing function")
|
||||
.setDesc(
|
||||
fragWithHTML(
|
||||
`An easing function for the tapering effect. For more info <a href="${URLs.EASINGS_NET}" target="_blank">click here</a>`,
|
||||
),
|
||||
)
|
||||
.setName(t("PEN_SETTINGS_EASING"))
|
||||
.setDesc(fragWithHTML(t("PEN_SETTINGS_EASING_DESC")))
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOptions(EASINGFUNCTIONS)
|
||||
.setValue(ps.penOptions.options.end.easing)
|
||||
.onChange((value) => {
|
||||
this.dirty = true;
|
||||
this.isDirty = true;
|
||||
ps.penOptions.options.end.easing = value;
|
||||
}),
|
||||
);
|
||||
|
||||
// Bottom buttons
|
||||
this.addActionButtons(ce);
|
||||
}
|
||||
}
|
||||
@@ -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[];
|
||||
}
|
||||
|
||||
|
||||
@@ -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[] = [
|
||||
|
||||
@@ -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}`;
|
||||
|
||||
@@ -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
@@ -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();
|
||||
|
||||
@@ -1129,6 +1129,25 @@ export const getStrokeKeyFormLegacyWidth = (
|
||||
}
|
||||
};
|
||||
|
||||
export const getStrokeWidthKeyByWidth = (
|
||||
strokeWidth: number,
|
||||
): StrokeWidthKey | "extraBold" | undefined => {
|
||||
switch (strokeWidth) {
|
||||
case 0.25:
|
||||
return "extraThin";
|
||||
case 0.5:
|
||||
return "thin";
|
||||
case 1:
|
||||
return "medium";
|
||||
case 2:
|
||||
return "bold";
|
||||
case 4:
|
||||
return "extraBold";
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
// Returns an appState key for the stroke width
|
||||
// excalidraw.com deprected and removed currentItemStrokeWidth from appState
|
||||
// but the plugin still supports it to allow custom line width settings for scripts and custom pens
|
||||
@@ -1140,7 +1159,8 @@ export const getAppStateStrokeWidthEntry = (
|
||||
legacyStrokeWidth: number,
|
||||
) => {
|
||||
if (legacyStrokeWidth !== undefined) {
|
||||
strokeWidthKey = getStrokeKeyFormLegacyWidth(legacyStrokeWidth);
|
||||
// Reusing the combined function here
|
||||
strokeWidthKey = getStrokeWidthKeyByWidth(legacyStrokeWidth);
|
||||
}
|
||||
if (!!legacyStrokeWidth && !strokeWidthKey) {
|
||||
return { currentItemStrokeWidth: legacyStrokeWidth };
|
||||
|
||||
+15
-5
@@ -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,
|
||||
|
||||
@@ -660,12 +660,16 @@ export function stripYamlFrontmatter(text: string): string {
|
||||
export function strictArrayBuffer(
|
||||
buffer: ArrayBuffer | SharedArrayBuffer,
|
||||
): ArrayBuffer {
|
||||
if (buffer instanceof SharedArrayBuffer) {
|
||||
// Check if SharedArrayBuffer is defined in the current environment
|
||||
if (
|
||||
typeof SharedArrayBuffer !== "undefined" &&
|
||||
buffer instanceof SharedArrayBuffer
|
||||
) {
|
||||
const strictBuffer = new ArrayBuffer(buffer.byteLength);
|
||||
new Uint8Array(strictBuffer).set(new Uint8Array(buffer));
|
||||
return strictBuffer;
|
||||
}
|
||||
return buffer;
|
||||
return buffer as ArrayBuffer;
|
||||
}
|
||||
|
||||
// 1. Map your custom 'type' strings to actual TypeScript types
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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
|
||||
@@ -8140,6 +8140,7 @@ export default class ExcalidrawView
|
||||
if (!api) {
|
||||
return false;
|
||||
}
|
||||
this.obsidianMenu?.invalidateCustomPenCache();
|
||||
api.updateScene({
|
||||
appState: {
|
||||
customPens: this.plugin.settings.customPens.slice(
|
||||
|
||||
@@ -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(
|
||||
@@ -151,6 +153,27 @@ export class ObsidianMenu {
|
||||
);
|
||||
}
|
||||
|
||||
public invalidateCustomPenCache() {
|
||||
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;
|
||||
@@ -167,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" });
|
||||
}
|
||||
@@ -264,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,
|
||||
@@ -294,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 (
|
||||
@@ -305,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"
|
||||
@@ -315,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 (
|
||||
@@ -434,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;
|
||||
|
||||
+16
@@ -1077,4 +1077,20 @@ End Obsidian Sheets Plus support
|
||||
|
||||
.excalidraw .App-tray-menu {
|
||||
min-width: calc(6 * var(--default-button-size));
|
||||
}
|
||||
|
||||
.excalidraw-pen-settings-floating-actions {
|
||||
position: sticky;
|
||||
bottom: -20px;
|
||||
margin-bottom: -20px;
|
||||
padding-bottom: 20px;
|
||||
padding-top: 15px;
|
||||
background-color: var(--background-primary);
|
||||
border-top: 1px solid var(--background-modifier-border);
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.excalidraw-pen-settings-floating-actions .setting-item {
|
||||
border-top: none;
|
||||
padding: 0;
|
||||
}
|
||||
Reference in new issue
Block a user