Compare commits

...
12 changed files with 536 additions and 208 deletions

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.25.0-beta.1",
"version": "2.25.0-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",
+4 -4
View File
@@ -13,7 +13,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.109",
"@zsviczian/excalidraw": "0.18.110",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -5232,9 +5232,9 @@
"license": "MIT"
},
"node_modules/@zsviczian/excalidraw": {
"version": "0.18.109",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.109.tgz",
"integrity": "sha512-E1lWFfI8QSnVjFZFiuVpoI6swhestPqbWni2uZnqEGy8Ypq8U7YyYet6wvEOm84xLeGExNel6Ff60UiMIyYevw==",
"version": "0.18.110",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.110.tgz",
"integrity": "sha512-R/5aZ/6Sbk3O/TI0O28kA/KzyeXC61NDXFVjIi5857Lmx2Gvf1Xva3APKoqsnBwiR2aNjB92qBE86AiUyvxmhA==",
"license": "MIT",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
+1 -1
View File
@@ -29,7 +29,7 @@
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.109",
"@zsviczian/excalidraw": "0.18.110",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
+1 -1
View File
@@ -412,7 +412,7 @@ export const FRONTMATTER_KEYS = {
type: "checkbox",
depricated: false,
},
};
} as const;
export const CaptureUpdateAction = {
/**
+278 -122
View File
@@ -29,6 +29,7 @@ import {
getParentOfClass,
isObsidianThemeDark,
getFileCSSClasses,
getSafeFrontmatter,
} from "../../utils/obsidianUtils";
import { linkClickModifierType } from "../../utils/modifierkeyHelper";
import { ImageKey, getImageCache } from "../../shared/ImageCache";
@@ -44,6 +45,7 @@ import {
import { ExportSettings } from "src/types/exportUtilTypes";
import { setElementDisplay } from "src/utils/htmlUtils";
import { setStyle } from "src/utils/styleUtils";
import { getGlobalTaskQueue } from "src/shared/GlobalTaskQueue";
interface imgElementAttributes {
file?: TFile;
@@ -77,6 +79,26 @@ const getDefaultHeight = (plugin: ExcalidrawPlugin): string => {
return plugin.settings.height;
};
/**
* Utility to aggressively halt background image decoding and free Blob memory
* when an element is discarded without being attached to the DOM.
*/
const discardImage = (el: Element | null) => {
if (!el) {
return;
}
const images = isInstanceOfHTMLImageElement(el)
? [el]
: Array.from(el.querySelectorAll("img"));
images.forEach((img) => {
if (img.src.startsWith("blob:")) {
URL.revokeObjectURL(img.src);
}
// Instantly aborts the browser's background V8 image decoder task
img.src = "";
});
};
export const initializeMarkdownPostProcessor = (p: ExcalidrawPlugin) => {
plugin = p;
app = plugin.app;
@@ -429,6 +451,7 @@ const _getSVGNative = async ({
const getIMG = async (
imgAttributes: imgElementAttributes,
onCanvas: boolean = false,
embedEl?: Node,
): Promise<HTMLImageElement | HTMLDivElement> => {
let file = imgAttributes.file;
if (!imgAttributes.file) {
@@ -473,66 +496,92 @@ const getIMG = async (
theme ? theme === "dark" : undefined,
);
let terminationTimer: number;
if (embedEl) {
terminationTimer = window.setInterval(() => {
if (!embedEl.isConnected) {
loader.terminate = true;
window.clearInterval(terminationTimer);
}
}, 500);
}
const cacheReady = getImageCache().isReady();
await plugin.awaitInit();
switch (plugin.settings.previewImageType) {
case PreviewImageType.PNG: {
const img = createEl("img");
setImgStyle({
element: img,
imgAttributes,
onCanvas,
isNativeSVG: false,
});
return await _getPNG({
imgAttributes,
filenameParts,
theme,
cacheReady,
img,
file,
exportSettings,
loader,
});
let resultElement: HTMLImageElement | HTMLDivElement = null;
try {
await plugin.awaitInit();
switch (plugin.settings.previewImageType) {
case PreviewImageType.PNG: {
const img = createEl("img");
setImgStyle({
element: img,
imgAttributes,
onCanvas,
isNativeSVG: false,
});
resultElement = await _getPNG({
imgAttributes,
filenameParts,
theme,
cacheReady,
img,
file,
exportSettings,
loader,
});
break;
}
case PreviewImageType.SVGIMG: {
const img = createEl("img");
setImgStyle({
element: img,
imgAttributes,
onCanvas,
isNativeSVG: false,
});
resultElement = await _getSVGIMG({
filenameParts,
theme,
cacheReady,
img,
file,
exportSettings,
loader,
});
break;
}
case PreviewImageType.SVG: {
const img = createEl("div");
setImgStyle({
element: img,
imgAttributes,
onCanvas,
isNativeSVG: true,
});
resultElement = await _getSVGNative({
filenameParts,
theme,
cacheReady,
containerElement: img,
file,
exportSettings,
loader,
width: imgAttributes.fwidth
? !imgAttributes.fwidth.endsWith("%")
? parseInt(imgAttributes.fwidth)
: 6000
: undefined,
});
break;
}
}
case PreviewImageType.SVGIMG: {
const img = createEl("img");
setImgStyle({
element: img,
imgAttributes,
onCanvas,
isNativeSVG: false,
});
return await _getSVGIMG({
filenameParts,
theme,
cacheReady,
img,
file,
exportSettings,
loader,
});
}
case PreviewImageType.SVG: {
const img = createEl("div");
setImgStyle({ element: img, imgAttributes, onCanvas, isNativeSVG: true });
return await _getSVGNative({
filenameParts,
theme,
cacheReady,
containerElement: img,
file,
exportSettings,
loader,
width: imgAttributes.fwidth
? !imgAttributes.fwidth.endsWith("%")
? parseInt(imgAttributes.fwidth)
: 6000
: undefined,
});
} finally {
if (terminationTimer) {
window.clearInterval(terminationTimer);
}
}
return resultElement;
};
const addSVGToImgSrc = (
@@ -564,8 +613,9 @@ const addSVGToImgSrc = (
const createImgElement = async (
attr: imgElementAttributes,
onCanvas: boolean = false,
embedEl?: Element,
): Promise<HTMLElement> => {
const imgOrDiv = await getIMG(attr, onCanvas);
const imgOrDiv = await getIMG(attr, onCanvas, embedEl);
if (!imgOrDiv) {
return null;
}
@@ -685,8 +735,11 @@ const createImgElement = async (
eventElement.addEventListener("dblclick", clickEvent);
eventElement.addEventListener(RERENDER_EVENT, (e) => {
e.stopPropagation();
void (async () => {
void getGlobalTaskQueue(plugin).addTask(async () => {
const parent = imgOrDiv.parentElement;
if (!parent || !parent.isConnected) {
return;
}
const imgMaxWidth = imgOrDiv.style.maxWidth;
const imgMaxHeigth = imgOrDiv.style.maxHeight;
const fileSource = imgOrDiv.getAttribute("fileSource");
@@ -699,10 +752,17 @@ const createImgElement = async (
imgstyle: [...Array.from(imgOrDiv.classList)],
},
onCanvas,
parent,
);
if (!newImg) {
return;
}
if (!parent.isConnected) {
discardImage(newImg);
return;
}
parent.empty();
if (!onCanvas) {
setStyle(newImg, {
@@ -712,7 +772,7 @@ const createImgElement = async (
}
newImg.setAttribute("fileSource", fileSource);
parent.append(newImg);
})();
});
});
const cssClasses = getFileCSSClasses(attr.file);
cssClasses.forEach((cssClass) => {
@@ -734,8 +794,12 @@ const createImgElement = async (
const createImageDiv = async (
attr: imgElementAttributes,
onCanvas: boolean = false,
embedEl?: Element,
): Promise<HTMLDivElement> => {
const img = await createImgElement(attr, onCanvas);
const img = await createImgElement(attr, onCanvas, embedEl);
if (!img) {
return null;
}
return createDiv(attr.imgstyle.join(" "), (el) => el.append(img));
};
@@ -749,7 +813,14 @@ const processReadingMode = async (
//Iterating all the containers in the file to check which one is an excalidraw drawing
//This is a for loop instead of embeddedItems.forEach() because processInternalEmbed at the end
//is awaited, otherwise excalidraw images would not display in the Kanban plugin
const promises: Promise<void>[] = [];
for (const maybeDrawing of embeddedItems) {
// If the node is detached from the DOM, the user has closed the note or navigated away.
if (!maybeDrawing.isConnected) {
break;
}
//check to see if the file in the src attribute exists
const fname = maybeDrawing.getAttribute("src")?.split("#")[0];
if (!fname) {
@@ -767,12 +838,31 @@ const processReadingMode = async (
continue;
}
maybeDrawing.parentElement.replaceChild(
await processInternalEmbed(maybeDrawing, file),
maybeDrawing,
promises.push(
getGlobalTaskQueue(plugin).addTask(async () => {
if (!maybeDrawing.isConnected) {
return;
}
const imgDiv = await processInternalEmbed(maybeDrawing, file);
if (!imgDiv) {
return;
}
// Ensure we don't attempt to append onto a detached DOM tree
if (!maybeDrawing.isConnected) {
discardImage(imgDiv);
return;
}
maybeDrawing.parentElement.replaceChild(imgDiv, maybeDrawing);
}),
);
}
}
// Await the completion of all generated jobs allowing concurrent processing via the Global Task Queue
await Promise.all(promises);
};
const processInternalEmbed = async (
@@ -788,7 +878,7 @@ const processInternalEmbed = async (
const src = internalEmbedEl.getAttribute("src");
if (!src) {
return;
return null;
}
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1059
@@ -813,7 +903,7 @@ const processInternalEmbed = async (
? fnameParts.linkpartReference
: "");
attr.file = file;
return await createImageDiv(attr);
return await createImageDiv(attr, false, internalEmbedEl);
};
function getDimensionsFromAliasString(data: string) {
@@ -970,7 +1060,8 @@ const tmpObsidianWYSIWYG = async (
if (!plugin.isExcalidrawFile(file)) {
return;
}
if (ctx.frontmatter?.["excalidraw-embed-md"]) {
const safeFrontmatter = getSafeFrontmatter(ctx.frontmatter);
if (safeFrontmatter["excalidraw-open-md"]) {
return;
}
if (ctx.remainingNestLevel < 4) {
@@ -1020,7 +1111,8 @@ const tmpObsidianWYSIWYG = async (
if (!plugin.settings.renderImageInHoverPreviewForMDNotes) {
//const isHoverPopover = internalEmbedDiv.parentElement?.hasClass("hover-popover");
const shouldOpenMD = Boolean(ctx.frontmatter?.["excalidraw-open-md"]);
const safeFrontmatter = getSafeFrontmatter(ctx.frontmatter);
const shouldOpenMD = Boolean(safeFrontmatter["excalidraw-open-md"]);
if (isHoverPopover && shouldOpenMD) {
return;
}
@@ -1084,46 +1176,63 @@ const tmpObsidianWYSIWYG = async (
}
internalEmbedDiv.empty();
const onCanvas = internalEmbedDiv.hasClass("canvas-node-content");
const imgDiv = await createImageDiv(attr, onCanvas);
if (markdownEmbed) {
//display image on canvas without markdown frame
internalEmbedDiv.removeClass("markdown-embed");
internalEmbedDiv.removeClass("inline-embed");
internalEmbedDiv.addClass("media-embed");
internalEmbedDiv.addClass("image-embed");
if (
!onCanvas &&
(isInstanceOfHTMLElement(imgDiv.firstChild) ||
isInstanceOfSVGElement(imgDiv.firstChild))
) {
setStyle(imgDiv.firstChild, {
maxHeight: "100%",
maxWidth: null,
});
await getGlobalTaskQueue(plugin).addTask(async () => {
if (!internalEmbedDiv.isConnected) {
return;
}
// Resolve the cyclic size dependency by applying a CSS width and/or height
if (
!onCanvas &&
isHoverPopover &&
isInstanceOfHTMLImageElement(imgDiv.firstChild)
) {
internalEmbedDiv.style.setProperty(
"--popover-width",
`${attr.fwidth}px`,
);
internalEmbedDiv.style.setProperty(
"--popover-height",
`${attr.fheight}px`,
);
setStyle(internalEmbedDiv, {
width: "var(--popover-width)",
height: "var(--popover-height)",
});
const imgDiv = await createImageDiv(attr, onCanvas, internalEmbedDiv);
if (!imgDiv) {
return;
}
internalEmbedDiv.appendChild(imgDiv.firstChild);
return;
}
internalEmbedDiv.appendChild(imgDiv);
// Check if the user navigated away while the image was generating
if (!internalEmbedDiv.isConnected) {
discardImage(imgDiv);
return;
}
if (markdownEmbed) {
//display image on canvas without markdown frame
internalEmbedDiv.removeClass("markdown-embed");
internalEmbedDiv.removeClass("inline-embed");
internalEmbedDiv.addClass("media-embed");
internalEmbedDiv.addClass("image-embed");
if (
!onCanvas &&
(isInstanceOfHTMLElement(imgDiv.firstChild) ||
isInstanceOfSVGElement(imgDiv.firstChild))
) {
setStyle(imgDiv.firstChild, {
maxHeight: "100%",
maxWidth: null,
});
}
// Resolve the cyclic size dependency by applying a CSS width and/or height
if (
!onCanvas &&
isHoverPopover &&
isInstanceOfHTMLImageElement(imgDiv.firstChild)
) {
internalEmbedDiv.style.setProperty(
"--popover-width",
`${attr.fwidth}px`,
);
internalEmbedDiv.style.setProperty(
"--popover-height",
`${attr.fheight}px`,
);
setStyle(internalEmbedDiv, {
width: "var(--popover-width)",
height: "var(--popover-height)",
});
}
internalEmbedDiv.appendChild(imgDiv.firstChild);
return;
}
internalEmbedDiv.appendChild(imgDiv);
});
return;
}
@@ -1141,8 +1250,25 @@ const tmpObsidianWYSIWYG = async (
internalEmbedDiv.setAttribute("ready", "");
internalEmbedDiv.empty();
const imgDiv = await processInternalEmbed(internalEmbedDiv, file);
internalEmbedDiv.appendChild(imgDiv);
await getGlobalTaskQueue(plugin).addTask(async () => {
if (!internalEmbedDiv.isConnected) {
return;
}
const imgDiv = await processInternalEmbed(internalEmbedDiv, file);
if (!imgDiv) {
return;
}
// Abort insertion if the container is no longer connected
if (!internalEmbedDiv.isConnected) {
discardImage(imgDiv);
return;
}
internalEmbedDiv.appendChild(imgDiv);
});
//timer to avoid the image flickering when the user is typing
let timer: number = null;
@@ -1156,10 +1282,23 @@ const tmpObsidianWYSIWYG = async (
timer = window.setTimeout(() => {
timer = null;
internalEmbedDiv.empty();
void (async () => {
void getGlobalTaskQueue(plugin).addTask(async () => {
if (!internalEmbedDiv.isConnected) {
observer.disconnect();
return;
}
const imgDiv = await processInternalEmbed(internalEmbedDiv, file);
internalEmbedDiv.appendChild(imgDiv);
})();
if (!imgDiv) {
return;
}
if (internalEmbedDiv.isConnected) {
internalEmbedDiv.appendChild(imgDiv);
} else {
discardImage(imgDiv);
}
});
}, 500);
};
const observer = DEBUGGING
@@ -1211,9 +1350,10 @@ export const markdownPostProcessor = async (
const isHoverPopover = Boolean(
containerEl && getParentOfClass(containerEl, "hover-popover"),
);
const safeFrontmatter = getSafeFrontmatter(ctx.frontmatter);
const isPreview =
isHoverPopover &&
Boolean(ctx?.frontmatter?.["excalidraw-open-md"]) &&
Boolean(safeFrontmatter["excalidraw-open-md"]) &&
!plugin.settings.renderImageInHoverPreviewForMDNotes;
const embeddedItems = el.querySelectorAll(".internal-embed");
@@ -1255,9 +1395,7 @@ export const markdownPostProcessor = async (
//then I want to hide all embedded items as these will be
//transcluded text element or some other transcluded content inside the Excalidraw file
//in reading mode these elements should be hidden
const excalidrawFile = Boolean(
ctx.frontmatter && "excalidraw-plugin" in ctx.frontmatter,
);
const excalidrawFile = Boolean(safeFrontmatter["excalidraw-plugin"]);
if (!(isPreview || isMarkdownReadingMode || isPrinting) && excalidrawFile) {
setElementDisplay(el, "none");
return;
@@ -1338,14 +1476,32 @@ const legacyExcalidrawPopoverObserverFn: MutationCallback = (m) => {
//this div will be on top of original DIV. By stopping the propagation of the click
//I prevent the default Obsidian feature of opening the link in the native app
void (async () => {
const img = await getIMG({
file,
fname: file.path,
fwidth: "300",
fheight: null,
imgstyle: ["excalidraw-svg"],
});
void getGlobalTaskQueue(plugin).addTask(async () => {
if (!node.isConnected) {
return;
}
const img = await getIMG(
{
file,
fname: file.path,
fwidth: "300",
fheight: null,
imgstyle: ["excalidraw-svg"],
},
false,
node,
);
if (!img) {
return;
}
if (!node.isConnected) {
discardImage(img);
return;
}
const div = createDiv("", (el) => {
el.appendChild(img);
el.setAttribute("src", file.path);
@@ -1361,7 +1517,7 @@ const legacyExcalidrawPopoverObserverFn: MutationCallback = (m) => {
});
});
node.appendChild(div);
})();
});
};
export const legacyExcalidrawPopoverObserver = DEBUGGING
+1
View File
@@ -28,6 +28,7 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
## Fixed
- BUG: Double Click to edit from Obsidian in Live preview doesn't work anymore [#2813](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2813)
- Edge cases leading to memory leak and CPU overload when closing a markdown preview while embedded Excalidraw drawings are loading, or closing an ExcalidrawView, while nested images are still loading.
`,
"2.24.2": `
## Fixed
+145 -63
View File
@@ -18,7 +18,7 @@ import {
mainDocument,
} from "../constants/constants";
import { createSVG } from "src/utils/excalidrawAutomateUtils";
import { ExcalidrawData, getTransclusion } from "./ExcalidrawData";
import { EquationItem, ExcalidrawData, getTransclusion } from "./ExcalidrawData";
import { t } from "../lang/helpers";
import { tex2dataURL } from "./LaTeX";
import ExcalidrawPlugin from "../core/main";
@@ -214,15 +214,15 @@ export class EmbeddedFile {
this.file.extension.toLowerCase() === "svg")
) {
try {
this.colorMap = colorMapJSON
? JSON.parse(colorMapJSON.toLocaleLowerCase())
: null;
} catch (error) {
console.log(
`Error parsing colorMap for file ${imgPath}`,
this.constructor,
this.colorMap = (
colorMapJSON ? JSON.parse(colorMapJSON.toLocaleLowerCase()) : null
) as ColorMap | null;
} catch (error: unknown) {
errorlog({
message: `Error parsing colorMap for file ${imgPath}`,
context: this.constructor,
error,
);
});
this.colorMap = null;
}
}
@@ -429,7 +429,7 @@ export class EmbeddedFilesLoader {
this.pdfDocs.forEach((pdfDoc) => {
try {
pdfDoc.destroy();
} catch (e) {
} catch (e: unknown) {
errorlog({ where: "EmbeddedFileLoader.emptyPDFDocsMap", error: e });
}
});
@@ -479,6 +479,9 @@ export class EmbeddedFilesLoader {
hasSVGwithBitmap: boolean;
loadedFromCache?: boolean;
}> {
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
}
//debug({where:"EmbeddedFileLoader.getExcalidrawSVG",uid:this.uid,file:file.name});
const isMask = isMaskFile(this.plugin, file);
const forceTheme = hasExportTheme(this.plugin, file)
@@ -540,6 +543,10 @@ export class EmbeddedFilesLoader {
})
: undefined;
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
}
if (maybeSVG && cacheValidation === "stale-first") {
onStaleCacheHit?.();
}
@@ -582,6 +589,10 @@ export class EmbeddedFilesLoader {
inFile instanceof EmbeddedFile ? inFile.colorMap : null,
) as SVGSVGElement);
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
}
//https://stackoverflow.com/questions/51154171/remove-css-filter-on-child-elements
const imageList = svg.querySelectorAll(
"image:not([href^='data:image/svg'])",
@@ -726,6 +737,10 @@ export class EmbeddedFilesLoader {
)
: await app.vault.readBinary(file);
if (this.terminate) {
return null;
}
let dURL: DataURL = null;
let excalidrawLoadedFromCache = false;
if (isExcalidrawFile) {
@@ -738,6 +753,10 @@ export class EmbeddedFilesLoader {
cacheValidation: options?.cacheValidation,
onStaleCacheHit: options?.onStaleCacheHit,
});
if (this.terminate) {
return null;
}
dURL = res.dataURL;
hasSVGwithBitmap = res.hasSVGwithBitmap;
excalidrawLoadedFromCache = !!res.loadedFromCache;
@@ -755,6 +774,10 @@ export class EmbeddedFilesLoader {
? await this.pdfToDataURL(file, linkParts, options)
: [null, null, null, null, false];
if (this.terminate) {
return null;
}
let mimeType: MimeType = isPDF ? "image/png" : "image/svg+xml";
const extension =
@@ -781,6 +804,10 @@ export class EmbeddedFilesLoader {
? null
: await getDataURL(ab, mimeType)));
if (this.terminate) {
return null;
}
if (!isHyperLink && !dataURL && !isLocalLink) {
markdownRendererRecursionWatcthdog.add(file);
try {
@@ -797,6 +824,11 @@ export class EmbeddedFilesLoader {
}
const size = isPDF ? pdfSize : await getImageSize(dataURL);
if (this.terminate) {
return null;
}
return {
mimeType,
fileId: await generateIdFromFile(
@@ -817,7 +849,7 @@ export class EmbeddedFilesLoader {
pdfPageViewProps,
renderScale: pdfRenderScale,
};
} catch (error) {
} catch (error: unknown) {
errorlog({
where: "EmbeddedFileLoader._getObsidianImage",
uid: this.uid,
@@ -874,7 +906,7 @@ export class EmbeddedFilesLoader {
promiseTry(async () => {
try {
await task();
} catch (error) {
} catch (error: unknown) {
errorlog({
where: "EmbeddedFileLoader.loadSceneFiles",
uid: this.uid,
@@ -913,6 +945,10 @@ export class EmbeddedFilesLoader {
? () => deferredValidationFileIds.add(id)
: undefined,
});
if (this.terminate) {
return null;
}
if (data) {
const fileData: FileData = {
mimeType: data.mimeType,
@@ -959,11 +995,15 @@ export class EmbeddedFilesLoader {
let equationItem;
const equations = excalidrawData.getEquationEntries();
while (!(equationItem = equations.next()).done) {
if (fileIDWhiteList && !fileIDWhiteList.has(equationItem.value[0])) {
const eiValue = equationItem.value as [FileId, EquationItem];
if (
fileIDWhiteList &&
!fileIDWhiteList.has(eiValue[0])
) {
continue;
}
const equation = equationItem.value[1];
const id = equationItem.value[0];
const equation = eiValue[1];
const id = eiValue[0];
yield createSafeLoadTask(
async () => {
if (this.terminate) {
@@ -972,6 +1012,9 @@ export class EmbeddedFilesLoader {
if (!excalidrawData.getEquation(id).isLoaded) {
const latex = equation.latex;
const data = await tex2dataURL(latex, 4, this.plugin);
if (this.terminate) {
return null;
}
if (data) {
const fileData = {
mimeType: data.mimeType,
@@ -1008,7 +1051,7 @@ export class EmbeddedFilesLoader {
const result = await mermaidToExcalidraw(data, {
themeVariables: { fontSize: "20" },
});
if (!result) {
if (!result || this.terminate) {
return;
}
if (result?.files) {
@@ -1020,7 +1063,7 @@ export class EmbeddedFilesLoader {
hasSVGwithBitmap: false,
shouldScale: true,
size: await getImageSize(result.files[key].dataURL),
};
} as FileData;
files[batch].push(fileData);
}
return;
@@ -1038,6 +1081,9 @@ export class EmbeddedFilesLoader {
hasSVGwithBitmap: false,
elements: result.elements,
});
if (this.terminate) {
return;
}
if (res?.dataURL) {
const size = await getImageSize(res.dataURL);
const fileData: FileData = {
@@ -1328,6 +1374,9 @@ export class EmbeddedFilesLoader {
};
const canvas = await renderPage(pageNum);
if (this.terminate) {
return [null, null, null, null, false];
}
if (canvas) {
const blob = await new Promise<Blob>((resolve, reject) => {
canvas.toBlob((pngBlob) => {
@@ -1368,10 +1417,16 @@ export class EmbeddedFilesLoader {
file: TFile,
linkParts: LinkParts,
): Promise<{ dataURL: DataURL; hasSVGwithBitmap: boolean }> {
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
}
//1.
//get the markdown text
let hasSVGwithBitmap = false;
const transclusion = await getTransclusion(linkParts, plugin.app, file);
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
}
let text = (transclusion.leadingHashes ?? "") + transclusion.contents;
if (text === "") {
text =
@@ -1499,25 +1554,37 @@ export class EmbeddedFilesLoader {
const renderComponent = new Component();
renderComponent.load();
//await MarkdownRenderer.renderMarkdown(text, mdDIV, file.path, plugin);
await MarkdownRenderer.render(
this.plugin.app,
text,
mdDIV,
file.path,
renderComponent,
);
renderComponent.unload();
try {
//await MarkdownRenderer.renderMarkdown(text, mdDIV, file.path, plugin);
await MarkdownRenderer.render(
this.plugin.app,
text,
mdDIV,
file.path,
renderComponent,
);
} finally {
renderComponent.unload();
}
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
}
mdDIV
.querySelectorAll(":scope > *[class^='frontmatter']")
.forEach((el) => mdDIV.removeChild(el));
await replaceBlobWithBase64(mdDIV); //because image cache returns a blob
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
}
const internalEmbeds = Array.from(
mdDIV.querySelectorAll("span[class='internal-embed']"),
);
for (let i = 0; i < internalEmbeds.length; i++) {
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
}
const el = internalEmbeds[i];
const src = el.getAttribute("src");
if (!src) {
@@ -1531,6 +1598,9 @@ export class EmbeddedFilesLoader {
continue;
}
const embeddedFile = await this._getObsidianImage(ef, 1);
if (this.terminate) {
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
}
const img = createEl("img");
if (width) {
img.setAttribute("width", width);
@@ -1548,36 +1618,43 @@ export class EmbeddedFilesLoader {
//blank styles into inline styles using computedStyle
const iframeHost = mainDocument.body.createDiv();
hideElement(iframeHost);
const iframe = iframeHost.createEl("iframe");
const iframeDoc = iframe.contentWindow.document;
if (style) {
const styleEl = iframeDoc.createElement("style");
styleEl.type = "text/css";
setStyleText(styleEl, style);
iframeDoc.head.appendChild(styleEl);
}
const stylingDIV = iframeDoc.importNode(mdDIV, true);
iframeDoc.body.appendChild(stylingDIV);
const footerDIV = createDiv();
footerDIV.setAttribute("class", "excalidraw-md-footer");
iframeDoc.body.appendChild(footerDIV);
iframeDoc.body.querySelectorAll("*").forEach((el: HTMLElement) => {
const elementStyle = el.style;
const computedStyle = window.getComputedStyle(el);
let style = "";
for (const [prop] of Object.entries(elementStyle)) {
if (Object.hasOwn(elementStyle ?? {}, prop)) {
const value = computedStyle.getPropertyValue(prop);
style += `${prop}: ${value};`;
}
let xmlINiframe = "";
let xmlFooter = "";
try {
const iframe = iframeHost.createEl("iframe");
const iframeDoc = iframe.contentWindow.document;
if (style) {
const styleEl = iframeDoc.createElement("style");
styleEl.type = "text/css";
setStyleText(styleEl, style);
iframeDoc.head.appendChild(styleEl);
}
el.setAttribute("style", style);
});
const stylingDIV = iframeDoc.importNode(mdDIV, true);
iframeDoc.body.appendChild(stylingDIV);
const footerDIV = createDiv();
footerDIV.setAttribute("class", "excalidraw-md-footer");
iframeDoc.body.appendChild(footerDIV);
const xmlINiframe = new XMLSerializer().serializeToString(stylingDIV);
const xmlFooter = new XMLSerializer().serializeToString(footerDIV);
mainDocument.body.removeChild(iframeHost);
iframeDoc.body.querySelectorAll("*").forEach((el: HTMLElement) => {
const elementStyle = el.style;
const computedStyle = window.getComputedStyle(el);
let style = "";
for (const [prop] of Object.entries(elementStyle)) {
if (Object.hasOwn(elementStyle ?? {}, prop)) {
const value = computedStyle.getPropertyValue(prop);
style += `${prop}: ${value};`;
}
}
el.setAttribute("style", style);
});
xmlINiframe = new XMLSerializer().serializeToString(stylingDIV);
xmlFooter = new XMLSerializer().serializeToString(footerDIV);
} finally {
if (iframeHost.parentElement) {
mainDocument.body.removeChild(iframeHost);
}
}
//5.2
//get SVG size
@@ -1588,15 +1665,20 @@ export class EmbeddedFilesLoader {
);
const svgEl = doc.firstElementChild;
const host = createDiv();
host.appendChild(svgEl);
mainDocument.body.appendChild(host);
const footerHeight = svgEl.querySelector(
".excalidraw-md-footer",
).scrollHeight;
const height =
svgEl.querySelector(".excalidraw-md-host").scrollHeight + footerHeight;
const svgHeight = height <= linkParts.height ? height : linkParts.height;
mainDocument.body.removeChild(host);
let svgHeight = 0;
let footerHeight = 0;
try {
host.appendChild(svgEl);
mainDocument.body.appendChild(host);
footerHeight = svgEl.querySelector(".excalidraw-md-footer").scrollHeight;
const height =
svgEl.querySelector(".excalidraw-md-host").scrollHeight + footerHeight;
svgHeight = height <= linkParts.height ? height : linkParts.height;
} finally {
if (host.parentElement) {
mainDocument.body.removeChild(host);
}
}
//finalize SVG
svgStyle = ` width="${linkParts.width}px" height="${svgHeight}px"`;
+12 -6
View File
@@ -500,6 +500,9 @@ export const getExcalidrawMarkdownHeaderSection = (
: `${header}\n`;
};
export type EquationItem = { latex: string; isLoaded: boolean };
export type MermaidItem = { mermaid: string; isLoaded: boolean };
export class ExcalidrawData {
public textElements: Map<
string,
@@ -519,8 +522,8 @@ export class ExcalidrawData {
public loaded: boolean = false;
public elementLinks: Map<string, string> = null;
public files: Map<FileId, EmbeddedFile> = null; //fileId, path
private equations: Map<FileId, { latex: string; isLoaded: boolean }> = null; //fileId, path
private mermaids: Map<FileId, { mermaid: string; isLoaded: boolean }> = null; //fileId, path
private equations: Map<FileId, EquationItem> = null; //fileId, path
private mermaids: Map<FileId, MermaidItem> = null; //fileId, path
private compatibilityMode: boolean = false;
private textElementCommentedOut: boolean = false;
selectedElementIds: { [key: string]: boolean } = {}; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/609
@@ -531,8 +534,8 @@ export class ExcalidrawData {
) {
this.app = this.plugin.app;
this.files = new Map<FileId, EmbeddedFile>();
this.equations = new Map<FileId, { latex: string; isLoaded: boolean }>();
this.mermaids = new Map<FileId, { mermaid: string; isLoaded: boolean }>();
this.equations = new Map<FileId, EquationItem>();
this.mermaids = new Map<FileId, MermaidItem>();
}
public destroy() {
@@ -768,8 +771,11 @@ export class ExcalidrawData {
.forEach((textEl: Mutable<ExcalidrawTextElement>) => {
textEl.containerId = null;
}); // log({message:"cleanup",textEl})});
} catch (error) {
console.log(error);
} catch (error: unknown) {
errorlog({
message: "unexpected error in loadData",
error,
});
}
}
+50
View File
@@ -0,0 +1,50 @@
import ExcalidrawPlugin from "src/core/main";
export class GlobalTaskQueue {
private queue: {
task: () => Promise<void>;
resolve: (value: void | PromiseLike<void>) => void;
reject: (err: unknown) => void;
}[] = [];
private activeCount = 0;
constructor(private plugin: ExcalidrawPlugin) {}
public async addTask(task: () => Promise<void>): Promise<void> {
return new Promise((resolve, reject) => {
this.queue.push({ task, resolve, reject });
void this.processNext();
});
}
private async processNext() {
const concurrencyLimit = this.plugin?.settings?.renderingConcurrency ?? 4;
if (this.activeCount >= concurrencyLimit || this.queue.length === 0) {
return;
}
this.activeCount++;
const { task, resolve, reject } = this.queue.shift();
try {
await task();
resolve();
} catch (error) {
reject(error);
} finally {
this.activeCount--;
void this.processNext();
}
}
}
let globalTaskQueue: GlobalTaskQueue = null;
export const getGlobalTaskQueue = (
plugin: ExcalidrawPlugin,
): GlobalTaskQueue => {
if (!globalTaskQueue) {
globalTaskQueue = new GlobalTaskQueue(plugin);
}
return globalTaskQueue;
};
+35 -5
View File
@@ -18,6 +18,7 @@ import { linkClickModifierType, ModifierKeys } from "./modifierkeyHelper";
import {
DEVICE,
EXCALIDRAW_PLUGIN,
FRONTMATTER_KEYS,
mainDocument,
VIEW_TYPE_EXCALIDRAW,
} from "src/constants/constants";
@@ -321,7 +322,9 @@ export const getFileCSSClasses = (file: TFile): string[] => {
if (!fileCache?.frontmatter) {
return [];
}
const x = parseFrontMatterEntry(fileCache.frontmatter, "cssclasses");
const x = parseFrontMatterEntry(fileCache.frontmatter, "cssclasses") as
| string
| string[];
if (Array.isArray(x)) {
return x;
}
@@ -381,8 +384,8 @@ export function mergeMarkdownFiles(template: string, target: string): string {
.substring(4, templateFrontmatterEnd)
.trim();
const templateContent = template.substring(templateFrontmatterEnd + 3);
const templateFrontmatterObj: FrontMatterCache =
parse(templateFrontmatterRaw) || {};
const templateFrontmatterObj = (parse(templateFrontmatterRaw) ||
{}) as FrontMatterCache;
const hasTargetFM =
target.startsWith("---\n") && target.indexOf("---\n", 4) > 0;
@@ -393,8 +396,9 @@ export function mergeMarkdownFiles(template: string, target: string): string {
.replace(/\s+$/, ""); // keep as-is
const targetContent = target.substring(targetFrontmatterEnd + 3);
const targetFrontmatterObj: FrontMatterCache =
parse(targetFrontmatterRaw) || {};
const targetFrontmatterObj: FrontMatterCache = (parse(
targetFrontmatterRaw,
) || {}) as FrontMatterCache;
// 1. Merge array keys present in both (target has precedence for ordering)
const mergeArrayKeys = Object.keys(templateFrontmatterObj).filter(
@@ -662,3 +666,29 @@ export function strictArrayBuffer(
}
return buffer;
}
// 1. Map your custom 'type' strings to actual TypeScript types
type FrontmatterTypeMap = {
text: string;
checkbox: boolean;
number: number;
};
// 2. Automatically infer the shape of your valid frontmatter keys from the object
type FrontmatterValueType<T extends keyof typeof FRONTMATTER_KEYS> =
FrontmatterTypeMap[(typeof FRONTMATTER_KEYS)[T]["type"]];
// 3. Construct a fully typed Record where keys are the true names (e.g., "excalidraw-open-md")
export type ValidFrontmatter = {
[K in keyof typeof FRONTMATTER_KEYS as (typeof FRONTMATTER_KEYS)[K]["name"]]?: FrontmatterValueType<K>;
};
// 4. Create a reusable type guard function
export function getSafeFrontmatter(frontmatter: unknown): ValidFrontmatter {
if (typeof frontmatter !== "object" || frontmatter === null) {
return {};
}
// Cast safely inside the boundary helper function
return frontmatter;
}
+7 -2
View File
@@ -3240,11 +3240,16 @@ export default class ExcalidrawView
this.cancelDeferredSceneFileValidation();
if (this.activeLoader) {
this.activeLoader.terminate = true;
this.activeLoader.emptyPDFDocsMap();
this.activeLoader = null;
}
this.nextLoader = null;
if (this.nextLoader) {
this.nextLoader.terminate = true;
this.nextLoader.emptyPDFDocsMap();
this.nextLoader = null;
}
this.lastSceneLoadTime = 0;
api.resetScene();
(api.resetScene as () => void)();
this.previousSceneVersion = 0;
}
+1 -3
View File
@@ -682,9 +682,7 @@ function RenderObsidianView({
return () => {
mo.disconnect();
const iframe = containerRef.current?.querySelector(
"iframe.embed-iframe",
);
const iframe = containerRef.current?.querySelector("iframe.embed-iframe");
if (iframe && iframeLoadHandler) {
iframe.removeEventListener("load", iframeLoadHandler);
}