Skip to content

Commit

Permalink
2.6.2-beta-2, 0.17.6-10 PDFCropping
Browse files Browse the repository at this point in the history
  • Loading branch information
zsviczian committed Nov 1, 2024
1 parent 7233d1e commit dec2909
Show file tree
Hide file tree
Showing 14 changed files with 203 additions and 94 deletions.
2 changes: 1 addition & 1 deletion manifest-beta.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.6.3-beta-1",
"version": "2.6.3-beta-2",
"minAppVersion": "1.1.6",
"description": "An Obsidian plugin to edit and view Excalidraw drawings",
"author": "Zsolt Viczian",
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
"license": "MIT",
"dependencies": {
"@popperjs/core": "^2.11.8",
"@zsviczian/excalidraw": "0.17.6-9",
"@zsviczian/excalidraw": "0.17.6-10",
"chroma-js": "^2.4.2",
"clsx": "^2.0.0",
"@zsviczian/colormaster": "^1.2.2",
Expand Down
58 changes: 0 additions & 58 deletions src/EmbeddedFileLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1108,66 +1108,8 @@ export class EmbeddedFilesLoader {
const getSVGData = async (app: App, file: TFile, colorMap: ColorMap | null): Promise<DataURL> => {
const svgString = replaceSVGColors(await app.vault.read(file), colorMap) as string;
return svgToBase64(svgString) as DataURL;
/*
try {
const container = document.createElement('div');
container.innerHTML = svgString;
const svgElement = container.querySelector('svg');
if (!svgElement) {
throw new Error('Invalid SVG content'); // Ensure there's an SVG element
}
// Check for width and height attributes
const hasWidth = svgElement.hasAttribute('width');
const hasHeight = svgElement.hasAttribute('height');
// If width or height is missing, calculate based on viewBox
if (!hasWidth || !hasHeight) {
const viewBox = svgElement.getAttribute('viewBox');
if (viewBox) {
const [ , , viewBoxWidth, viewBoxHeight] = viewBox.split(/\s+/).map(Number);
// Set width and height based on viewBox if they are missing
if (!hasWidth) {
svgElement.setAttribute('width', `${viewBoxWidth}px`);
}
if (!hasHeight) {
svgElement.setAttribute('height', `${viewBoxHeight}px`);
}
}
}
// Get the updated SVG string from outerHTML
const updatedSVGString = svgElement.outerHTML;
// Convert the updated SVG string to a base64 Data URL
return svgToBase64(updatedSVGString) as DataURL;
} catch (error) {
errorlog({ where: "EmbeddedFileLoader.getSVGData", error });
return svgToBase64(svgString) as DataURL;
}*/
};

/*export const generateIdFromFile = async (file: ArrayBuffer): Promise<FileId> => {
let id: FileId;
try {
const hashBuffer = await window.crypto.subtle.digest("SHA-1", file);
id =
// convert buffer to byte array
Array.from(new Uint8Array(hashBuffer))
// convert to hex string
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("") as FileId;
} catch (error) {
errorlog({ where: "EmbeddedFileLoader.generateIdFromFile", error });
id = fileid() as FileId;
}
return id;
};*/

export const generateIdFromFile = async (file: ArrayBuffer, key?: string): Promise<FileId> => {
let id: FileId;
try {
Expand Down
4 changes: 4 additions & 0 deletions src/ExcalidrawAutomate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1547,6 +1547,10 @@ export class ExcalidrawAutomate {
: imageFile.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,
},
};
if (scale && (Math.max(image.size.width, image.size.height) > MAX_IMAGE_SIZE)) {
const scale =
Expand Down
21 changes: 21 additions & 0 deletions src/ExcalidrawData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import { updateElementIdsInScene } from "./utils/ExcalidrawSceneUtils";
import { getNewUniqueFilepath } from "./utils/FileUtils";
import { t } from "./lang/helpers";
import { displayFontMessage } from "./utils/ExcalidrawViewUtils";
import { getPDFRect } from "./utils/PDFUtils";

type SceneDataWithFiles = SceneData & { files: BinaryFiles };

Expand Down Expand Up @@ -1579,6 +1580,25 @@ export class ExcalidrawData {
return file;
}

private syncCroppedPDFs() {
let dirty = false;
const scene = this.scene as SceneDataWithFiles;
const pdfScale = this.plugin.settings.pdfScale;
scene.elements
.filter(el=>el.type === "image" && el.crop && !el.isDeleted)
.forEach((el: Mutable<ExcalidrawImageElement>)=>{
const ef = this.getFile(el.fileId);
if(ef.file.extension !== "pdf") return;
const pageRef = ef.linkParts.original.split("#")?.[1];
if(!pageRef || !pageRef.startsWith("page=") || pageRef.includes("rect")) return;
const restOfLink = el.link ? el.link.match(/&rect=\d*,\d*,\d*,\d*(.*)/)?.[1] : "";
const link = ef.linkParts.original + getPDFRect(el.crop, pdfScale) + (restOfLink ? restOfLink : "]]");
el.link = `[[${link}`;
this.elementLinks.set(el.id, el.link);
dirty = true;
});
}

/**
* deletes fileIds from Excalidraw data for files no longer in the scene
* @returns
Expand Down Expand Up @@ -1699,6 +1719,7 @@ export class ExcalidrawData {
this.updateElementLinksFromScene();
result =
result ||
this.syncCroppedPDFs() ||
this.setLinkPrefix() ||
this.setUrlPrefix() ||
this.setShowLinkBrackets() ||
Expand Down
37 changes: 36 additions & 1 deletion src/ExcalidrawView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ import { Packages } from "./types/types";
import React from "react";
import { diagramToHTML } from "./utils/matic";
import { IS_WORKER_SUPPORTED } from "./workers/compression-worker";
import { getPDFCropRect } from "./utils/PDFUtils";

const EMBEDDABLE_SEMAPHORE_TIMEOUT = 2000;
const PREVENT_RELOAD_TIMEOUT = 2000;
Expand Down Expand Up @@ -218,6 +219,27 @@ export const addFiles = async (
if (isDark === undefined) {
isDark = s.scene.appState.theme;
}
// update element.crop naturalWidth and naturalHeight in case scale of PDF loading has changed
// update crop.x crop.y, crop.width, crop.height according to the new scale
files
.filter((f:FileData) => view.excalidrawData.getFile(f.id)?.file?.extension === "pdf")
.forEach((f:FileData) => {
s.scene.elements
.filter((el:ExcalidrawElement)=>el.type === "image" && el.fileId === f.id && el.crop && el.crop.naturalWidth !== f.size.width)
.forEach((el:Mutable<ExcalidrawImageElement>) => {
s.dirty = true;
const scale = f.size.width / el.crop.naturalWidth;
el.crop = {
x: el.crop.x * scale,
y: el.crop.y * scale,
width: el.crop.width * scale,
height: el.crop.height * scale,
naturalWidth: f.size.width,
naturalHeight: f.size.height,
};
});
});

if (s.dirty) {
//debug({where:"ExcalidrawView.addFiles",file:view.file.name,dataTheme:view.excalidrawData.scene.appState.theme,before:"updateScene",state:scene.appState})
view.updateScene({
Expand Down Expand Up @@ -4036,7 +4058,20 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
} else {
if(link.match(/^[^#]*#page=\d*(&\w*=[^&]+){0,}&rect=\d*,\d*,\d*,\d*/g)) {
const ea = getEA(this) as ExcalidrawAutomate;
await ea.addImage(this.currentPosition.x, this.currentPosition.y,link);
const imgID = await ea.addImage(this.currentPosition.x, this.currentPosition.y,link.split("&rect=")[0]);
const el = ea.getElement(imgID) as Mutable<ExcalidrawImageElement>;
const fd = ea.imagesDict[el.fileId] as FileData;
el.crop = getPDFCropRect({
scale: this.plugin.settings.pdfScale,
link,
naturalHeight: fd.size.height,
naturalWidth: fd.size.width,
});
if(el.crop) {
el.width = el.crop.width/this.plugin.settings.pdfScale;
el.height = el.crop.height/this.plugin.settings.pdfScale;
}
el.link = `[[${link}]]`;
ea.addElementsToView(false,false).then(()=>ea.destroy());
} else {
const modal = new UniversalInsertFileModal(this.plugin, this);
Expand Down
1 change: 1 addition & 0 deletions src/constants/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ export const FRONTMATTER_KEYS:{[key:string]: {name: string, type: string, depric

export const EMBEDDABLE_THEME_FRONTMATTER_VALUES = ["light", "dark", "auto", "dafault"];
export const VIEW_TYPE_EXCALIDRAW = "excalidraw";
export const VIEW_TYPE_EXCALIDRAW_LOADING = "excalidraw-loading";
export const ICON_NAME = "excalidraw-icon";
export const MAX_COLORS = 5;
export const COLOR_FREQ = 6;
Expand Down
16 changes: 10 additions & 6 deletions src/dialogs/ExcalidrawLoading.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import { FileView, TextFileView, View, WorkspaceLeaf } from "obsidian";
import { App, FileView, WorkspaceLeaf } from "obsidian";
import { VIEW_TYPE_EXCALIDRAW_LOADING } from "src/constants/constants";
import ExcalidrawPlugin from "src/main";
import { setExcalidrawView } from "src/utils/ObsidianUtils";

export default class ExcalidrawLoading extends FileView {
export function switchToExcalidraw(app: App) {
const leaves = app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW_LOADING).filter(l=>l.view instanceof ExcalidrawLoading);
leaves.forEach(l=>(l.view as ExcalidrawLoading).switchToeExcalidraw());
}

export class ExcalidrawLoading extends FileView {
constructor(leaf: WorkspaceLeaf, private plugin: ExcalidrawPlugin) {
super(leaf);
this.switchToeExcalidraw();
this.displayLoadingText();
}

Expand All @@ -14,13 +19,12 @@ export default class ExcalidrawLoading extends FileView {
this.displayLoadingText();
}

private async switchToeExcalidraw() {
await this.plugin.awaitInit();
public switchToeExcalidraw() {
setExcalidrawView(this.leaf);
}

getViewType(): string {
return "excalidra-loading";
return VIEW_TYPE_EXCALIDRAW_LOADING;
}

getDisplayText() {
Expand Down
65 changes: 54 additions & 11 deletions src/dialogs/Prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -713,27 +713,70 @@ export class ConfirmationPrompt extends Modal {
}
}

export async function linkPrompt (
linkText:string,
export async function linkPrompt(
linkText: string,
app: App,
view?: ExcalidrawView,
message: string = "Select link to open",
):Promise<[file:TFile, linkText:string, subpath: string]> {
const linksArray = REGEX_LINK.getResList(linkText);
const tagsArray = REGEX_TAGS.getResList(linkText.replaceAll(/([^\s])#/g,"$1 "));
message: string = t("SELECT_LINK_TO_OPEN"),
): Promise<[file: TFile, linkText: string, subpath: string]> {
const linksArray = REGEX_LINK.getResList(linkText).filter(x => Boolean(x.value));
const links = linksArray.map(x => REGEX_LINK.getLink(x));

// Create a map to track duplicates by base link (without rect reference)
const linkMap = new Map<string, number[]>();
links.forEach((link, i) => {
const linkBase = link.split("&rect=")[0];
if (!linkMap.has(linkBase)) linkMap.set(linkBase, []);
linkMap.get(linkBase).push(i);
});

// Determine indices to keep
const indicesToKeep = new Set<number>();
linkMap.forEach(indices => {
if (indices.length === 1) {
// Only one link, keep it
indicesToKeep.add(indices[0]);
} else {
// Multiple links: prefer the one with rect reference, if available
const rectIndex = indices.find(i => links[i].includes("&rect="));
if (rectIndex !== undefined) {
indicesToKeep.add(rectIndex);
} else {
// No rect reference in duplicates, add the first one
indicesToKeep.add(indices[0]);
}
}
});

// Final validation to ensure each duplicate group has at least one entry
linkMap.forEach(indices => {
const hasKeptEntry = indices.some(i => indicesToKeep.has(i));
if (!hasKeptEntry) {
// Add the first index if none were kept
indicesToKeep.add(indices[0]);
}
});

// Filter linksArray, links, itemsDisplay, and items based on indicesToKeep
const filteredLinksArray = linksArray.filter((_, i) => indicesToKeep.has(i));
const tagsArray = REGEX_TAGS.getResList(linkText.replaceAll(/([^\s])#/g, "$1 ")).filter(x => Boolean(x.value));

let subpath: string = null;
let file: TFile = null;
let parts = linksArray[0] ?? tagsArray[0];
let parts = filteredLinksArray[0] ?? tagsArray[0];

// Generate filtered itemsDisplay and items arrays
const itemsDisplay = [
...linksArray.filter(p=> Boolean(p.value)).map(p => {
...filteredLinksArray.map(p => {
const alias = REGEX_LINK.getAliasOrLink(p);
return alias === "100%" ? REGEX_LINK.getLink(p) : alias;
}),
...tagsArray.filter(x=> Boolean(x.value)).map(x => REGEX_TAGS.getTag(x)),
...tagsArray.map(x => REGEX_TAGS.getTag(x)),
];

const items = [
...linksArray.filter(p=>Boolean(p.value)),
...tagsArray.filter(x=> Boolean(x.value)),
...filteredLinksArray,
...tagsArray,
];

if (items.length>1) {
Expand Down
4 changes: 4 additions & 0 deletions src/lang/locale/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ export default {
IMPORT_SVG_CONTEXTMENU: "Convert SVG to strokes - with limitations",
INSERT_MD: "Insert markdown file from vault",
INSERT_PDF: "Insert PDF file from vault",
INSERT_LAST_ACTIVE_PDF_PAGE_AS_IMAGE: "Insert last active PDF page as image",
UNIVERSAL_ADD_FILE: "Insert ANY file",
INSERT_CARD: "Add back-of-note card",
CONVERT_CARD_TO_FILE: "Move back-of-note card to File",
Expand All @@ -101,6 +102,9 @@ export default {
FONTS_LOADED: "Excalidraw: CJK Fonts loaded",
FONTS_LOAD_ERROR: "Excalidraw: Could not find CJK Fonts in the assets folder\n",

//Prompt.ts
SELECT_LINK_TO_OPEN: "Select a link to open",

//ExcalidrawView.ts
NO_SEARCH_RESULT: "Didn't find a matching element in the drawing",
FORCE_SAVE_ABORTED: "Force Save aborted because saving is in progress",
Expand Down
Loading

0 comments on commit dec2909

Please sign in to comment.