Compare commits

...
21 changed files with 1160 additions and 503 deletions

No files matched your search

+1 -11
View File
@@ -10,11 +10,6 @@ type DataURL = string & { _brand: "DataURL" };
type FileId = string & { _brand: "FileId" };
const fileid = customAlphabet("1234567890abcdef", 40);
type Tex2DataURLOptions = {
applyThemeFilter?: boolean;
themeFilter?: string;
};
let adaptor: LiteAdaptor;
let html: any;
let preamble: string;
@@ -43,8 +38,7 @@ async function getImageSize(src: string): Promise<{ height: number; width: numbe
export async function tex2dataURL(
tex: string,
scale: number = 4,
plugin?: any,
options?: Tex2DataURLOptions
plugin?: any
): Promise<{
mimeType: string;
fileId: FileId;
@@ -87,10 +81,6 @@ export async function tex2dataURL(
styleNode.appendChild(document.createTextNode(".mjx-solid { stroke-width: 80px; }"));
svg.appendChild(styleNode);
if (options?.applyThemeFilter && options.themeFilter) {
svg.setAttribute("filter", options.themeFilter);
}
if (svg) {
if(svg.width.baseVal.valueInSpecifiedUnits < 2) {
svg.width.baseVal.valueAsString = `${(svg.width.baseVal.valueInSpecifiedUnits+1).toFixed(3)}ex`;
+766
View File
@@ -0,0 +1,766 @@
/*
This is an experimental script. If you find bugs, please consider debugging yourself then submitting a PR on github with the fix, instead of raising an issue. Thank you!
This script modifies the color lightness/hue/saturation/transparency of selected Excalidraw elements and SVG and nested Excalidraw drawings. Select eligible elements in the scene, then run the script.
- The color of Excalidraw elements (lines, ellipses, rectangles, etc.) will be changed by the script.
- The color of SVG elements and nested Excalidraw drawings will only be mapped. When mapping colors, the original image remains unchanged, only a mapping table is created and the image is recolored during rendering of your Excalidraw screen. In case you want to make manual changes you can also edit the mapping in Markdown View Mode under `## Embedded Files`
If you select only a single SVG or nested Excalidraw element, then the script offers an additional feature. You can map colors one by one in the image.
*/
const HELP_TEXT = `
- Select SVG images, nested Excalidraw drawings and/or regular Excalidraw elements
- For a single selected image, you can map colors individually in the color mapping section
- For Excalidraw elements: stroke and background colors are modified permanently
- For SVG/nested drawings: original files stay unchanged, color mapping is stored under \`## Embedded Files\`
- Using color maps helps maintain links between drawings while allowing different color themes
- Sliders work on relative scale - the amount of change is applied to current values
- Unlike Excalidraw's opacity setting which affects the whole element:
- Shade Master can set different opacity for stroke vs background
- **Note:** SVG/nested drawing colors are mapped at color name level, thus "black" is different from "#000000"
- Additionally if the same color is used as fill and stroke the color can only be mapped once
- This is an experimental script - contributions welcome on GitHub via PRs
<div class="ex-coffee-div"><a href="https://ko-fi.com/zsolt"><img src="https://storage.ko-fi.com/cdn/kofi6.png?v=6" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
<a href="https://www.youtube.com/watch?v=ISuORbVKyhQ" target="_blank"><img src ="https://i.ytimg.com/vi/ISuORbVKyhQ/maxresdefault.jpg" style="max-width:560px; width:100%"></a>
`;
if(!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.19.1")) {
new Notice("Please update the Excalidraw Plugin to version 2.19.1 or higher.");
return;
}
const existingTab = ea.checkForActiveSidepanelTabForScript();
if (existingTab) {
const hostEA = existingTab.getHostEA();
if (hostEA && hostEA !== ea) {
hostEA.setView(ea.targetView);
existingTab.open();
return;
}
}
/*
SVGColorInfo is returned by ea.getSVGColorInfoForImgElement. Color info will all the color strings in the SVG file plus "fill" which represents the default fill color for SVG icons set at the SVG root element level. Fill if not set defaults to black:
type SVGColorInfo = Map<string, {
mappedTo: string;
fill: boolean;
stroke: boolean;
}>;
In the Excalidraw file under `## Embedded Files` the color map is included after the file. That color map implements ColorMap. ea.updateViewSVGImageColorMap takes a ColorMap as input.
interface ColorMap {
[color: string]: string;
};
*/
// Main script state variables
let allElements = [];
let svgImageElements = [];
let lastSelectionIds = "";
const originalColors = new Map();
const currentColors = new Map();
const colorInputs = new Map();
const sliderResetters = [];
let terminate = false;
const FORMAT = "Color Format";
const STROKE = "Modify Stroke Color";
const BACKGROUND = "Modify Background Color"
const ACTIONS = ["Hue", "Lightness", "Saturation", "Transparency"];
const precision = [1,2,2,3];
const minLigtness = 1/Math.pow(10,precision[2]);
const maxLightness = 100 - minLigtness;
const minSaturation = 1/Math.pow(10,precision[2]);
let settings = ea.getScriptSettings();
//set default values on first run
if(!settings[STROKE]) {
settings = {};
settings[FORMAT] = {
value: "HEX",
valueset: ["HSL", "RGB", "HEX"],
description: "Output color format."
};
settings[STROKE] = { value: true }
settings[BACKGROUND] = {value: true }
ea.setScriptSettings(settings);
}
function getRegularElements() {
if (!ea.targetView) return [];
ea.clear();
//loading view elements again as element objects change when colors are updated
const viewElements = ea.getViewSelectedElements();
return viewElements.filter(el =>
["rectangle", "ellipse", "diamond", "line", "arrow", "freedraw", "text"].includes(el.type)
);
}
const updatedImageElementColorMaps = new Map();
let isWaitingForSVGUpdate = false;
function updateViewImageColors() {
if(terminate || isWaitingForSVGUpdate || updatedImageElementColorMaps.size === 0) {
return;
}
isWaitingForSVGUpdate = true;
elementArray = Array.from(updatedImageElementColorMaps.keys());
colorMapArray = Array.from(updatedImageElementColorMaps.values());
updatedImageElementColorMaps.clear();
ea.updateViewSVGImageColorMap(elementArray, colorMapArray).then(()=>{
isWaitingForSVGUpdate = false;
updateViewImageColors();
});
}
async function storeOriginalColors() {
// Clear previous state
originalColors.clear();
currentColors.clear();
// Store colors for regular elements
for (const el of getRegularElements()) {
const key = el.id;
const colorData = {
type: "regular",
strokeColor: el.strokeColor,
backgroundColor: el.backgroundColor
};
originalColors.set(key, colorData);
}
// Store colors for SVG elements
for (const el of svgImageElements) {
const colorInfo = await ea.getSVGColorInfoForImgElement(el);
const svgColors = new Map();
for (const [color, info] of colorInfo.entries()) {
svgColors.set(color, {...info});
}
originalColors.set(el.id, {type: "svg",colors: svgColors});
}
copyOriginalsToCurrent();
}
function copyOriginalsToCurrent() {
currentColors.clear();
for (const [key, value] of originalColors.entries()) {
if(value.type === "regular") {
currentColors.set(key, {...value});
} else {
const newColorMap = new Map();
for (const [color, info] of value.colors.entries()) {
newColorMap.set(color, {...info});
}
currentColors.set(key, {type: "svg", colors: newColorMap});
}
}
}
function clearSVGMapping() {
for (const resetter of sliderResetters) {
resetter();
}
// Reset SVG elements
if (svgImageElements.length === 1) {
const el = svgImageElements[0];
const original = originalColors.get(el.id);
const current = currentColors.get(el.id);
if (original && original.type === "svg") {
for (const color of original.colors.keys()) {
current.colors.get(color).mappedTo = color;
}
}
} else {
for (const el of svgImageElements) {
const original = originalColors.get(el.id);
const current = currentColors.get(el.id);
if (original && original.type === "svg") {
for (const color of original.colors.keys()) {
current.colors.get(color).mappedTo = color;
}
}
}
}
run("clear");
}
// Set colors
async function setColors(colors) {
debounceColorPicker = true;
const regularElements = getRegularElements();
if (regularElements.length > 0) {
ea.copyViewElementsToEAforEditing(regularElements);
for (const el of ea.getElements()) {
const original = colors.get(el.id);
if (original && original.type === "regular") {
if (original.strokeColor) el.strokeColor = original.strokeColor;
if (original.backgroundColor) el.backgroundColor = original.backgroundColor;
}
}
await ea.addElementsToView(false, false);
}
// Reset SVG elements
if (svgImageElements.length === 1) {
const el = svgImageElements[0];
const original = colors.get(el.id);
if (original && original.type === "svg") {
const newColorMap = {};
for (const [color, info] of original.colors.entries()) {
newColorMap[color] = info.mappedTo;
// Update UI components
const inputs = colorInputs.get(color);
if (inputs) {
if(info.mappedTo === "fill") {
info.mappedTo = "black";
//"fill" is a special value in case the SVG has no fill color defined (i.e black)
inputs.textInput.setValue("black");
inputs.colorPicker.setValue("#000000");
} else {
const cm = ea.getCM(info.mappedTo);
inputs.textInput.setValue(info.mappedTo);
inputs.colorPicker.setValue(cm.stringHEX({alpha: false}).toLowerCase());
}
}
}
updatedImageElementColorMaps.set(el, newColorMap);
}
} else {
for (const el of svgImageElements) {
const original = colors.get(el.id);
if (original && original.type === "svg") {
const newColorMap = {};
for (const [color, info] of original.colors.entries()) {
newColorMap[color] = info.mappedTo;
}
updatedImageElementColorMaps.set(el, newColorMap);
}
}
}
updateViewImageColors();
}
function modifyColor(color, isDecrease, step, action) {
if (!color) return null;
const cm = ea.getCM(color);
if (!cm) return color;
let modified = cm;
if (modified.lightness === 0) modified = modified.lightnessTo(minLigtness);
if (modified.lightness === 100) modified = modified.lightnessTo(maxLightness);
if (modified.saturation === 0) modified = modified.saturationTo(minSaturation);
switch(action) {
case "Lightness":
// handles edge cases where lightness is 0 or 100 would convert saturation and hue to 0
let lightness = cm.lightness;
const shouldRoundLight = (lightness === minLigtness || lightness === maxLightness);
if (shouldRoundLight) lightness = Math.round(lightness);
lightness += isDecrease ? -step : step;
if (lightness <= 0) lightness = minLigtness;
if (lightness >= 100) lightness = maxLightness;
modified = modified.lightnessTo(lightness);
break;
case "Hue":
modified = isDecrease ? modified.hueBy(-step) : modified.hueBy(step);
break;
case "Transparency":
modified = isDecrease ? modified.alphaBy(-step) : modified.alphaBy(step);
break;
default:
let saturation = cm.saturation;
const shouldRoundSat = saturation === minSaturation;
if (shouldRoundSat) saturation = Math.round(saturation);
saturation += isDecrease ? -step : step;
if (saturation <= 0) saturation = minSaturation;
modified = modified.saturationTo(saturation);
}
const hasAlpha = modified.alpha < 1;
const opts = { alpha: hasAlpha, precision };
const format = settings[FORMAT].value;
switch(format) {
case "RGB": return modified.stringRGB(opts).toLowerCase();
case "HEX": return modified.stringHEX(opts).toLowerCase();
default: return modified.stringHSL(opts).toLowerCase();
}
}
function slider(contentEl, action, min, max, step, invert) {
let prevValue = (max-min)/2;
let debounce = false;
let sliderControl;
new ea.obsidian.Setting(contentEl)
.setName(action)
.addSlider(slider => {
sliderControl = slider;
slider
.setLimits(min, max, step)
.setValue(prevValue)
.onChange(async (value) => {
if (debounce) return;
const isDecrease = invert ? value > prevValue : value < prevValue;
const step = Math.abs(value-prevValue);
prevValue = value;
if(step>0) {
run(action, isDecrease, step);
}
});
}
);
return () => {
debounce = true;
prevValue = (max-min)/2;
sliderControl.setValue(prevValue);
debounce = false;
}
}
let debounceColorPicker = true;
// Replaces showModal with renderSidepanel logic
function renderSidepanel(contentEl) {
contentEl.empty();
contentEl.createEl('h2', { text: 'Shade Master' });
const helpDiv = contentEl.createEl("details", {
attr: { style: "margin-bottom: 1em;background: var(--background-secondary); padding: 1em; border-radius: 4px;" }});
helpDiv.createEl("summary", { text: "Help & Usage Guide", attr: { style: "cursor: pointer; color: var(--text-accent);" } });
const helpDetailsDiv = helpDiv.createEl("div", {
attr: { style: "margin-top: 0em; " }
});
ea.obsidian.MarkdownRenderer.render(ea.plugin.app, HELP_TEXT, helpDetailsDiv, "", ea.plugin);
if (!ea.targetView) {
contentEl.createEl("p", {
text: "No active Excalidraw view found. Please open a drawing and select elements to use Shade Master.",
attr: { style: "color: var(--text-muted);" }
});
return;
}
const { width, height } = ea.getExcalidrawAPI().getAppState();
if(allElements.length === 0) {
contentEl.createEl("p", {
text: "Select at least one rectangle, ellipse, diamond, line, arrow, freedraw, text or SVG image element",
attr: { style: "color: var(--text-warning);" }
});
return;
}
const component = new ea.obsidian.Setting(contentEl)
.setName(FORMAT)
.setDesc("Output color format")
.addDropdown(dropdown => dropdown
.addOptions({
"HSL": "HSL",
"RGB": "RGB",
"HEX": "HEX"
})
.setValue(settings[FORMAT].value)
.onChange(value => {
settings[FORMAT].value = value;
run();
dirty = true;
})
);
new ea.obsidian.Setting(contentEl)
.setName(STROKE)
.addToggle(toggle => toggle
.setValue(settings[STROKE].value)
.onChange(value => {
settings[STROKE].value = value;
dirty = true;
})
);
new ea.obsidian.Setting(contentEl)
.setName(BACKGROUND)
.addToggle(toggle => toggle
.setValue(settings[BACKGROUND].value)
.onChange(value => {
settings[BACKGROUND].value = value;
dirty = true;
})
);
sliderResetters.length = 0; // Clear existing resetters
sliderResetters.push(slider(contentEl, "Hue", 0, 360, 1, false));
sliderResetters.push(slider(contentEl, "Saturation", 0, 200, 1, false));
sliderResetters.push(slider(contentEl, "Lightness", 0, 200, 1, false));
sliderResetters.push(slider(contentEl, "Transparency", 0, 2, 0.05, true));
// Add color pickers if a single SVG image is selected
if (svgImageElements.length === 1) {
const svgElement = svgImageElements[0];
const initialColorInfo = currentColors.get(svgElement.id).colors;
const colorSection = contentEl.createDiv();
colorSection.createEl('h3', { text: 'SVG Colors' });
colorInputs.clear(); // Clear old inputs map
for (const [color, info] of initialColorInfo.entries()) {
const row = new ea.obsidian.Setting(colorSection)
.setName(color === "fill" ? "SVG default" : color)
.setDesc(`${info.fill ? "Fill" : ""}${info.fill && info.stroke ? " & " : ""}${info.stroke ? "Stroke" : ""}`);
row.descEl.style.width = "100px";
row.nameEl.style.width = "100px";
// Create color preview div
const previewDiv = row.controlEl.createDiv();
previewDiv.style.width = "50px";
previewDiv.style.height = "20px";
previewDiv.style.border = "1px solid var(--background-modifier-border)";
if (color === "transparent") {
previewDiv.style.backgroundImage = "linear-gradient(45deg, #808080 25%, transparent 25%), linear-gradient(-45deg, #808080 25%, transparent 25%), linear-gradient(45deg, transparent 75%, #808080 75%), linear-gradient(-45deg, transparent 75%, #808080 75%)";
previewDiv.style.backgroundSize = "10px 10px";
previewDiv.style.backgroundPosition = "0 0, 0 5px, 5px -5px, -5px 0px";
} else {
previewDiv.style.backgroundColor = ea.getCM(color).stringHEX({alpha: false}).toLowerCase();
}
const resetButton = new ea.obsidian.Setting(row.controlEl)
.addButton(button => button
.setButtonText(">>")
.setClass("reset-color-button")
.onClick(async () => {
const original = originalColors.get(svgElement.id);
const current = currentColors.get(svgElement.id);
if (original?.type === "svg") {
const originalInfo = original.colors.get(color);
const currentInfo = current.colors.get(color);
if (originalInfo) {
currentInfo.mappedTo = color;
run("reset single color");
}
}
}))
resetButton.settingEl.style.padding = "0";
resetButton.settingEl.style.border = "0";
// Add text input for color value
const textInput = new ea.obsidian.TextComponent(row.controlEl)
.setValue(info.mappedTo)
.setPlaceholder("Color value");
textInput.inputEl.style.width = "100%";
textInput.onChange(value => {
const lower = value.toLowerCase();
if (lower === color) return;
textInput.setValue(lower);
})
const applyButtonComponent = new ea.obsidian.Setting(row.controlEl)
.addButton(button => button
.setIcon("check")
.setTooltip("Apply")
.onClick(async () => {
const value = textInput.getValue();
try {
if(!CSS.supports("color",value)) {
new Notice (`${value} is not a valid color string`);
return;
}
const cm = ea.getCM(value);
if (cm) {
const format = settings[FORMAT].value;
const alpha = cm.alpha < 1 ? true : false;
const newColor = format === "RGB"
? cm.stringRGB({alpha , precision }).toLowerCase()
: format === "HEX"
? cm.stringHEX({alpha}).toLowerCase()
: cm.stringHSL({alpha, precision }).toLowerCase();
textInput.setValue(newColor);
const currentInfo = currentColors.get(svgElement.id).colors;
currentInfo.get(color).mappedTo = newColor;
run("Update SVG color");
debounceColorPicker = true;
colorPicker.setValue(cm.stringHEX({alpha: false}).toLowerCase());
}
} catch (e) {
console.error("Invalid color value:", e);
}
}));
applyButtonComponent.settingEl.style.padding = "0";
applyButtonComponent.settingEl.style.border = "0";
// Add color picker
const colorPicker = new ea.obsidian.ColorComponent(row.controlEl)
.setValue(ea.getCM(info.mappedTo).stringHEX({alpha: false}).toLowerCase());
colorPicker.colorPickerEl.style.maxWidth = "2.5rem";
// Add palette picker button
const paletteButton = new ea.obsidian.Setting(row.controlEl)
.addButton(button => button
.setIcon("swatch-book")
.setTooltip("Pick from Palette")
.onClick(async () => {
const selected = await ea.showColorPicker(button.buttonEl, "elementStroke");
if (selected) {
try {
const cm = ea.getCM(selected);
if (cm) {
const format = settings[FORMAT].value;
// Preserve alpha from original color
const currentInfo = currentColors.get(svgElement.id).colors.get(color);
const originalAlpha = ea.getCM(currentInfo.mappedTo).alpha;
cm.alphaTo(originalAlpha);
const alpha = originalAlpha < 1 ? true : false;
const newColor = format === "RGB"
? cm.stringRGB({alpha , precision }).toLowerCase()
: format === "HEX"
? cm.stringHEX({alpha}).toLowerCase()
: cm.stringHSL({alpha, precision }).toLowerCase();
// Update text input
textInput.setValue(newColor);
// Update Color Picker visual
colorPicker.setValue(cm.stringHEX({alpha: false}).toLowerCase());
// Update SVG mapping
currentInfo.mappedTo = newColor;
run("Update SVG color");
}
} catch (e) {
console.error("Invalid color value:", e);
}
}
}));
paletteButton.settingEl.style.padding = "0";
paletteButton.settingEl.style.border = "0";
paletteButton.infoEl.style.display = "none";
// Store references to the components
colorInputs.set(color, {
textInput,
colorPicker,
previewDiv,
resetButton
});
colorPicker.colorPickerEl.addEventListener('click', () => {
debounceColorPicker = false;
});
colorPicker.onChange(async (value) => {
try {
if(!debounceColorPicker) {
const currentInfo = currentColors.get(svgElement.id).colors.get(color);
// Preserve alpha from original color
const originalAlpha = ea.getCM(currentInfo.mappedTo).alpha;
const cm = ea.getCM(value);
cm.alphaTo(originalAlpha);
const alpha = originalAlpha < 1 ? true : false;
const format = settings[FORMAT].value;
const newColor = format === "RGB"
? cm.stringRGB({alpha, precision }).toLowerCase()
: format === "HEX"
? cm.stringHEX({alpha}).toLowerCase()
: cm.stringHSL({alpha, precision }).toLowerCase();
// Update text input
textInput.setValue(newColor);
// Update SVG
currentInfo.mappedTo = newColor;
run("Update SVG color");
}
} catch (e) {
console.error("Invalid color value:", e);
} finally {
debounceColorPicker = true;
}
});
}
}
const buttons = new ea.obsidian.Setting(contentEl);
if(svgImageElements.length > 0) {
buttons.addButton(button => button
.setButtonText("Initialize SVG Colors")
.onClick(() => {
debounceColorPicker = true;
clearSVGMapping();
})
);
}
buttons
.addButton(button => button
.setButtonText("Reset")
.onClick(() => {
for (const resetter of sliderResetters) {
resetter();
}
copyOriginalsToCurrent();
setColors(originalColors);
}));
// Close button removed for sidepanel implementation
}
function executeChange(isDecrease, step, action) {
const modifyStroke = settings[STROKE].value;
const modifyBackground = settings[BACKGROUND].value;
const regularElements = getRegularElements();
// Process regular elements
if (regularElements.length > 0) {
for (const el of regularElements) {
const currentColor = currentColors.get(el.id);
if (modifyStroke && currentColor.strokeColor) {
currentColor.strokeColor = modifyColor(el.strokeColor, isDecrease, step, action);
}
if (modifyBackground && currentColor.backgroundColor) {
currentColor.backgroundColor = modifyColor(el.backgroundColor, isDecrease, step, action);
}
}
}
// Process SVG image elements
if (svgImageElements.length === 1) { // Only update UI for single SVG
const el = svgImageElements[0];
colorInfo = currentColors.get(el.id).colors;
// Process each color in the SVG
for (const [color, info] of colorInfo.entries()) {
let shouldModify = (modifyBackground && info.fill) || (modifyStroke && info.stroke);
if (shouldModify) {
const modifiedColor = modifyColor(info.mappedTo, isDecrease, step, action);
colorInfo.get(color).mappedTo = modifiedColor;
// Update UI components if they exist
const inputs = colorInputs.get(color);
if (inputs) {
const cm = ea.getCM(modifiedColor);
inputs.textInput.setValue(modifiedColor);
inputs.colorPicker.setValue(cm.stringHEX({alpha: false}).toLowerCase());
}
}
}
} else {
if (svgImageElements.length > 0) {
for (const el of svgImageElements) {
const colorInfo = currentColors.get(el.id).colors;
// Process each color in the SVG
for (const [color, info] of colorInfo.entries()) {
let shouldModify = (modifyBackground && info.fill) || (modifyStroke && info.stroke);
if (shouldModify) {
const modifiedColor = modifyColor(info.mappedTo, isDecrease, step, action);
colorInfo.get(color).mappedTo = modifiedColor;
}
}
}
}
}
}
let isRunning = false;
let queue = false;
function processQueue() {
if (!terminate && !isRunning && queue) {
queue = false;
isRunning = true;
setColors(currentColors).then(() => {
isRunning = false;
if (queue) processQueue();
});
}
}
function run(action="Hue", isDecrease=true, step=0) {
// passing invalid action (such as "clear") will bypass rewriting of colors using CM
// this is useful when resetting colors to original values
if(ACTIONS.includes(action)) {
executeChange(isDecrease, step, action);
}
queue = true;
if (!isRunning) processQueue();
}
// Function to refresh internal state based on current selection
function refreshSelectionState() {
if (!ea.targetView) {
allElements = [];
svgImageElements = [];
lastSelectionIds = "";
return;
}
allElements = ea.getViewSelectedElements();
svgImageElements = allElements.filter(el => {
if(el.type !== "image") return false;
const file = ea.getViewFileForImageElement(el);
if(!file) return false;
return el.type === "image" && (
file.extension === "svg" ||
ea.isExcalidrawFile(file)
);
});
lastSelectionIds = allElements.map(e => e.id).sort().join(",");
}
// Sidepanel initialization and logic
ea.createSidepanelTab("Shade Master", true, true).then(tab => {
if (!tab) return;
const initializeAndRender = async () => {
refreshSelectionState();
await storeOriginalColors();
renderSidepanel(tab.contentEl);
processQueue();
};
tab.onOpen = async () => {
terminate = false;
// Initial load
await initializeAndRender();
};
tab.onFocus = async (view) => {
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.onClose = async () => {
terminate = true;
if (dirty) {
ea.setScriptSettings(settings);
}
if(ea.targetView && ea.targetView.isDirty()) {
ea.targetView.save(false);
}
};
tab.open();
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.20.0-beta-2",
"version": "2.20.0-beta-4",
"minAppVersion": "1.5.7",
"description": "Sketch Your Mind. An Obsidian plugin to edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+7 -7
View File
@@ -11,7 +11,7 @@
"dependencies": {
"@popperjs/core": "^2.11.8",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.0-69",
"@zsviczian/excalidraw": "0.18.0-71",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -3753,9 +3753,9 @@
"license": "MIT"
},
"node_modules/@zsviczian/excalidraw": {
"version": "0.18.0-69",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.0-69.tgz",
"integrity": "sha512-fdSLmYiNakLRKLzLJ1Xj4l9mmIEoEhZBh3izQz1C9VH7fLf8mAM7hXIUGhrr0ErkAKF2ULQvWHxIJ+iUvCL2fQ==",
"version": "0.18.0-71",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.0-71.tgz",
"integrity": "sha512-EmK1W0iN6Rg0Scv9n6hep8SNImYgd6pp3Zzb7U8TkoMSN5aIXTTB2cOTUwsFU85RaQW4ezmk3bMleL+nRMBFYQ==",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
"@excalidraw/mermaid-to-excalidraw": "2.0.0-rfc3",
@@ -11704,9 +11704,9 @@
"integrity": "sha512-ZqLIY9odz5JOG0t6gc9jjM96y+c3aAINNj8D3Xd9vaXSqCscQOE7hInG0U0rRlL4dvUaaHuDxAGxo7eGgeL01A=="
},
"@zsviczian/excalidraw": {
"version": "0.18.0-69",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.0-69.tgz",
"integrity": "sha512-fdSLmYiNakLRKLzLJ1Xj4l9mmIEoEhZBh3izQz1C9VH7fLf8mAM7hXIUGhrr0ErkAKF2ULQvWHxIJ+iUvCL2fQ==",
"version": "0.18.0-71",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.0-71.tgz",
"integrity": "sha512-EmK1W0iN6Rg0Scv9n6hep8SNImYgd6pp3Zzb7U8TkoMSN5aIXTTB2cOTUwsFU85RaQW4ezmk3bMleL+nRMBFYQ==",
"requires": {
"@braintree/sanitize-url": "6.0.2",
"@excalidraw/mermaid-to-excalidraw": "2.0.0-rfc3",
+1 -1
View File
@@ -25,7 +25,7 @@
"license": "MIT",
"dependencies": {
"@popperjs/core": "^2.11.8",
"@zsviczian/excalidraw": "0.18.0-69",
"@zsviczian/excalidraw": "0.18.0-71",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"@zsviczian/colormaster": "^1.2.2",
+1 -2
View File
@@ -1,4 +1,3 @@
export const TAG_PDFEXPORT = "PDFExport";
export const TAG_MDREADINGMODE = "MDReadingMode";
export const TAG_AUTOEXPORT = "Autoexport";
export const TAG_IMAGECACHE = "ResetImageCache";
export const TAG_AUTOEXPORT = "Autoexport";
+3 -69
View File
@@ -2,7 +2,6 @@ import {
App,
ButtonComponent,
DropdownComponent,
ExtraButtonComponent,
getIcon,
Modifier,
normalizePath,
@@ -11,7 +10,7 @@ import {
TextComponent,
TFile,
} from "obsidian";
import { GITHUB_RELEASES, setRootElementSize, THEME_FILTER } from "src/constants/constants";
import { GITHUB_RELEASES, setRootElementSize } from "src/constants/constants";
import { t } from "src/lang/helpers";
import type ExcalidrawPlugin from "src/core/main";
import { PenStyle } from "src/types/penTypes";
@@ -39,7 +38,7 @@ import { ANNOTATED_PREFIX, CROPPED_PREFIX } from "src/utils/carveout";
import { EDITOR_FADEOUT } from "src/core/editor/EditorHandler";
import { setDebugging } from "src/utils/debugHelper";
import { Rank } from "src/constants/actionIcons";
import { TAG_AUTOEXPORT, TAG_IMAGECACHE, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
import { TAG_AUTOEXPORT, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
import { HotkeyEditor } from "src/shared/Dialogs/HotkeyEditor";
import { getExcalidrawViews } from "src/utils/obsidianUtils";
import { createSliderWithText } from "src/utils/sliderUtils";
@@ -49,9 +48,6 @@ import { UIMode, UIModeSettingsComponent } from "src/shared/Dialogs/UIModeSettin
import { ScriptSettingValue } from "src/types/excalidrawAutomateTypes";
export interface ExcalidrawSettings {
invertSVGforDarkMode: boolean;
invertBitmapforDarkMode: boolean;
themeFilter: string;
copyLinkToElemenetAnchorTo100: boolean;
copyFrameLinkByName: boolean;
disableDoubleClickTextEditing: boolean;
@@ -243,9 +239,6 @@ export interface ExcalidrawSettings {
declare const PLUGIN_VERSION:string;
export const DEFAULT_SETTINGS: ExcalidrawSettings = {
invertSVGforDarkMode: true,
invertBitmapforDarkMode: false,
themeFilter: THEME_FILTER,
copyLinkToElemenetAnchorTo100: false,
copyFrameLinkByName: false,
disableDoubleClickTextEditing: false,
@@ -2230,7 +2223,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}
});
const embedImageCacheSetting = new Setting(detailsEl)
new Setting(detailsEl)
.setName(t("EMBED_IMAGE_CACHE_NAME"))
.setDesc(fragWithHTML(t("EMBED_IMAGE_CACHE_DESC")))
.addToggle((toggle) =>
@@ -2241,7 +2234,6 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
})
)
embedImageCacheSetting.controlEl.setAttribute("id",TAG_IMAGECACHE);
new Setting(detailsEl)
.setName(t("SCENE_IMAGE_CACHE_NAME"))
.setDesc(fragWithHTML(t("SCENE_IMAGE_CACHE_DESC")))
@@ -2424,64 +2416,6 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
this.applySettingsUpdate();
}),
);
new Setting(detailsEl)
.setName(t("EMBED_INVERT_SVG"))
.setDesc(fragWithHTML(t("EMBED_INVERT_SVG_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.invertSVGforDarkMode)
.onChange(async (value) => {
this.plugin.settings.invertSVGforDarkMode = value;
this.applySettingsUpdate();
}),
);
new Setting(detailsEl)
.setName(t("EMBED_INVERT_BITMAP"))
.setDesc(fragWithHTML(t("EMBED_INVERT_BITMAP_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.invertBitmapforDarkMode)
.onChange(async (value) => {
this.plugin.settings.invertBitmapforDarkMode = value;
this.applySettingsUpdate();
}),
);
let themeFilterSettingText:TextComponent;
let themeFilterResetButton:ExtraButtonComponent;
new Setting(detailsEl)
.setName(t("EMBED_THEME_FILTER_NAME"))
.setDesc(fragWithHTML(t("EMBED_THEME_FILTER_DESC")))
.addText((text) => {
themeFilterSettingText = text;
text
.setPlaceholder("e.g.: brightness(0.9) contrast(1.2)")
.setValue(this.plugin.settings.themeFilter)
.onChange(async (value) => {
this.plugin.settings.themeFilter = value;
this.applySettingsUpdate();
if (value !== THEME_FILTER) {
themeFilterResetButton.extraSettingsEl.style.display = "";
}
})
})
.addExtraButton((btn) => {
themeFilterResetButton = btn;
btn
.setIcon("rotate-ccw")
.setTooltip(t("RESET")!)
.onClick(() => {
themeFilterSettingText.setValue(THEME_FILTER);
this.plugin.settings.themeFilter = THEME_FILTER;
themeFilterResetButton.extraSettingsEl.style.display = "none";
this.applySettingsUpdate();
})
});
if(this.plugin.settings.themeFilter === THEME_FILTER) {
themeFilterResetButton.extraSettingsEl.style.display = "none";
}
detailsEl = exportDetailsEl.createEl("details");
detailsEl.createEl("summary", {
+5 -10
View File
@@ -3,7 +3,7 @@ import {
FRONTMATTER_KEYS,
CJK_FONTS,
} from "src/constants/constants";
import { TAG_AUTOEXPORT, TAG_IMAGECACHE, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
import { TAG_AUTOEXPORT, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
import { labelALT, labelCTRL, labelMETA, labelSHIFT } from "src/utils/modifierkeyHelper";
declare const PLUGIN_VERSION:string;
@@ -93,6 +93,8 @@ export default {
CONVERT_CARD_TO_FILE: "Move back-of-note card to File",
ERROR_TRY_AGAIN: "Please try again.",
PASTE_CODEBLOCK: "Paste code block",
INVERT_IMAGES_IN_DARK_MODE: "Invert image(s) in dark mode",
DO_NOT_INVERT_IMAGES_IN_DARK_MODE: "Do not invert image(s) in dark mode",
INSERT_LATEX:
`Insert LaTeX formula (e.g. \\binom{n}{k} = \\frac{n!}{k!(n-k)!}).`,
ENTER_LATEX: "Enter a valid LaTeX expression",
@@ -688,13 +690,6 @@ export default {
EMBED_IMAGE_CACHE_NAME: "Cache images for embedding in markdown",
EMBED_IMAGE_CACHE_DESC: "Cache images for embedding in markdown. This will speed up the embedding process, but in case you compose images of several sub-component drawings, " +
"the embedded image in Markdown won't update until you open the drawing and save it to trigger an update of the cache.",
EMBED_INVERT_SVG: "Invert embedded Excalidraw drawings and SVG images in dark mode",
EMBED_INVERT_SVG_DESC: "The change will only take affect when you reopen your drawing. When changing this setting, you may need to clear the <a href='#"+TAG_IMAGECACHE+"'>image cache</a>. This is the default for all images; set colorMap.invertInDarkMode to override per image.",
EMBED_INVERT_BITMAP: "Invert embedded bitmap images in dark mode",
EMBED_INVERT_BITMAP_DESC: "The change will only take affect when you reopen your drawing. When changing this setting, you may need to clear the <a href='#"+TAG_IMAGECACHE+"'>image cache</a>. This is the default for all images; set colorMap.invertInDarkMode to override per image.",
EMBED_THEME_FILTER_NAME: "Theme filter for color inversion",
EMBED_THEME_FILTER_DESC: "Modify this only if you know what you are doing. The change will only take affect when you reopen your drawing. When changing this setting, you may need to clear the <a href='#"+TAG_IMAGECACHE+"'>image cache</a>.",
RESET: "Reset to default",
SCENE_IMAGE_CACHE_NAME: "Cache nested Excalidraws in Scene",
SCENE_IMAGE_CACHE_DESC: "Cache nested Excalidraws in the Scene for faster scene rendering. This will speed up the rendering process, especially if you have deeply nested Excalidraws in your scene. " +
"Excalidraw will try to intelligently identify if any children of a nested Excalidraw have changed and will update the cache accordingly. " +
@@ -1225,8 +1220,8 @@ export default {
UIFM_SECTION_HEAD: "Select section heading",
UIFM_ANCHOR: "Anchor to 100% of original size",
UIFM_ANCHOR_DESC: "This is a pro feature, use it only if you understand how it works. If enabled even if you change the size of the imported image in Excalidraw, the next time you open the drawing this image will pop back to 100% size. This is useful when embedding an atomic Excalidraw idea into another note and preserving relative sizing of text and icons.",
UIFM_BTN_EMBEDDABLE: "as Embeddable",
UIFM_BTN_PDF: "as Pdf",
UIFM_BTN_EMBEDDABLE: "PDF as Embeddable",
UIFM_BTN_PDF: "PDF as Image",
UIFM_BTN_IMAGE: "as Image",
//ReleaseNotes.ts
+1 -8
View File
@@ -3,7 +3,7 @@ import {
FRONTMATTER_KEYS,
CJK_FONTS,
} from "src/constants/constants";
import { TAG_AUTOEXPORT, TAG_IMAGECACHE, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
import { TAG_AUTOEXPORT, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
import { labelALT, labelCTRL, labelMETA, labelSHIFT } from "src/utils/modifierkeyHelper";
declare const PLUGIN_VERSION:string;
@@ -688,13 +688,6 @@ export default {
EMBED_IMAGE_CACHE_NAME: "为嵌入到 Markdown 文档中的绘图创建预览图缓存",
EMBED_IMAGE_CACHE_DESC: "可提高下次嵌入的速度。" +
"但如果绘图包含子绘图,(当子绘图改变时)预览图不会更新,直到您打开绘图并手动保存。",
EMBED_INVERT_SVG: "深色主题下反转嵌入的 Excalidraw 绘图和 SVG 图像",
EMBED_INVERT_SVG_DESC: "重新打开绘图后生效。可能需要配合清除 <a href='#"+TAG_IMAGECACHE+"'>预览图缓存</a>。可为某个图像单独设置 colorMap.invertInDarkMode。",
EMBED_INVERT_BITMAP: "深色主题下反转嵌入的位图图像",
EMBED_INVERT_BITMAP_DESC: "重新打开绘图后生效。可能需要配合清除 <a href='#"+TAG_IMAGECACHE+"'>预览图缓存</a>。可为某个图像单独设置 colorMap.invertInDarkMode。",
EMBED_THEME_FILTER_NAME: "用于颜色反转的主题滤镜",
EMBED_THEME_FILTER_DESC: "谨慎修改。重新打开绘图后生效。可能需要配合清除 <a href='#"+TAG_IMAGECACHE+"'>预览图缓存</a>。",
RESET: "恢复默认",
SCENE_IMAGE_CACHE_NAME: "缓存场景中嵌套的绘图",
SCENE_IMAGE_CACHE_DESC: "Excalidraw 将智能地尝试识别嵌套的绘图的子元素是否发生变化,并更新缓存。" +
"这将加快渲染过程,特别是在您的场景中有深度嵌套的绘图时。<br>" +
+79 -28
View File
@@ -20,6 +20,7 @@ export class InsertPDFModal extends Modal {
private lockAfterImport: boolean = true;
private pagesToImport:number[] = [];
private pageDimensions: {width: number, height: number} = {width: 0, height: 0};
private pageDimensionsByPage: Map<number, {width: number; height: number}> = new Map();
private importScale = 0.3;
private imageSizeMessage: HTMLElement;
private pdfDoc: any;
@@ -63,6 +64,7 @@ export class InsertPDFModal extends Modal {
this.pdfDoc.destroy();
this.pdfDoc = null;
}
this.pageDimensionsByPage.clear();
this.plugin = null;
this.view = null;
this.app = null;
@@ -70,23 +72,44 @@ export class InsertPDFModal extends Modal {
this.setImageSizeMessage = null;
}
private async getPDFPageDimensions (pdfDoc: any) {
try {
const scale = this.plugin.settings.pdfScale;
const canvas = createEl("canvas");
const page = await pdfDoc.getPage(1);
// Set scale
const viewport = page.getViewport({ scale });
this.pageDimensions.height = viewport.height;
this.pageDimensions.width = viewport.width;
//https://github.com/excalidraw/excalidraw/issues/4036
canvas.width = 0;
canvas.height = 0;
this.setImageSizeMessage();
} catch(e) {
console.log(e);
private async loadPageDimensions(pages?: number[]) {
if(!this.pdfDoc) return;
const scale = this.plugin.settings.pdfScale;
const pagesToLoad = pages && pages.length > 0 ? [...new Set(pages)] : [1];
for (const pageNum of pagesToLoad) {
if(this.pageDimensionsByPage.has(pageNum)) continue;
try {
const page = await this.pdfDoc.getPage(pageNum);
const viewport = page.getViewport({ scale });
this.pageDimensionsByPage.set(pageNum, { width: viewport.width, height: viewport.height });
} catch(e) {
console.log(e);
}
}
this.pageDimensions = this.getMaxSelectedPageDimensions();
this.setImageSizeMessage();
}
private getMaxSelectedPageDimensions() {
let width = 0;
let height = 0;
const pages = this.pagesToImport.length > 0
? this.pagesToImport
: Array.from(this.pageDimensionsByPage.keys());
pages.forEach((p) => {
const dims = this.pageDimensionsByPage.get(p);
if(!dims) return;
width = Math.max(width, dims.width);
height = Math.max(height, dims.height);
});
if(width === 0 || height === 0) {
const first = this.pageDimensionsByPage.values().next().value;
if(first) {
width = first.width;
height = first.height;
}
}
return { width, height };
}
@@ -118,7 +141,11 @@ export class InsertPDFModal extends Modal {
return this.pagesToImport;
}
private setImageSizeMessage = () => this.imageSizeMessage.innerText = `${Math.round(this.pageDimensions.width*this.importScale)} x ${Math.round(this.pageDimensions.height*this.importScale)}`;
private setImageSizeMessage = () => {
if(!this.imageSizeMessage) return;
const dims = this.getMaxSelectedPageDimensions();
this.imageSizeMessage.innerText = `${Math.round(dims.width*this.importScale)} x ${Math.round(dims.height*this.importScale)}`;
};
async createForm() {
await this.plugin.loadSettings();
@@ -136,7 +163,7 @@ export class InsertPDFModal extends Modal {
let numPagesMessage: HTMLParagraphElement;
let numPages: number;
let numPages: number = 0;
let importButton: ButtonComponent;
let importMessage: HTMLElement;
@@ -174,8 +201,15 @@ export class InsertPDFModal extends Modal {
let pageRangesTextComponent: TextComponent
let importPagesMessage: HTMLParagraphElement;
const rangeOnChange = (value:string) => {
const rangeOnChange = async (value:string) => {
const pages = this.createPageListFromString(value);
if(this.pdfDoc && pages.length > 0) {
await this.loadPageDimensions(pages);
} else {
this.pageDimensionsByPage.clear();
this.pageDimensions = {width: 0, height: 0};
this.setImageSizeMessage();
}
if(pages.length > 15) {
importPagesMessage.innerHTML = `You are importing <b>${pages.length}</b> pages. ⚠️ This may take a while. ⚠️`;
} else {
@@ -187,6 +221,10 @@ export class InsertPDFModal extends Modal {
const setFile = async (file: TFile) => {
if(this.pdfDoc) await this.pdfDoc.destroy();
this.pdfDoc = null;
this.pageDimensionsByPage.clear();
this.pageDimensions = {width: 0, height: 0};
numPages = 0;
this.setImageSizeMessage();
if(file) {
this.pdfDoc = await getPDFDoc(file);
@@ -194,14 +232,16 @@ export class InsertPDFModal extends Modal {
if(this.pdfDoc) {
numPages = this.pdfDoc.numPages;
pageRangesTextComponent.setValue(`1-${numPages}`);
rangeOnChange(`1-${numPages}`);
await rangeOnChange(`1-${numPages}`);
importButtonMessages();
numPagesMessages();
this.getPDFPageDimensions(this.pdfDoc);
} else {
importButton.setDisabled(true);
}
}
} else {
importButtonMessages();
numPagesMessages();
}
}
const search = new TextComponent(ce);
@@ -225,7 +265,7 @@ export class InsertPDFModal extends Modal {
pageRangesTextComponent = text;
text
.setValue("")
.onChange((value) => rangeOnChange(value))
.onChange(async (value) => { await rangeOnChange(value); })
text.inputEl.style.width = "100%";
})
importPagesMessage = ce.createEl("p", {text: ""});
@@ -382,9 +422,10 @@ export class InsertPDFModal extends Modal {
el.innerText = ` ${this.gapSize.toString()}`;
});
const initialDims = this.getMaxSelectedPageDimensions();
const importSizeSetting = new Setting(ce)
.setName("Imported page size")
.setDesc(`${this.pageDimensions.width*this.importScale} x ${this.pageDimensions.height*this.importScale}`)
.setDesc(`${Math.round(initialDims.width*this.importScale)} x ${Math.round(initialDims.height*this.importScale)}`)
.addSlider(slider => slider
.setLimits(0.1, 1.5, 0.1)
.setValue(this.importScale)
@@ -395,6 +436,7 @@ export class InsertPDFModal extends Modal {
}))
this.imageSizeMessage = importSizeSetting.descEl;
this.setImageSizeMessage();
const actionButton = new Setting(ce)
.setDesc("Select a document first")
@@ -406,13 +448,22 @@ export class InsertPDFModal extends Modal {
const ea = getEA(this.view) as ExcalidrawAutomate;
let column = 0;
let row = 0;
const imgWidth = Math.round(this.pageDimensions.width*this.importScale);
const imgHeight = Math.round(this.pageDimensions.height*this.importScale);
await this.loadPageDimensions(this.pagesToImport);
const maxPageDimensions = this.getMaxSelectedPageDimensions();
const cellWidth = Math.round(maxPageDimensions.width*this.importScale);
const cellHeight = Math.round(maxPageDimensions.height*this.importScale);
if(cellWidth === 0 || cellHeight === 0) {
importMessage.innerText = t("IPM_SELECT_PAGES_TO_IMPORT");
return;
}
for(let i = 0; i < this.pagesToImport.length; i++) {
const page = this.pagesToImport[i];
importMessage.innerText = `Importing page ${page} (${i+1} of ${this.pagesToImport.length})`;
const topX = Math.round(this.pageDimensions.width*this.importScale*column + this.gapSize*column);
const topY = Math.round(this.pageDimensions.height*this.importScale*row + this.gapSize*row);
const dims = this.pageDimensionsByPage.get(page) ?? maxPageDimensions;
const imgWidth = Math.round(dims.width*this.importScale);
const imgHeight = Math.round(dims.height*this.importScale);
const topX = Math.round(cellWidth*column + this.gapSize*column);
const topY = Math.round(cellHeight*row + this.gapSize*row);
ea.style.strokeColor = this.borderBox ? "#000000" : "transparent";
const boxID = ea.addRect(
+11 -8
View File
@@ -19,16 +19,19 @@ I build this plugin in my free time, as a labor of love. Curious about the philo
`,
"2.20.0":`
## New
- Dark theme from Excalidraw.com [#10578](https://github.com/excalidraw/excalidraw/pull/10578)
- New setting in Excalidraw plugin settings under "Embedding Excalidraw/Export Settings/Image Theme". You can now choose to invert embedded SVG/Excalidraw and Bitmap images in dark mode.
- New Easter Egg feature, by adding {"invertColors": true/false} after the embedded file in Excalidraw markdown view, you can control whether the embedded image inverts colors in dark mode or not, regardless of the global setting.
- New from Excalidraw.com: chat-like interface for Mermaid TextToDiagrams (requires OpenAI API key set in Excalidraw plugin settings). [#10530](https://github.com/excalidraw/excalidraw/pull/10530)
- Breaking change: the old force-SVG option for Mermaid diagrams is no longer supported. If a diagram can be rendered as Excalidraw it will be, else, an SVG will be used.
- Dark theme from Excalidraw.com [#10578](https://github.com/excalidraw/excalidraw/pull/10578) (including correct emoji rendering in dark mode 😍).
- New image context-menu option (right-click an image) to control whether that image inverts in dark mode
- Default behavior: SVG-based images (including LaTeX, Mermaid, and nested Excalidraw images) invert in dark mode; bitmap images (PNG/JPG) do not.
- New from Excalidraw.com: chat-style interface for Mermaid TextToDiagrams (requires an OpenAI API key configured in Excalidraw plugin settings). [#10530](https://github.com/excalidraw/excalidraw/pull/10530)
- Breaking change: the legacy “force SVG” option for Mermaid diagrams is no longer supported. If a diagram can be rendered as Excalidraw, it will be; otherwise, an SVG will be used.
- Moved the Shade Master script to use the new Sidepanel (just like MindMap Builder).
## Fixed
- Full screen on phones left a large area at the top of the screen unused. Fixed issue with Obsidian Mobile Navigation bar floating on top of the Excalidraw toolbar.
- Link indicator in top right corner remains visible even if element is set to transparent [#2625](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2625)
- In full-screen mode on phones, a large area at the top of the screen was left unused. Also fixed an issue where the Obsidian Mobile navigation bar could overlap the Excalidraw toolbar.
- The link indicator in the top-right corner would remain visible even when an element was set to transparent [#2625](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2625)
- Importing PDFs with mixed page sizes could produce distorted pages [#2578](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2578)
- Some PDFs failed to load when importing PDFs as images (notably documents using JPEG2000-compressed images). Also improved handling of certain color profiles and cases where text rendered with missing/incorrect glyphs.
- A long-standing export issue: when exporting in a theme different from the current view (e.g., viewing in dark mode but exporting in light mode), nested Excalidraw images containing bitmap images could export with inverted colors.
`,
"2.19.2":`
## Fixed
+6 -7
View File
@@ -417,13 +417,12 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
{
field: "addImage",
code: "async addImage(opts: {topX: number, topY: number, imageFile: TFile|string, scale?: boolean, anchor?: boolean, colorMap?: ColorMap}): Promise<string>;",
desc: "imageFile may be a TFile or a string that contains a hyperlink.\n"+
"imageFile may also be an obsidian filepath including a reference eg.: 'path/my.pdf#page=3'\n"+
"Set scale to false if you want to embed the image at 100% of its original size. Default is true which will insert a scaled image.\n"+
"anchor will only be evaluated if scale is false. anchor true will add |100% to the end of the filename, resulting in an image that will always pop back to 100% when the source file is updated or when the Excalidraw file is reopened.\n"+
"colorMap is only used for SVG images and nested Excalidraw images. See the Shade Master script and the Deconstruct Selected Elements script for examples using colorMap.\n"+
"Set colorMap.invertInDarkMode to force or disable dark-mode inversion for that image.\n"+
"type ColorMap = { [color: string]: string; invertInDarkMode?: boolean; }",
desc: "imageFile may be a TFile or a string that contains a hyperlink.\n" +
"imageFile may also be an obsidian filepath including a reference eg.: 'path/my.pdf#page=3'\n" +
"Set scale to false if you want to embed the image at 100% of its original size. Default is true which will insert a scaled image.\n" +
"anchor will only be evaluated if scale is false. anchor true will add |100% to the end of the filename, resulting in an image that will always pop back to 100% when the source file is updated or when the Excalidraw file is reopened.\n" +
"colorMap is only used for SVG images and nested Excalidraw images. See the Shade Master script and the Deconstruct Selected Elements script for examples using colorMap.\n" +
"type ColorMap = { [color: string]: string; }",
after: "",
},
{
+30 -200
View File
@@ -13,7 +13,7 @@ import {
FRONTMATTER_KEYS,
getCSSFontDefinition,
} from "../constants/constants";
import { createSVG, normalizeColorMap } from "src/utils/excalidrawAutomateUtils";
import { createSVG } from "src/utils/excalidrawAutomateUtils";
import { ExcalidrawData, getTransclusion } from "./ExcalidrawData";
import { t } from "../lang/helpers";
import { tex2dataURL } from "./LaTeX";
@@ -54,6 +54,8 @@ import { ExportSettings } from "src/types/exportUtilTypes";
//and getObsidianImage is aborted if the file is already in the Watchdog stack
const markdownRendererRecursionWatcthdog = new Set<TFile>();
/**
* Function takes an SVG and replaces all fill and stroke colors with the ones in the colorMap
* @param svg: SVGSVGElement
@@ -61,17 +63,13 @@ const markdownRendererRecursionWatcthdog = new Set<TFile>();
* @returns svg with colors replaced
*/
const replaceSVGColors = (svg: SVGSVGElement | string, colorMap: ColorMap | null): SVGSVGElement | string => {
const normalizedColorMap = normalizeColorMap(colorMap);
if(!normalizedColorMap) {
if(!colorMap) {
return svg;
}
if(typeof svg === 'string') {
// Replace colors in the SVG string
for (const [oldColor, newColor] of Object.entries(normalizedColorMap)) {
if(typeof newColor !== "string" || oldColor === "invertInDarkMode") {
continue;
}
for (const [oldColor, newColor] of Object.entries(colorMap)) {
if(oldColor === "stroke" || oldColor === "fill") {
const [svgTag, prefix, suffix] = (svg.match(/(<svg[^>]*)(>)/i) || []) as string[];
if (!svgTag) continue;
@@ -104,11 +102,11 @@ const replaceSVGColors = (svg: SVGSVGElement | string, colorMap: ColorMap | null
const oldFill = node.getAttribute('fill')?.toLocaleLowerCase();
const oldStroke = node.getAttribute('stroke')?.toLocaleLowerCase();
if (oldFill && typeof normalizedColorMap[oldFill] === "string") {
node.setAttribute('fill', normalizedColorMap[oldFill] as string);
if (oldFill && colorMap[oldFill]) {
node.setAttribute('fill', colorMap[oldFill]);
}
if (oldStroke && typeof normalizedColorMap[oldStroke] === "string") {
node.setAttribute('stroke', normalizedColorMap[oldStroke] as string);
if (oldStroke && colorMap[oldStroke]) {
node.setAttribute('stroke', colorMap[oldStroke]);
}
}
for(const child of node.childNodes) {
@@ -116,8 +114,8 @@ const replaceSVGColors = (svg: SVGSVGElement | string, colorMap: ColorMap | null
}
}
if(typeof normalizedColorMap.fill === "string") svg.setAttribute("fill", normalizedColorMap.fill);
if(typeof normalizedColorMap.stroke === "string") svg.setAttribute("stroke", normalizedColorMap.stroke);
if("fill" in colorMap) svg.setAttribute("fill", colorMap.fill);
if("stroke" in colorMap) svg.setAttribute("stroke", colorMap.stroke);
for (const child of svg.childNodes) {
childNodes(child);
}
@@ -125,63 +123,6 @@ const replaceSVGColors = (svg: SVGSVGElement | string, colorMap: ColorMap | null
return svg;
}
const getInvertPreference = (colorMap: ColorMap | null | undefined, fallback: boolean): boolean =>
typeof colorMap?.invertInDarkMode === "boolean" ? colorMap.invertInDarkMode : fallback;
const applyThemeFilterToBitmapDataURL = async (
dataURL: DataURL,
mimeType: MimeType,
themeFilter: string,
): Promise<DataURL> =>
new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
try {
const canvas = createEl("canvas");
const ctx = canvas.getContext("2d");
if(!ctx) {
reject(new Error("Canvas 2D context unavailable"));
return;
}
canvas.width = img.naturalWidth || img.width;
canvas.height = img.naturalHeight || img.height;
ctx.filter = themeFilter || THEME_FILTER;
ctx.drawImage(img, 0, 0);
resolve(canvas.toDataURL(mimeType) as DataURL);
} catch (e) {
reject(e);
}
};
img.onerror = (e) => reject(e);
img.src = dataURL;
});
const applyThemeFilterToSVGDataURL = (
dataURL: DataURL,
themeFilter: string,
): DataURL => {
const prefix = "data:image/svg+xml;base64,";
if (!dataURL || !dataURL.startsWith(prefix)) {
return dataURL;
}
try {
const svgText = atob(dataURL.substring(prefix.length));
const parser = new DOMParser();
const doc = parser.parseFromString(svgText, "image/svg+xml");
const root = doc.documentElement;
if (!(root instanceof SVGSVGElement)) {
return dataURL;
}
const svg = root as SVGSVGElement;
svg.setAttribute("filter", themeFilter || THEME_FILTER);
const serialized = new XMLSerializer().serializeToString(doc);
return svgToBase64(serialized) as DataURL;
} catch (e) {
return dataURL;
}
};
export class EmbeddedFile {
public file: TFile = null;
public isSVGwithBitmap: boolean = false;
@@ -204,10 +145,9 @@ export class EmbeddedFile {
constructor(plugin: ExcalidrawPlugin, hostPath: string, imgPath: string, colorMapJSON?: string) {
this.plugin = plugin;
this.resetImage(hostPath, imgPath);
if(this.file) { // && (this.plugin.isExcalidrawFile(this.file) || this.file.extension.toLowerCase() === "svg")) {
if(this.file && (this.plugin.isExcalidrawFile(this.file) || this.file.extension.toLowerCase() === "svg")) {
try {
const parsedColorMap = colorMapJSON ? JSON.parse(colorMapJSON) : null;
this.colorMap = normalizeColorMap(parsedColorMap);
this.colorMap = colorMapJSON ? JSON.parse(colorMapJSON.toLocaleLowerCase()) : null;
} catch (error) {
this.colorMap = null;
}
@@ -215,17 +155,7 @@ export class EmbeddedFile {
}
get hasSeparateDarkAndLightVersion(): boolean {
const isPDF = this.file && this.file.extension.toLowerCase() === "pdf";
const mime = this.mimeType?.toLowerCase?.();
const isBitmap = mime?.startsWith("image/") && mime !== "image/svg+xml";
const invertBitmapPref = getInvertPreference(this.colorMap, !!this.plugin?.settings?.invertBitmapforDarkMode);
const invertSVGPref = getInvertPreference(this.colorMap, !!this.plugin?.settings?.invertSVGforDarkMode);
const isSVG = mime === "image/svg+xml";
const needsBitmapOrPDFInversion = isPDF || (invertBitmapPref && isBitmap);
const needsSVGInversion = invertSVGPref && isSVG;
return needsBitmapOrPDFInversion || needsSVGInversion || this.isSVGwithBitmap;
return this.isSVGwithBitmap;
}
public resetImage(hostPath: string, imgPath: string) {
@@ -379,11 +309,7 @@ export class EmbeddedFilesLoader {
this.pdfDocsMap.clear();
}
public async getObsidianImage(
inFile: TFile | EmbeddedFile,
depth: number,
isDark?: boolean,
): Promise<{
public async getObsidianImage(inFile: TFile | EmbeddedFile, depth: number): Promise<{
mimeType: MimeType;
fileId: FileId;
dataURL: DataURL;
@@ -392,10 +318,7 @@ export class EmbeddedFilesLoader {
size: { height: number; width: number };
pdfPageViewProps?: PDFPageViewProps;
}> {
if (typeof isDark === "boolean") {
this.isDark = isDark;
}
const result = await this._getObsidianImage(inFile, depth, isDark);
const result = await this._getObsidianImage(inFile, depth);
this.emptyPDFDocsMap();
return result;
}
@@ -429,10 +352,7 @@ export class EmbeddedFilesLoader {
skipInliningFonts: false,
};
const colorMap = inFile instanceof EmbeddedFile ? inFile.colorMap : null;
const invertBitmapInDarkMode = getInvertPreference(colorMap, this.plugin.settings.invertBitmapforDarkMode);
const invertSVGInDarkMode = getInvertPreference(colorMap, this.plugin.settings.invertSVGforDarkMode);
const hasColorMap = Boolean(colorMap);
const hasColorMap = Boolean(inFile instanceof EmbeddedFile ? inFile.colorMap : null);
const shouldUseCache = !hasColorMap && this.plugin.settings.allowImageCacheInScene && file && imageCache.isReady();
const hasFilenameParts = Boolean((inFile instanceof EmbeddedFile) && inFile.filenameparts);
const filenameParts = hasFilenameParts ? (inFile as EmbeddedFile).filenameparts : null;
@@ -489,7 +409,7 @@ export class EmbeddedFilesLoader {
depth+1,
getExportPadding(this.plugin, file),
),
colorMap
inFile instanceof EmbeddedFile ? inFile.colorMap : null
) as SVGSVGElement;
//https://stackoverflow.com/questions/51154171/remove-css-filter-on-child-elements
@@ -500,21 +420,14 @@ export class EmbeddedFilesLoader {
hasSVGwithBitmap = true;
}
if (isDark && invertSVGInDarkMode) {
svg.setAttribute("filter", this.plugin.settings.themeFilter);
}
if (isDark && hasSVGwithBitmap && !Boolean(maybeSVG) && (
(!invertBitmapInDarkMode && invertSVGInDarkMode) ||
(invertBitmapInDarkMode && !invertSVGInDarkMode)
)) {
if (hasSVGwithBitmap && isDark && !Boolean(maybeSVG)) {
imageList.forEach((i) => {
const id = i.parentElement?.id;
svg.querySelectorAll(`use[href='#${id}']`).forEach((u) => {
u.setAttribute("filter", this.plugin.settings.themeFilter);
u.setAttribute("filter", THEME_FILTER);
});
});
}
if (!hasSVGwithBitmap && svg.getAttribute("hasbitmap")) {
hasSVGwithBitmap = true;
}
@@ -545,34 +458,16 @@ export class EmbeddedFilesLoader {
return localPath;
}
private async _getObsidianImage(
inFile: TFile | EmbeddedFile,
depth: number,
isDark?: boolean,
): Promise<ImgData> {
private async _getObsidianImage(inFile: TFile | EmbeddedFile, depth: number): Promise<ImgData> {
if (!this.plugin || !inFile) {
return null;
}
const app = this.plugin.app;
const effectiveIsDark =
typeof isDark === "boolean"
? isDark
: typeof this.isDark === "boolean"
? this.isDark
: undefined;
if (typeof effectiveIsDark === "boolean") {
this.isDark = effectiveIsDark;
}
const isHyperLink = inFile instanceof EmbeddedFile ? inFile.isHyperLink : false;
const isLocalLink = inFile instanceof EmbeddedFile ? inFile.isLocalLink : false;
const hyperlink = inFile instanceof EmbeddedFile ? inFile.hyperlink : "";
const normalizedColorMap = inFile instanceof EmbeddedFile ? normalizeColorMap(inFile.colorMap) : null;
if (inFile instanceof EmbeddedFile) {
inFile.colorMap = normalizedColorMap;
}
const file: TFile = inFile instanceof EmbeddedFile ? inFile.file : inFile;
if(file && markdownRendererRecursionWatcthdog.has(file)) {
new Notice(`Loading of ${file.path}. Please check if there is an inifinite loop of one file embedded in the other.`);
@@ -597,11 +492,6 @@ export class EmbeddedFilesLoader {
let hasSVGwithBitmap = false;
const isExcalidrawFile = !isHyperLink && !isLocalLink && this.plugin.isExcalidrawFile(file);
const isPDF = !isHyperLink && !isLocalLink && file.extension.toLowerCase() === "pdf";
const invertBitmapInDarkMode = getInvertPreference(
normalizedColorMap,
isPDF || this.plugin.settings.invertBitmapforDarkMode,
);
const invertSVGInDarkMode = getInvertPreference(normalizedColorMap, this.plugin.settings.invertSVGforDarkMode);
if (
!isHyperLink && !isPDF && !isLocalLink &&
@@ -622,7 +512,7 @@ export class EmbeddedFilesLoader {
let dURL: DataURL = null;
if (isExcalidrawFile) {
const res = await this.getExcalidrawSVG({
isDark: effectiveIsDark ?? this.isDark,
isDark: this.isDark,
file,
depth,
inFile,
@@ -658,7 +548,7 @@ export class EmbeddedFilesLoader {
)
: excalidrawSVG ?? pdfDataURL ??
(file?.extension === "svg"
? await getSVGData(app, file, normalizedColorMap)
? await getSVGData(app, file, inFile instanceof EmbeddedFile ? inFile.colorMap : null)
: file?.extension === "md"
? null
: await getDataURL(ab, mimeType));
@@ -670,36 +560,6 @@ export class EmbeddedFilesLoader {
dataURL = result.dataURL;
hasSVGwithBitmap = result.hasSVGwithBitmap;
}
if (
(effectiveIsDark ?? this.isDark) &&
invertSVGInDarkMode &&
dataURL &&
mimeType === "image/svg+xml"
) {
dataURL = applyThemeFilterToSVGDataURL(
dataURL,
this.plugin.settings.themeFilter,
);
}
if (
(effectiveIsDark ?? this.isDark) &&
invertBitmapInDarkMode &&
dataURL &&
mimeType?.startsWith("image/") &&
mimeType !== "image/svg+xml"
) {
try {
dataURL = await applyThemeFilterToBitmapDataURL(
dataURL,
mimeType,
this.plugin.settings.themeFilter,
);
} catch (error) {
errorlog({ where: "EmbeddedFileLoader._getObsidianImage", error });
}
}
try{
const size = isPDF ? pdfSize : await getImageSize(dataURL);
return {
@@ -739,9 +599,7 @@ export class EmbeddedFilesLoader {
}
const entries = excalidrawData.getFileEntries();
//debug({where:"EmbeddedFileLoader.loadSceneFiles",uid:this.uid,isDark:this.isDark,sceneTheme:excalidrawData.scene.appState.theme});
if (isThemeChange) {
this.isDark = excalidrawData?.scene?.appState?.theme === "dark";
} else if (this.isDark === undefined) {
if (this.isDark === undefined) {
this.isDark = excalidrawData?.scene?.appState?.theme === "dark";
}
let entry: IteratorResult<[FileId, EmbeddedFile]>;
@@ -801,19 +659,9 @@ export class EmbeddedFilesLoader {
if (this.terminate) {
return;
}
const invertPreference = getInvertPreference(equation?.colorMap, this.plugin.settings.invertSVGforDarkMode);
const shouldReloadForTheme = isThemeChange && invertPreference;
if (!excalidrawData.getEquation(id).isLoaded || shouldReloadForTheme) {
if (!excalidrawData.getEquation(id).isLoaded) {
const latex = equation.latex;
const data = await tex2dataURL(
latex,
4,
this.plugin,
{
applyThemeFilter: this.isDark && this.plugin.settings.invertSVGforDarkMode,
themeFilter: this.plugin.settings.themeFilter,
},
);
const data = await tex2dataURL(latex, 4, this.plugin);
if (data) {
const fileData = {
mimeType: data.mimeType,
@@ -1209,7 +1057,7 @@ export class EmbeddedFilesLoader {
const ef = new EmbeddedFile(plugin,file.path,src);
//const f = app.metadataCache.getFirstLinkpathDest(src.split("#")[0],file.path);
if(!ef.file) continue;
const embeddedFile = await this._getObsidianImage(ef,1,this.isDark);
const embeddedFile = await this._getObsidianImage(ef,1);
const img = createEl("img");
if(width) img.setAttribute("width", width);
if(height) img.setAttribute("height", height);
@@ -1284,11 +1132,7 @@ export class EmbeddedFilesLoader {
if (imageList.length > 0) {
hasSVGwithBitmap = true;
}
if (this.isDark && hasSVGwithBitmap && (
(!this.plugin.settings.invertBitmapforDarkMode && this.plugin.settings.invertSVGforDarkMode) ||
(this.plugin.settings.invertBitmapforDarkMode && !this.plugin.settings.invertSVGforDarkMode)
)) {
if (hasSVGwithBitmap && this.isDark) {
imageList.forEach(img => {
if(img instanceof HTMLImageElement) {
img.style.filter = THEME_FILTER;
@@ -1296,29 +1140,15 @@ export class EmbeddedFilesLoader {
});
}
/*if (hasSVGwithBitmap && this.isDark) {
imageList.forEach(img => {
if(img instanceof HTMLImageElement) {
img.style.filter = THEME_FILTER;
}
});
}*/
const xml = new XMLSerializer().serializeToString(mdDIV);
const finalSVG = svg(xml, '<div class="excalidraw-md-footer"></div>', style);
plugin.ea.mostRecentMarkdownSVG = parser.parseFromString(
finalSVG,
"image/svg+xml",
).firstElementChild as SVGSVGElement;
if (this.isDark && this.plugin.settings.invertSVGforDarkMode) {
plugin.ea.mostRecentMarkdownSVG.setAttribute("filter", this.plugin.settings.themeFilter);
}
return {
//dataURL: svgToBase64(finalSVG) as DataURL,
dataURL: svgToBase64(plugin.ea.mostRecentMarkdownSVG.outerHTML) as DataURL,
hasSVGwithBitmap: hasSVGwithBitmap || !!mdDIV.querySelector(".excalidraw-svg"),
dataURL: svgToBase64(finalSVG) as DataURL,
hasSVGwithBitmap
};
};
}
+51 -51
View File
@@ -32,7 +32,6 @@ import {
DEVICE,
mermaidToExcalidraw,
refreshTextDimensions,
getDefaultColorPalette,
getFontFamilyString,
} from "src/constants/constants";
import { blobToBase64, checkAndCreateFolder, getDrawingFilename, getExcalidrawEmbeddedFilesFiletree, getListOfTemplateFiles, getNewUniqueFilepath, splitFolderAndFilename } from "src/utils/fileUtils";
@@ -85,7 +84,7 @@ import { log } from "../utils/debugHelper";
import { ExcalidrawLib } from "../types/excalidrawLib";
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/src/types";
import { AddImageOptions, ImageInfo, KeyBlocker, ScriptSettingValue, SVGColorInfo } from "src/types/excalidrawAutomateTypes";
import { _measureText, cloneElement, createPNG, createSVG, ensureActiveScriptSettingsObject, errorMessage, filterColorMap, getEmbeddedFileForImageElment, getLastActiveExcalidrawView, getLineBox, getTemplate, isColorStringTransparent, isSVGColorInfo, mergeColorMapIntoSVGColorInfo, normalizeBindMode, normalizeColorMap, normalizeFixedPoint, normalizeLinePoints, repositionElementsToCursor, svgColorInfoToColorMap, updateOrAddSVGColorInfo, verifyMinimumPluginVersion } from "src/utils/excalidrawAutomateUtils";
import { _measureText, cloneElement, createPNG, createSVG, ensureActiveScriptSettingsObject, errorMessage, filterColorMap, getEmbeddedFileForImageElment, getLastActiveExcalidrawView, getLineBox, getTemplate, isColorStringTransparent, isSVGColorInfo, mergeColorMapIntoSVGColorInfo, normalizeBindMode, normalizeFixedPoint, normalizeLinePoints, repositionElementsToCursor, svgColorInfoToColorMap, updateOrAddSVGColorInfo, verifyMinimumPluginVersion } from "src/utils/excalidrawAutomateUtils";
import { exportToPDF, getMarginValue, getPageDimensions } from "src/utils/exportUtils";
import { PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFPageProperties, ExportSettings} from "src/types/exportUtilTypes";
import { FrameRenderingOptions } from "src/types/utilTypes";
@@ -98,6 +97,7 @@ import { patchMobileView } from "src/utils/customEmbeddableUtils";
import { ObsidianCanvasNode } from "src/view/managers/CanvasNodeFactory";
import { AIRequest } from "src/types/AIUtilTypes";
import { getAspectRatio } from "src/utils/YoutTubeUtils";
import { getPDFCropRect } from "src/utils/PDFUtils";
extendPlugins([
HarmonyPlugin,
@@ -708,9 +708,6 @@ export class ExcalidrawAutomate {
*/
public getAPI(view?:ExcalidrawView):ExcalidrawAutomate {
const ea = new ExcalidrawAutomate(this.plugin, view);
if(view && view.excalidrawAPI) {
ea.canvas.theme = view.excalidrawAPI.getAppState().theme;
}
this.plugin.eaInstances.push(ea);
return ea;
}
@@ -2179,7 +2176,7 @@ export class ExcalidrawAutomate {
anchor: boolean = true, //only has effect if scale is false. If anchor is true the image path will include |100%, if false the image will be inserted at 100%, but if resized by the user it won't pop back to 100% the next time Excalidraw is opened.
): Promise<string> {
let colorMap: ColorMap | null = null;
let colorMap: ColorMap;
let topX: number;
if(typeof topXOrOpts === "number") {
topX = topXOrOpts;
@@ -2189,43 +2186,49 @@ export class ExcalidrawAutomate {
imageFile = topXOrOpts.imageFile;
scale = topXOrOpts.scale ?? true;
anchor = topXOrOpts.anchor ?? true;
colorMap = normalizeColorMap(topXOrOpts.colorMap);
colorMap = topXOrOpts.colorMap;
}
const pdfLinkRegex = /^[^#]*#page=\d*(&\w*=[^&]+){0,}&rect=\d*,\d*,\d*,\d*/;
const originalLink = typeof imageFile === "string" ? imageFile : null;
const imageFileForLoader = originalLink && pdfLinkRegex.test(originalLink)
? originalLink.split("&rect=")[0]
: imageFile;
const id = nanoid();
const loader = new EmbeddedFilesLoader(
this.plugin,
this.canvas.theme === "dark",
);
const image = (typeof imageFile === "string")
? await loader.getObsidianImage(new EmbeddedFile(this.plugin, "", imageFile),0, this.canvas.theme === "dark")
: await loader.getObsidianImage(imageFile,0, this.canvas.theme === "dark");
const image = (typeof imageFileForLoader === "string")
? await loader.getObsidianImage(new EmbeddedFile(this.plugin, "", imageFileForLoader),0)
: await loader.getObsidianImage(imageFileForLoader,0);
if (!image) {
return null;
}
const fileId = typeof imageFile === "string"
const fileId = typeof imageFileForLoader === "string"
? image.fileId
: imageFile.extension === "md" || imageFile.extension.toLowerCase() === "pdf" ? fileid() as FileId : image.fileId;
: imageFileForLoader.extension === "md" || imageFileForLoader.extension.toLowerCase() === "pdf" ? fileid() as FileId : image.fileId;
this.imagesDict[fileId] = {
mimeType: image.mimeType,
id: fileId,
dataURL: image.dataURL,
created: image.created,
isHyperLink: typeof imageFile === "string",
hyperlink: typeof imageFile === "string"
? imageFile
isHyperLink: typeof imageFileForLoader === "string",
hyperlink: typeof imageFileForLoader === "string"
? imageFileForLoader
: null,
file: typeof imageFile === "string"
file: typeof imageFileForLoader === "string"
? null
: imageFile.path + (scale || !anchor ? "":"|100%"),
: imageFileForLoader.path + (scale || !anchor ? "":"|100%"),
hasSVGwithBitmap: image.hasSVGwithBitmap,
latex: null,
size: { //must have the natural size here (e.g. for PDF cropping)
height: image.size.height,
width: image.size.width,
},
colorMap: colorMap ?? undefined,
colorMap,
pdfPageViewProps: image.pdfPageViewProps,
};
if (scale && (Math.max(image.size.width, image.size.height) > MAX_IMAGE_SIZE)) {
@@ -2246,6 +2249,22 @@ export class ExcalidrawAutomate {
newEl.fileId = fileId;
newEl.scale = [1, 1];
newEl.crop = null;
if(originalLink && pdfLinkRegex.test(originalLink)) {
const fd = this.imagesDict[fileId];
newEl.crop = getPDFCropRect({
scale: this.plugin.settings.pdfScale,
link: originalLink,
naturalHeight: fd.size.height,
naturalWidth: fd.size.width,
pdfPageViewProps: fd.pdfPageViewProps,
});
addAppendUpdateCustomData(newEl, {pdfPageViewProps: fd.pdfPageViewProps});
if(newEl.crop) {
newEl.width = newEl.crop.width/this.plugin.settings.pdfScale;
newEl.height = newEl.crop.height/this.plugin.settings.pdfScale;
}
newEl.link = `[[${originalLink}]]`;
}
if(!scale && anchor) {
newEl.customData = {isAnchored: true}
};
@@ -2257,24 +2276,16 @@ export class ExcalidrawAutomate {
* @param {number} topX - The x-coordinate of the top-left corner.
* @param {number} topY - The y-coordinate of the top-left corner.
* @param {string} tex - The LaTeX equation string.
* @param {number} [scaleX=1] - The x-scaling factor (post mathjax creation)
* @param {number} [scaleY=1] - The y-scaling factor (post mathjax creation)
* @returns {Promise<string>} Promise resolving to the ID of the added LaTeX image element.
*/
async addLaTex(topX: number, topY: number, tex: string): Promise<string> {
if (!tex){
async addLaTex(topX: number, topY: number, tex: string, scaleX: number = 1, scaleY: number = 1): Promise<string> {
if (!tex || !scaleX || !scaleY){
return null;
}
const currentTheme = this.targetView?.excalidrawAPI?.getAppState().theme ?? this.canvas.theme;
const applyFilter = currentTheme === "dark" && this.plugin.settings.invertSVGforDarkMode;
const id = nanoid();
const image = await tex2dataURL(
tex,
4,
this.plugin,
{
applyThemeFilter: applyFilter,
themeFilter: this.plugin.settings.themeFilter,
},
);
const image = await tex2dataURL(tex, 4, this.plugin);
if (!image) {
return null;
}
@@ -2292,12 +2303,12 @@ export class ExcalidrawAutomate {
"image",
topX,
topY,
image.size.width,
image.size.height,
image.size.width * Math.abs(scaleX),
image.size.height * Math.abs(scaleY),
);
this.elementsDict[id].fileId = image.fileId;
this.addAppendUpdateCustomData(id, {latex: tex});
this.elementsDict[id].scale = [1, 1];
this.elementsDict[id].scale = [Math.sign(scaleX), Math.sign(scaleY)];
return id;
};
@@ -2309,8 +2320,7 @@ export class ExcalidrawAutomate {
*/
async tex2dataURL(
tex: string,
scale: number = 4, // Default scale value, adjust as needed
options?: { applyThemeFilter?: boolean; themeFilter?: string },
scale: number = 4 // Default scale value, adjust as needed
): Promise<{
mimeType: MimeType;
fileId: FileId;
@@ -2318,12 +2328,7 @@ export class ExcalidrawAutomate {
created: number;
size: { height: number; width: number };
}> {
const currentTheme = this.targetView?.excalidrawAPI?.getAppState().theme ?? this.canvas.theme;
const themeOptions = options ?? {
applyThemeFilter: currentTheme === "dark" && this.plugin.settings.invertSVGforDarkMode,
themeFilter: this.plugin.settings.themeFilter,
};
return await tex2dataURL(tex, scale, this.plugin, themeOptions);
return await tex2dataURL(tex,scale, this.plugin);
};
/**
@@ -2595,9 +2600,6 @@ export class ExcalidrawAutomate {
this.targetView.leaf,
);
}
if (this.targetView && this.targetView.excalidrawAPI) {
this.canvas.theme = this.targetView.excalidrawAPI.getAppState().theme;
}
return this.targetView;
};
@@ -2706,11 +2708,10 @@ export class ExcalidrawAutomate {
*/
getColorMapForImageElement(el: ExcalidrawElement): ColorMap {
const cm = getEmbeddedFileForImageElment(this,el)?.colorMap
const normalized = normalizeColorMap(cm);
if(!normalized) {
if(!cm) {
return {};
}
return normalized;
return cm;
}
/**
@@ -2748,9 +2749,7 @@ export class ExcalidrawAutomate {
errorMessage("Must provide an image element and a colorMap as input", "updateViewSVGImageColorMap()");
continue;
}
const hasColorEntries = Object.keys(colorMap).some(key => key.toLocaleLowerCase() !== "invertindarkmode");
const hasInvertPreference = typeof (colorMap as Record<string, unknown>).invertInDarkMode === "boolean";
if (!colorMap || typeof colorMap !== 'object' || (!hasColorEntries && !hasInvertPreference)) {
if (!colorMap || typeof colorMap !== 'object' || Object.keys(colorMap).length === 0) {
ef.colorMap = null;
} else {
ef.colorMap = colorMap;
@@ -3817,6 +3816,7 @@ export class ExcalidrawAutomate {
/**
* Moves the specified element to a specific position in the z-index.
* * Operates directly on the Excalidraw Scene in targetView, not through ExcalidrawAutomate elements.
* @param {number} elementId - The ID of the element to move.
* @param {number} newZIndex - The new z-index position for the element.
*/
+2 -30
View File
@@ -38,7 +38,6 @@ import {
arrayToMap,
compressAsync,
} from "../utils/utils";
import { ColorMap } from "../types/embeddedFileLoaderTypes";
import { cleanBlockRef, cleanSectionHeading, getAttachmentsFolderAndFilePath, isObsidianThemeDark } from "../utils/obsidianUtils";
import {
ExcalidrawElement,
@@ -147,31 +146,6 @@ export const REGEX_LINK = {
},
};
const COLOR_MAP_INVERT_KEY = "invertindarkmode";
const isReservedColorMapKey = (key: string) => key.toLocaleLowerCase() === COLOR_MAP_INVERT_KEY;
const normalizeColorMapLocal = (colorMap?: ColorMap | null): ColorMap | null => {
if (!colorMap || typeof colorMap !== "object") {
return null;
}
const normalized: ColorMap = {};
const invert = (colorMap as Record<string, unknown>).invertInDarkMode ?? (colorMap as Record<string, unknown>)[COLOR_MAP_INVERT_KEY];
if (typeof invert === "boolean") {
normalized.invertInDarkMode = invert;
}
for (const [key, value] of Object.entries(colorMap)) {
if (isReservedColorMapKey(key) || typeof value !== "string") {
continue;
}
const normalizedKey = key.toLocaleLowerCase();
const normalizedValue = value.toLocaleLowerCase();
normalized[normalizedKey] = normalizedValue;
}
return normalized;
};
//added \n at and of DRAWING_REG: https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/357
const DRAWING_REG = /\n##? Drawing\n[^`]*(```json\n)([\s\S]*?)```\n/gm; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/182
const DRAWING_REG_FALLBACK = /\n##? Drawing\n(```json\n)?(.*)(```)?(%%)?/gm;
@@ -1523,8 +1497,7 @@ export class ExcalidrawData {
const path = ef.file
? ef.linkParts.original.replace(PATHREG,this.app.metadataCache.fileToLinktext(ef.file,this.file.path))
: ef.linkParts.original;
const normalizedColorMap = normalizeColorMapLocal(ef.colorMap);
const colorMap = normalizedColorMap ? " " + JSON.stringify(normalizedColorMap) : "";
const colorMap = ef.colorMap ? " " + JSON.stringify(ef.colorMap) : "";
outString += `${key}: [[${path}]]${colorMap}\n\n`;
}
}
@@ -2041,7 +2014,6 @@ export class ExcalidrawData {
}
const parts = data.linkParts.original.split("#");
const normalizedColorMap = normalizeColorMapLocal(data.colorMap);
this.plugin.filesMaster.set(fileId, {
isHyperLink: false,
isLocalLink: false,
@@ -2050,7 +2022,7 @@ export class ExcalidrawData {
? null
: parts[1],
hasSVGwithBitmap: data.isSVGwithBitmap,
colorMapJSON: normalizedColorMap ? JSON.stringify(normalizedColorMap) : null,
colorMapJSON: data.colorMap ? JSON.stringify(data.colorMap) : null,
});
}
+1 -2
View File
@@ -53,7 +53,6 @@ export async function tex2dataURL(
tex: string,
scale: number = 4,
plugin: ExcalidrawPlugin,
options?: { applyThemeFilter?: boolean; themeFilter?: string },
): Promise<{
mimeType: MimeType;
fileId: FileId;
@@ -62,7 +61,7 @@ export async function tex2dataURL(
size: { height: number; width: number };
}> {
await loadMathJax();
return tex2dataURLExternal(tex, scale, plugin, options);
return tex2dataURLExternal(tex, scale, plugin);
}
export const clearMathJaxVariables = () => {
+1 -2
View File
@@ -48,6 +48,5 @@ export type Size = {
};
export interface ColorMap {
invertInDarkMode?: boolean;
[color: string]: string | boolean | undefined;
[color: string]: string;
};
+29 -56
View File
@@ -1,5 +1,5 @@
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import { BinaryFileData, DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import ExcalidrawPlugin from "src/core/main";
import {
ExcalidrawElement,
@@ -59,48 +59,15 @@ export function isSVGColorInfo(obj: ColorMap | SVGColorInfo): boolean {
);
}
const COLOR_MAP_INVERT_KEY = "invertindarkmode";
const isReservedColorMapKey = (key: string) => key.toLocaleLowerCase() === COLOR_MAP_INVERT_KEY;
//Normalize color maps and lift the invertInDarkMode flag out of color entries
export function normalizeColorMap(colorMap?: ColorMap | null): ColorMap | null {
if (!colorMap || typeof colorMap !== "object") {
return null;
}
const normalized: ColorMap = {};
const invert = (colorMap as Record<string, unknown>).invertInDarkMode ?? (colorMap as Record<string, unknown>)[COLOR_MAP_INVERT_KEY];
if (typeof invert === "boolean") {
normalized.invertInDarkMode = invert;
}
for (const [key, value] of Object.entries(colorMap)) {
if (isReservedColorMapKey(key) || typeof value !== "string") {
continue;
}
const normalizedKey = key.toLocaleLowerCase();
const normalizedValue = value.toLocaleLowerCase();
normalized[normalizedKey] = normalizedValue;
}
return normalized;
}
export function mergeColorMapIntoSVGColorInfo(
colorMap: ColorMap,
svgColorInfo: SVGColorInfo
): SVGColorInfo {
const normalized = normalizeColorMap(colorMap);
if(normalized) {
for(const key of Object.keys(normalized)) {
if(isReservedColorMapKey(key)) {
continue;
if(colorMap) {
for(const key of Object.keys(colorMap)) {
if(svgColorInfo.has(key)) {
svgColorInfo.get(key).mappedTo = colorMap[key];
}
const mappedTo = normalized[key];
if(!svgColorInfo.has(key) || typeof mappedTo !== "string") {
continue;
}
svgColorInfo.get(key).mappedTo = mappedTo;
}
}
return svgColorInfo;
@@ -117,23 +84,9 @@ export function svgColorInfoToColorMap(svgColorInfo: SVGColorInfo): ColorMap {
//Remove identical key-value pairs from a ColorMap
export function filterColorMap(colorMap: ColorMap): ColorMap {
const normalized = normalizeColorMap(colorMap) ?? {};
const filtered: ColorMap = {};
if (typeof normalized.invertInDarkMode === "boolean") {
filtered.invertInDarkMode = normalized.invertInDarkMode;
}
Object.entries(normalized).forEach(([key, value]) => {
if (isReservedColorMapKey(key) || typeof value !== "string") {
return;
}
if (key.toLocaleLowerCase() !== value.toLocaleLowerCase()) {
filtered[key] = value;
}
});
return filtered;
return Object.fromEntries(
Object.entries(colorMap).filter(([key, value]) => key.toLocaleLowerCase() !== value?.toLocaleLowerCase())
);
}
export function updateOrAddSVGColorInfo(
@@ -441,6 +394,7 @@ export async function createPNG(
depth: number,
padding?: number,
imagesDict?: any,
overrideFiles?: Record<ExcalidrawElement["id"], BinaryFileData>,
): Promise<Blob> {
if (!loader) {
loader = new EmbeddedFilesLoader(plugin);
@@ -482,6 +436,7 @@ export async function createPNG(
},
padding,
scale,
overrideFiles,
);
}
@@ -557,6 +512,7 @@ export async function createSVG(
imagesDict?: any,
convertMarkdownLinksToObsidianURLs: boolean = false,
includeInternalLinks: boolean = true,
overrideFiles?: Record<ExcalidrawElement["id"], BinaryFileData>,
): Promise<SVGSVGElement> {
if (!loader) {
loader = new EmbeddedFilesLoader(plugin);
@@ -607,6 +563,7 @@ export async function createSVG(
},
padding,
null,
overrideFiles,
);
if (withTheme && theme === "dark") addFilterToForeignObjects(svg);
@@ -714,8 +671,24 @@ export const insertLaTeXToView = (view: ExcalidrawView, center: boolean = false)
3
)
).then(async (formula: string) => {
const lastLatexEl = ea.getViewElements()
.filter((el) => el.type === "image" && view.excalidrawData.hasEquation(el.fileId))
.reduce(
(maxel, curr) => (!maxel || curr.updated > maxel.updated) ? curr : maxel,
undefined
) as ExcalidrawImageElement;
let scaleX = 1;
let scaleY = 1;
if (lastLatexEl) {
const equation = view.excalidrawData.getEquation(lastLatexEl.fileId);
const dataurl = await ea.tex2dataURL(equation.latex);
if (dataurl.size.width > 0 && dataurl.size.height > 0) {
scaleX = lastLatexEl.width/dataurl.size.width;
scaleY = lastLatexEl.height/dataurl.size.height;
}
}
if (formula) {
const id = await ea.addLaTex(0, 0, formula);
const id = await ea.addLaTex(0, 0, formula, scaleX, scaleY);
if(center) {
const el = ea.getElement(id);
let {width, height} = el;
+16 -1
View File
@@ -305,7 +305,22 @@ export const arrayBufferToBase64 = (arrayBuffer: ArrayBuffer): string => {
export const getPDFDoc = async (f: TFile): Promise<any> => {
if(typeof window.pdfjsLib === "undefined") await loadPdfJs();
return await window.pdfjsLib.getDocument(EXCALIDRAW_PLUGIN.app.vault.getResourcePath(f)).promise;
const pdfjs = window.pdfjsLib;
const url = EXCALIDRAW_PLUGIN.app.vault.getResourcePath(f);
const workerSrc = pdfjs.GlobalWorkerOptions.workerSrc as string;
const workerDir = workerSrc?.replace(/pdf\.worker(\.min)?\.m?js$/, "");
const wasmUrl = workerDir ? `${workerDir}wasm/` : undefined;
return await pdfjs.getDocument({
url,
wasmUrl,
cMapUrl: "/lib/pdfjs/cmaps/",
cMapPacked: true,
standardFontDataUrl: "/lib/pdfjs/standard_fonts/",
iccUrl: "/lib/pdfjs/iccs/",
}).promise;
}
export const readLocalFile = async (filePath:string): Promise<string> => {
+12 -4
View File
@@ -343,6 +343,7 @@ export async function getSVG (
exportSettings: ExportSettings,
padding: number,
srcFile: TFile|null, //if set, will replace markdown links with obsidian links
overrideFiles?: Record<ExcalidrawElement["id"], BinaryFileData>,
): Promise<SVGSVGElement> {
let elements:ExcalidrawElement[] = scene.elements;
if(elements.some(el => el.type === "embeddable")) {
@@ -359,10 +360,13 @@ export async function getSVG (
})
: elements;
const baseFiles = scene.files ?? {};
const files = overrideFiles ? { ...baseFiles, ...overrideFiles } : baseFiles;
try {
let svg: SVGSVGElement;
if(exportSettings.isMask) {
const cropObject = new CropImage(elements, scene.files);
const cropObject = new CropImage(elements, files);
svg = await cropObject.getCroppedSVG();
cropObject.destroy();
} else {
@@ -378,7 +382,7 @@ export async function getSVG (
? {frameRendering: exportSettings.frameRendering}
: {},
},
files: scene.files,
files,
exportPadding: exportSettings.frameRendering?.enabled ? 0 : padding,
exportingFrame: null,
renderEmbeddables: true,
@@ -415,10 +419,14 @@ export async function getPNG (
exportSettings: ExportSettings,
padding: number,
scale: number = 1,
overrideFiles?: Record<ExcalidrawElement["id"], BinaryFileData>,
): Promise<Blob> {
try {
const baseFiles = scene.files ?? {};
const files = overrideFiles ? { ...baseFiles, ...overrideFiles } : baseFiles;
if(exportSettings.isMask) {
const cropObject = new CropImage(scene.elements, scene.files);
const cropObject = new CropImage(scene.elements, files);
const blob = await cropObject.getCroppedPNG();
cropObject.destroy();
return blob;
@@ -436,7 +444,7 @@ export async function getPNG (
? {frameRendering: exportSettings.frameRendering}
: {},
},
files: filterFiles(scene.files),
files: filterFiles(files),
exportPadding: exportSettings.frameRendering?.enabled ? 0 : padding,
mimeType: "image/png",
getDimensions: (width: number, height: number) => ({
+136 -5
View File
@@ -50,7 +50,6 @@ import {
obsidianToExcalidrawMap,
MAX_IMAGE_SIZE,
fileid,
sceneCoordsToViewportCoords,
MD_EX_SECTIONS,
refreshTextDimensions,
getContainerElement,
@@ -67,7 +66,8 @@ import {
getFrameElementsMatchingQuery,
getElementsWithLinkMatchingQuery,
getImagesMatchingQuery,
getBoundTextElementId
getBoundTextElementId,
getEmbeddedFileForImageElment
} from "../utils/excalidrawAutomateUtils";
import { t } from "../lang/helpers";
import {
@@ -152,7 +152,6 @@ import { Packages } from "../types/types";
import React from "react";
import { diagramToHTML } from "../utils/matic";
import { IS_WORKER_SUPPORTED } from "../shared/Workers/compression-worker";
import { getPDFCropRect } from "../utils/PDFUtils";
import { AutoexportConfig, Position, ViewSemaphores } from "../types/excalidrawViewTypes";
import { DropManager } from "./managers/DropManager";
import { ImageInfo } from "src/types/excalidrawAutomateTypes";
@@ -164,6 +163,7 @@ import { FileData } from "src/types/embeddedFileLoaderTypes";
import { UIMode } from "src/shared/Dialogs/UIModeSettingComponent";
import { UIModeSettings } from "src/shared/Dialogs/UIModeSettings";
import { copyLinkToSelectedElementToClipboard } from "src/shared/Dialogs/copyLinkToSelectedElement";
import { getPDFCropRect } from "src/utils/PDFUtils";
const EMBEDDABLE_SEMAPHORE_TIMEOUT = 2000;
const PREVENT_RELOAD_TIMEOUT = 2000;
@@ -535,6 +535,43 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
const ed = this.exportDialog;
return ed ? ed.exportInternalLinks : getExportInternalLinks(this.plugin, this.file)
}
private async loadFilesForExport(exportTheme: string): Promise<Record<FileId, BinaryFileData> | null> {
const api = this.excalidrawAPI as ExcalidrawImperativeAPI;
if (!api || !this.excalidrawData) {
return null;
}
const viewTheme = api.getAppState().theme;
if (!exportTheme || exportTheme === viewTheme) {
return null;
}
const loader = new EmbeddedFilesLoader(this.plugin, exportTheme === "dark");
const collected: Record<FileId, BinaryFileData> = {};
let resolved = false;
await new Promise<void>((resolve) => {
loader.loadSceneFiles({
excalidrawData: this.excalidrawData,
addFiles: (files: FileData[], _isDark: boolean, final: boolean = true) => {
if (files && files.length > 0) {
files.forEach((f) => {
collected[f.id] = { ...f } as BinaryFileData;
});
}
if (final && !resolved) {
resolved = true;
resolve();
}
},
depth: 0,
isThemeChange: true,
});
});
return Object.keys(collected).length ? collected : null;
}
public async svg(scene: any, theme?:string, embedScene?: boolean, embedFont: boolean = false): Promise<SVGSVGElement> {
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.svg, "ExcalidrawView.svg", scene, theme, embedScene);
@@ -546,13 +583,16 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
skipInliningFonts: !embedFont,
};
const exportTheme = this.getViewExportTheme(theme);
const overrideFiles = await this.loadFilesForExport(exportTheme);
return await getSVG(
{
...scene,
...{
appState: {
...scene.appState,
theme: this.getViewExportTheme(theme),
theme: exportTheme,
exportEmbedScene: this.getViewExportEmbedScene(embedScene),
},
},
@@ -560,6 +600,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
exportSettings,
this.getViewExportPadding(),
this.file,
overrideFiles ?? undefined,
);
}
@@ -681,13 +722,16 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
isMask: isMaskFile(this.plugin, this.file),
};
const exportTheme = this.getViewExportTheme(theme);
const overrideFiles = await this.loadFilesForExport(exportTheme);
return await getPNG(
{
...scene,
...{
appState: {
...scene.appState,
theme: this.getViewExportTheme(theme),
theme: exportTheme,
exportEmbedScene: this.getViewExportEmbedScene(embedScene),
},
},
@@ -695,6 +739,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
exportSettings,
this.getViewExportPadding(),
this.getViewExportScale(),
overrideFiles ?? undefined,
);
}
@@ -5147,6 +5192,92 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
]);
}
const selectedImages = this.getViewSelectedElements().filter(el => el.type === "image") as ExcalidrawImageElement[];
if(selectedImages.length > 0) {
type ImageType = "svg" | "pdf" | "bitmap" | "excalidraw";
const getImageType = (embeddedFile: EmbeddedFile | null | undefined): ImageType | null => {
if(!embeddedFile) return null;
if(embeddedFile.file && this.plugin.isExcalidrawFile(embeddedFile.file)) return "excalidraw";
if(embeddedFile.file?.extension?.toLowerCase?.() === "pdf" || !!embeddedFile.pdfPageViewProps) return "pdf";
if(embeddedFile.mimeType === "image/svg+xml") return "svg";
return "bitmap";
};
const getInvertInDarkMode = (
imageEl: ExcalidrawImageElement,
embeddedFile: EmbeddedFile,
imageType: ImageType,
): boolean => {
const invertBitmap = imageEl.customData?.invertBitmapInDarkmode;
if(imageType === "svg" || imageType === "excalidraw") {
return imageEl.customData?.doNotInvertSVGInDarkMode ? false : true;
}
if(imageType === "pdf") {
return typeof invertBitmap === "boolean" ? invertBitmap : true;
}
return typeof invertBitmap === "boolean" ? invertBitmap : false;
};
const imageMenuState = (() => {
const ea = getEA(this) as ExcalidrawAutomate;
try {
const imagesWithStatus = selectedImages
.map(el => {
const embeddedFile = getEmbeddedFileForImageElment(ea, el);
const imageType = getImageType(embeddedFile);
if(!embeddedFile || !imageType) return null;
return {
el,
imageType,
invertInDarkMode: getInvertInDarkMode(el, embeddedFile, imageType),
};
})
.filter(Boolean) as { el: ExcalidrawImageElement; imageType: ImageType; invertInDarkMode: boolean; }[];
if(imagesWithStatus.length === 0) return null;
const reference = imagesWithStatus[0].invertInDarkMode;
if(!imagesWithStatus.every(img => img.invertInDarkMode === reference)) return null;
return { imagesWithStatus, invertInDarkMode: reference };
} finally {
ea.destroy();
}
})();
if(imageMenuState) {
const { imagesWithStatus, invertInDarkMode } = imageMenuState;
const newInvertState = !invertInDarkMode;
contextMenuActions.push([
renderContextMenuAction(
React,
newInvertState ? t("INVERT_IMAGES_IN_DARK_MODE") : t("DO_NOT_INVERT_IMAGES_IN_DARK_MODE"),
async () => {
const ea = getEA(this) as ExcalidrawAutomate;
ea.copyViewElementsToEAforEditing(imagesWithStatus.map(img => img.el));
imagesWithStatus.forEach(img => {
const editableEl = ea.getElement(img.el.id) as Mutable<ExcalidrawImageElement>;
const embeddedFile = getEmbeddedFileForImageElment(ea, editableEl);
const imageType = getImageType(embeddedFile) ?? img.imageType;
if(imageType === "svg" || imageType === "excalidraw") {
addAppendUpdateCustomData(editableEl, {
doNotInvertSVGInDarkMode: newInvertState ? undefined : true,
invertBitmapInDarkmode: undefined,
});
} else {
addAppendUpdateCustomData(editableEl, {
invertBitmapInDarkmode: newInvertState,
doNotInvertSVGInDarkMode: undefined,
});
}
});
await ea.addElementsToView(false);
ea.destroy();
},
onClose
),
]);
}
}
if(areElementsSelected) {
contextMenuActions.push([
renderContextMenuAction(