mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-11-27 06:32:42 +00:00
Compare commits
84
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
73a90fda05 | ||
|
|
8d9efe1e38 | ||
|
|
1136ebc88a | ||
|
|
40a0694a0f | ||
|
|
123cac8e00 | ||
|
|
c140f24473 | ||
|
|
f2a911c47c | ||
|
|
30eb992484 | ||
|
|
bb3eb684c0 | ||
|
|
11a5c06190 | ||
|
|
168d0e5fa6 | ||
|
|
30b20ebaf0 | ||
|
|
841db04f75 | ||
|
|
d61131e321 | ||
|
|
f45a9ebd66 | ||
|
|
757147ad4b | ||
|
|
a57db28e22 | ||
|
|
64f105b11b | ||
|
|
fccc325825 | ||
|
|
7843d9ce51 | ||
|
|
894350739a | ||
|
|
53eae64ed3 | ||
|
|
ec426ce5ea | ||
|
|
97c4381f64 | ||
|
|
25220bb6fc | ||
|
|
c3c666e0c9 | ||
|
|
ee479985f6 | ||
|
|
ab799ab836 | ||
|
|
629763ed7a | ||
|
|
e0f9326a8b | ||
|
|
2fb2ffbc4c | ||
|
|
9fcabc2d94 | ||
|
|
cc8af155c7 | ||
|
|
33e8085161 | ||
|
|
5af5844556 | ||
|
|
d2ed7faefa | ||
|
|
44bb246572 | ||
|
|
0a7ec898d1 | ||
|
|
84c77180e1 | ||
|
|
809c722855 | ||
|
|
e6c05292a7 | ||
|
|
4ad249db22 | ||
|
|
46ac969f4e | ||
|
|
573397868b | ||
|
|
278e6d9976 | ||
|
|
fb2b782bd4 | ||
|
|
421f2ec21a | ||
|
|
9e358cac97 | ||
|
|
5cbb5f2ee5 | ||
|
|
c8470ffdc5 | ||
|
|
57f8a781a6 | ||
|
|
4c764b5656 | ||
|
|
e655cfbccd | ||
|
|
1208a509d6 | ||
|
|
1759cdffab | ||
|
|
e7af4b62ac | ||
|
|
bd5df81be7 | ||
|
|
db1ec02578 | ||
|
|
e92d95fc67 | ||
|
|
9d7e0828f9 | ||
|
|
1160e0ec1f | ||
|
|
efe7009040 | ||
|
|
96aa17d4d8 | ||
|
|
52d6d905d3 | ||
|
|
329e739c69 | ||
|
|
b8b51fcff2 | ||
|
|
11f47ecd41 | ||
|
|
817854bbcd | ||
|
|
d3232f3071 | ||
|
|
e4e290cdb6 | ||
|
|
3c3f4a54b1 | ||
|
|
820e5b2324 | ||
|
|
ce332eab26 | ||
|
|
57a5149a91 | ||
|
|
cebe80ce0d | ||
|
|
cf9096adf8 | ||
|
|
dc0038a116 | ||
|
|
09356cfcef | ||
|
|
f210b4b28e | ||
|
|
6c7e9b0811 | ||
|
|
b3879f9550 | ||
|
|
4d2555532d | ||
|
|
605222de78 | ||
|
|
209ae5e2b9 |
No files matched your search
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"extends": ["@excalidraw/eslint-config"],
|
||||
"rules": {
|
||||
"import/no-anonymous-default-export": "off",
|
||||
"no-restricted-globals": "off"
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ dist
|
||||
tmp
|
||||
deploy.ps1
|
||||
eslint_results.json
|
||||
bundle-analysis.html
|
||||
|
||||
#VSCode
|
||||
yarn.lock
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"tabWidth": 2,
|
||||
"useTabs": false
|
||||
}
|
||||
Vendored
+4
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"typescript.tsdk": "node_modules/typescript/lib",
|
||||
"typescript.enablePromptUseWorkspaceTsdk": true,
|
||||
"typescript.enablePromptUseWorkspaceTsdk": true,
|
||||
"typescript.tsserver.log": "off",
|
||||
"[typescript]": {
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode",
|
||||
@@ -13,6 +13,9 @@
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.eslint": "explicit"
|
||||
},
|
||||
"editor.tabSize": 2,
|
||||
"editor.insertSpaces": true,
|
||||
"editor.formatOnSave": true,
|
||||
"eslint.validate": [
|
||||
"javascript",
|
||||
"javascriptreact",
|
||||
|
||||
Vendored
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
"type": "npm",
|
||||
"script": "lint",
|
||||
"problemMatcher": "$eslint-stylish",
|
||||
"group": {
|
||||
"kind": "build",
|
||||
"isDefault": true
|
||||
},
|
||||
"label": "Run Project Linting"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
import { mathjax } from "mathjax-full/js/mathjax";
|
||||
import { TeX } from 'mathjax-full/js/input/tex.js';
|
||||
import { SVG } from 'mathjax-full/js/output/svg.js';
|
||||
import { LiteAdaptor,liteAdaptor } from 'mathjax-full/js/adaptors/liteAdaptor.js';
|
||||
import { RegisterHTMLHandler } from 'mathjax-full/js/handlers/html.js';
|
||||
import { AllPackages } from 'mathjax-full/js/input/tex/AllPackages.js';
|
||||
import { customAlphabet } from "nanoid";
|
||||
import type { TAbstractFile, TFile } from "obsidian";
|
||||
|
||||
type DataURL = string & { _brand: "DataURL" };
|
||||
type FileId = string & { _brand: "FileId" };
|
||||
const fileid = customAlphabet("1234567890abcdef", 40);
|
||||
|
||||
type LatexPluginLike = {
|
||||
app: {
|
||||
vault: {
|
||||
getFileByPath: (path: string) => TFile | null;
|
||||
getAbstractFileByPath: (path: string) => TAbstractFile | null;
|
||||
read: (file: TAbstractFile) => Promise<string>;
|
||||
};
|
||||
};
|
||||
settings: {
|
||||
latexPreambleLocation?: string;
|
||||
};
|
||||
};
|
||||
|
||||
let adaptor: LiteAdaptor;
|
||||
let html: ReturnType<typeof mathjax.document>;
|
||||
let preamble: string;
|
||||
|
||||
function svgToBase64(svg: string): string {
|
||||
const cleanSvg = svg.replaceAll(" ", " ");
|
||||
|
||||
// Convert the string to UTF-8 and handle non-Latin1 characters
|
||||
const encodedData = encodeURIComponent(cleanSvg)
|
||||
.replace(/%([0-9A-F]{2})/g,
|
||||
(match, p1) => String.fromCharCode(parseInt(p1, 16))
|
||||
);
|
||||
|
||||
return `data:image/svg+xml;base64,${btoa(encodedData)}`;
|
||||
}
|
||||
|
||||
async function getImageSize(src: string): Promise<{ height: number; width: number }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
img.onload = () => resolve({ height: img.naturalHeight, width: img.naturalWidth });
|
||||
img.onerror = reject;
|
||||
img.src = src;
|
||||
});
|
||||
}
|
||||
|
||||
export async function tex2dataURL(
|
||||
tex: string,
|
||||
scale: number = 4,
|
||||
plugin?: LatexPluginLike
|
||||
): Promise<{
|
||||
mimeType: string;
|
||||
fileId: FileId;
|
||||
dataURL: DataURL;
|
||||
created: number;
|
||||
size: { height: number; width: number };
|
||||
}> {
|
||||
let input: TeX<Record<string, never>, Record<string, never>, Record<string, never>>;
|
||||
let output: SVG<Record<string, never>, Record<string, never>, Record<string, never>>;
|
||||
|
||||
if(!adaptor) {
|
||||
if (plugin) {
|
||||
const file = plugin.app.vault.getFileByPath(plugin.settings.latexPreambleLocation || "preamble.sty");
|
||||
preamble = file ? await plugin.app.vault.read(file) : null;
|
||||
}
|
||||
adaptor = liteAdaptor();
|
||||
RegisterHTMLHandler(adaptor);
|
||||
input = new TeX({
|
||||
packages: AllPackages,
|
||||
...(preamble ? {
|
||||
inlineMath: [['$', '$']],
|
||||
displayMath: [['$$', '$$']]
|
||||
} : {}),
|
||||
});
|
||||
output = new SVG({ fontCache: "local" });
|
||||
html = mathjax.document("", { InputJax: input, OutputJax: output });
|
||||
}
|
||||
|
||||
try {
|
||||
const node = html.convert(
|
||||
preamble ? `${preamble}\n${tex}` : tex,
|
||||
{ display: true, scale }
|
||||
);
|
||||
const svg = new DOMParser().parseFromString(adaptor.innerHTML(node), "image/svg+xml").firstChild as SVGSVGElement;
|
||||
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2195
|
||||
//https://stackoverflow.com/a/77181931
|
||||
svg.insertAdjacentHTML("beforeend", "<style>.mjx-solid { stroke-width: 80px; }</style>");
|
||||
|
||||
if (svg) {
|
||||
if(svg.width.baseVal.valueInSpecifiedUnits < 2) {
|
||||
svg.width.baseVal.valueAsString = `${(svg.width.baseVal.valueInSpecifiedUnits+1).toFixed(3)}ex`;
|
||||
}
|
||||
const img = svgToBase64(svg.outerHTML);
|
||||
svg.width.baseVal.valueAsString = (svg.width.baseVal.valueInSpecifiedUnits * 10).toFixed(3);
|
||||
svg.height.baseVal.valueAsString = (svg.height.baseVal.valueInSpecifiedUnits * 10).toFixed(3);
|
||||
const dataURL = svgToBase64(svg.outerHTML);
|
||||
return {
|
||||
mimeType: "image/svg+xml",
|
||||
fileId: fileid() as FileId,
|
||||
dataURL: dataURL as DataURL,
|
||||
created: Date.now(),
|
||||
size: await getImageSize(img),
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function clearMathJaxVariables(): void {
|
||||
adaptor = null;
|
||||
html = null;
|
||||
preamble = null;
|
||||
}
|
||||
Generated
-1655
File diff suppressed because it is too large.
Load diff
@@ -1,28 +0,0 @@
|
||||
{
|
||||
"name": "@zsviczian/mathjax-to-svg",
|
||||
"version": "1.0.0",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"build": "cross-env NODE_ENV=production rollup --config rollup.config.mjs",
|
||||
"dev": "cross-env NODE_ENV=development rollup --config rollup.config.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"mathjax-full": "^3.2.2",
|
||||
"nanoid": "^5.0.9"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rollup/plugin-commonjs": "^26.0.1",
|
||||
"@rollup/plugin-node-resolve": "^15.2.3",
|
||||
"@rollup/plugin-terser": "^0.4.4",
|
||||
"@rollup/plugin-typescript": "^12.1.2",
|
||||
"cross-env": "^7.0.3",
|
||||
"obsidian": "1.5.7-1",
|
||||
"rollup": "^4.14.0",
|
||||
"tslib": "^2.8.1",
|
||||
"typescript": "5.9.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.0.0",
|
||||
"npm": ">=10.0.0"
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import { nodeResolve } from '@rollup/plugin-node-resolve';
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import typescript from '@rollup/plugin-typescript';
|
||||
import terser from '@rollup/plugin-terser'; // <-- Updated import
|
||||
|
||||
const isProd = (process.env.NODE_ENV === 'production');
|
||||
|
||||
export default {
|
||||
input: './index.ts',
|
||||
output: {
|
||||
dir: 'dist',
|
||||
format: 'iife',
|
||||
name: 'MathjaxToSVG', // Global variable name
|
||||
exports: 'named',
|
||||
sourcemap: !isProd,
|
||||
},
|
||||
plugins: [
|
||||
typescript({
|
||||
tsconfig: 'tsconfig.json',
|
||||
sourceMap: !isProd, // <-- Explicitly tell TS compiler to output maps in dev
|
||||
}),
|
||||
commonjs(),
|
||||
nodeResolve({
|
||||
browser: true,
|
||||
preferBuiltins: false
|
||||
}),
|
||||
isProd && terser({
|
||||
format: {
|
||||
comments: false,
|
||||
},
|
||||
compress: {
|
||||
passes: 2,
|
||||
}
|
||||
})
|
||||
].filter(Boolean)
|
||||
};
|
||||
@@ -1,27 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"sourceMap": true,
|
||||
"module": "es2022",
|
||||
"target": "es2022",
|
||||
"allowJs": false,
|
||||
"noImplicitAny": true,
|
||||
"moduleResolution": "bundler",
|
||||
"esModuleInterop": true,
|
||||
"importHelpers": true,
|
||||
"resolveJsonModule": true,
|
||||
"lib": [
|
||||
"dom",
|
||||
"scripthost",
|
||||
"es2022",
|
||||
"DOM.Iterable"
|
||||
],
|
||||
"jsx": "react"
|
||||
},
|
||||
"include": [
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
"src/shared/Dialogs/OpenDrawing.ts",
|
||||
"src/types/types.d.ts"
|
||||
]
|
||||
}
|
||||
@@ -331,6 +331,7 @@ export declare class ExcalidrawAutomate {
|
||||
startArrowHead: string;
|
||||
endArrowHead: string;
|
||||
};
|
||||
setStyle(style: Partial<ExcalidrawAutomate["style"]>): void;
|
||||
canvas: {
|
||||
theme: string;
|
||||
viewBackgroundColor: string;
|
||||
@@ -1087,8 +1088,8 @@ export declare class ExcalidrawAutomate {
|
||||
* @param {ExcalidrawElement[]} [scene.elements] - Array of elements in the scene.
|
||||
* @param {AppState} [scene.appState] - The app state of the scene.
|
||||
* @param {BinaryFiles} [scene.files] - The files in the scene.
|
||||
* @param {boolean} [scene.commitToHistory] - Whether to commit the scene to history. @deprecated Use scene.storageOption instead
|
||||
* @param {"capture" | "none" | "update"} [scene.storeAction] - The store action for the scene. @deprecated Use scene.storageOption instead
|
||||
* @param {boolean} [scene.commitToHistory] - Deprecated: Use scene.storageOption instead.
|
||||
* @param {"capture" | "none" | "update"} [scene.storeAction] - Deprecated: Use scene.storageOption instead
|
||||
* @param {"IMMEDIATELY" | "NEVER" | "EVENTUALLY"} [scene.captureUpdate] - The capture update action for the scene.
|
||||
* @param {boolean} [restore=false] - Whether to restore legacy elements in the scene.
|
||||
*/
|
||||
@@ -1808,6 +1809,26 @@ export interface FrameRenderingOptions {
|
||||
clip: boolean;
|
||||
}
|
||||
export type PaneTarget = "active-pane" | "new-pane" | "popout-window" | "new-tab" | "md-properties";
|
||||
export interface NestedFileNode {
|
||||
file: TFile;
|
||||
/**
|
||||
* All distinct dependency paths from the root file down to this embedded file.
|
||||
* Each path is an ordered array of TFile objects starting with the `rootFile` at index 0.
|
||||
*
|
||||
* @example
|
||||
* If Root -> A -> B2.2 and Root -> B -> B2 -> B2.2
|
||||
* The paths for B2.2 will be:
|
||||
* [
|
||||
* [Root, A, B2.2],
|
||||
* [Root, B, B2, B2.2]
|
||||
* ]
|
||||
*
|
||||
* Usage: To find which top-level embeds to reload if this file changes,
|
||||
* you can map over `paths` and collect `path[1]`.
|
||||
*/
|
||||
paths: TFile[][];
|
||||
}
|
||||
export type NestedFileMap = Map<TFile, NestedFileNode>;
|
||||
|
||||
/* ************************************ */
|
||||
/* lib/types/exportUtilTypes.d.ts */
|
||||
@@ -1900,6 +1921,71 @@ export interface ExportSettings {
|
||||
frameRendering?: FrameRenderingOptions;
|
||||
skipInliningFonts?: boolean;
|
||||
}
|
||||
export interface PrintToPDFOptions {
|
||||
includeName: boolean;
|
||||
pageSize: string | {
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
landscape: boolean;
|
||||
margins: {
|
||||
top: number;
|
||||
left: number;
|
||||
right: number;
|
||||
bottom: number;
|
||||
};
|
||||
scaleFactor: number;
|
||||
scale: number;
|
||||
open: boolean;
|
||||
filepath: string;
|
||||
preferCSSPageSize?: boolean;
|
||||
pageRanges?: string | {
|
||||
from: number;
|
||||
to: number;
|
||||
}[];
|
||||
}
|
||||
export interface SaveDialogOptions {
|
||||
defaultPath: string;
|
||||
filters: {
|
||||
name: string;
|
||||
extensions: string[];
|
||||
}[];
|
||||
properties: string[];
|
||||
}
|
||||
export interface SaveDialogReturnValue {
|
||||
canceled: boolean;
|
||||
filePath?: string;
|
||||
}
|
||||
type CaptureRect = {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
type NativeImageLike = {
|
||||
toPNG(): Uint8Array | Buffer;
|
||||
};
|
||||
interface ElectronWebContentsLike {
|
||||
capturePage(rect: CaptureRect): Promise<NativeImageLike>;
|
||||
getZoomFactor(): number;
|
||||
setZoomFactor(factor: number): void;
|
||||
}
|
||||
interface ElectronWebUtilsLike {
|
||||
getPathForFile(file: File): string;
|
||||
}
|
||||
export interface ElectronAPI {
|
||||
ipcRenderer: {
|
||||
send(channel: string, ...args: unknown[]): void;
|
||||
once(channel: string, func: (...args: unknown[]) => void): void;
|
||||
};
|
||||
remote: {
|
||||
dialog: {
|
||||
showSaveDialog(options: SaveDialogOptions): Promise<SaveDialogReturnValue>;
|
||||
};
|
||||
getCurrentWebContents(): ElectronWebContentsLike;
|
||||
};
|
||||
webUtils: ElectronWebUtilsLike;
|
||||
}
|
||||
|
||||
/* ************************************** */
|
||||
/* lib/types/embeddedFileLoaderTypes.d.ts */
|
||||
@@ -2906,6 +2992,7 @@ export type OnExportProgress = {
|
||||
};
|
||||
export interface ExcalidrawProps {
|
||||
onChange?: (elements: readonly OrderedExcalidrawElement[], appState: AppState, files: BinaryFiles) => void;
|
||||
onThemeChange?: (theme: Theme | "system") => void;
|
||||
/**
|
||||
* note: only subscribes if the props.onIncrement is defined on initial render
|
||||
*/
|
||||
@@ -2982,7 +3069,6 @@ export interface ExcalidrawProps {
|
||||
nextLink: string;
|
||||
};
|
||||
generateIdForFile?: (file: File) => string | Promise<string>;
|
||||
onThemeChange?: (newTheme: string) => void;
|
||||
onViewModeChange?: (isViewModeEnabled: boolean) => void;
|
||||
generateLinkForSelection?: (id: string, type: "element" | "group") => string;
|
||||
onLinkOpen?: (element: NonDeletedExcalidrawElement, event: CustomEvent<{
|
||||
@@ -3049,6 +3135,11 @@ export type CanvasActions = Partial<{
|
||||
export: false | ExportOpts;
|
||||
loadScene: boolean;
|
||||
saveToActiveFile: boolean;
|
||||
/**
|
||||
* defaults to true if `props.theme` is omitted or `props.onThemeChange`
|
||||
* is supplied (at which point the theme is considered as host-app controlled),
|
||||
* else default to false
|
||||
* */
|
||||
toggleTheme: boolean | null;
|
||||
saveAsImage: boolean;
|
||||
}>;
|
||||
@@ -3383,6 +3474,23 @@ export declare const pointInsideBounds: <P extends GlobalPoint | LocalPoint>(p:
|
||||
export declare const pointInsideBoundsInclusive: <P extends GlobalPoint | LocalPoint>(p: P, bounds: Bounds) => boolean;
|
||||
export declare const doBoundsIntersect: (bounds1: Bounds | null, bounds2: Bounds | null) => boolean;
|
||||
export declare const boundsContainBounds: (outerBounds: Bounds, innerBounds: Bounds) => boolean;
|
||||
/**
|
||||
* High level helper to get elements overlapping a bounding box.
|
||||
* It can be used to get elements overlapping a selection box, for example.
|
||||
*
|
||||
*/
|
||||
export declare const elementsOverlappingBBox: ({ elements, elementsMap, bounds, type, excludeElementsInFrames, shouldIgnoreElementFromSelection, }: {
|
||||
elements: readonly NonDeletedExcalidrawElement[];
|
||||
elementsMap?: ElementsMap;
|
||||
bounds: Bounds | ExcalidrawElement;
|
||||
/**
|
||||
* - overlap: elements overlapping or inside bounds
|
||||
* - contain: elements inside bounds
|
||||
**/
|
||||
type: "contain" | "overlap";
|
||||
excludeElementsInFrames?: boolean;
|
||||
shouldIgnoreElementFromSelection?: (element: NonDeletedExcalidrawElement) => boolean;
|
||||
}) => NonDeletedExcalidrawElement[];
|
||||
export declare const elementCenterPoint: (element: ExcalidrawElement, elementsMap: ElementsMap, xOffset?: number, yOffset?: number) => GlobalPoint;
|
||||
|
||||
/* ************************************** */
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+101
-35
@@ -682,7 +682,7 @@ async function prepareTargetExcalidrawView(noteBWorkspaceLeaf) {
|
||||
}
|
||||
|
||||
// Injects the visual frame marker and template onto the target Note B
|
||||
async function injectVisualFormat(target_ea, targetX, targetY, sectionRawText, todayDNPBasename, isCurrentDNP, preGeneratedFrameID, embeddedElementId, ontologyAction, originFilePath) {
|
||||
async function injectVisualFormat(target_ea, targetX, targetY, sectionRawText, todayDNPBasename, isCurrentDNP, preGeneratedFrameID, embeddedElementId, ontologyAction, originFilePath, opt) {
|
||||
const fWidth = parseInt(settings.frameWidth) || 1920;
|
||||
const fHeight = parseInt(settings.frameHeight) || 1080;
|
||||
|
||||
@@ -715,9 +715,15 @@ async function injectVisualFormat(target_ea, targetX, targetY, sectionRawText, t
|
||||
}
|
||||
|
||||
let clonedTemplateElementIds = [];
|
||||
if (settings.visualTemplateJSON) {
|
||||
|
||||
// Resolve Visual Template details with fallback to global settings
|
||||
const visualTemplateJSON = opt?.visualTemplateJSON || settings.visualTemplateJSON;
|
||||
const visualTemplateHAlign = opt?.visualTemplateHAlign || settings.visualTemplateHAlign || "center";
|
||||
const visualTemplateVAlign = opt?.visualTemplateVAlign || settings.visualTemplateVAlign || "middle";
|
||||
|
||||
if (visualTemplateJSON) {
|
||||
try {
|
||||
const parsed = JSON.parse(settings.visualTemplateJSON);
|
||||
const parsed = JSON.parse(visualTemplateJSON);
|
||||
if (parsed.elements && parsed.elements.length > 0) {
|
||||
const clonedElements = ExcalidrawLib.restoreElements(
|
||||
target_ea.cloneElements(parsed.elements,
|
||||
@@ -735,17 +741,17 @@ async function injectVisualFormat(target_ea, targetX, targetY, sectionRawText, t
|
||||
let offsetX = 0;
|
||||
let offsetY = 0;
|
||||
|
||||
if (settings.visualTemplateHAlign === "left") {
|
||||
if (visualTemplateHAlign === "left") {
|
||||
offsetX = targetX - bounds[0] + FRAME_MARGIN;
|
||||
} else if (settings.visualTemplateHAlign === "right") {
|
||||
} else if (visualTemplateHAlign === "right") {
|
||||
offsetX = targetX + fWidth - bounds[2] - FRAME_MARGIN;
|
||||
} else {
|
||||
offsetX = targetX + (fWidth - boundsWidth) / 2 - bounds[0];
|
||||
}
|
||||
|
||||
if (settings.visualTemplateVAlign === "top") {
|
||||
if (visualTemplateVAlign === "top") {
|
||||
offsetY = targetY - bounds[1] + FRAME_MARGIN;
|
||||
} else if (settings.visualTemplateVAlign === "bottom") {
|
||||
} else if (visualTemplateVAlign === "bottom") {
|
||||
offsetY = targetY + fHeight - bounds[3] - FRAME_MARGIN;
|
||||
} else {
|
||||
offsetY = targetY + (fHeight - boundsHeight) / 2 - bounds[1];
|
||||
@@ -1131,6 +1137,11 @@ async function handleFinalActionFocus(actionType, originView, noteBWorkspaceLeaf
|
||||
target_ea.viewZoomToElements(format !== "Visual", targetElements, 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
// Set MMB view if Visual and mmAPI is available
|
||||
if (format === "Visual" && window.MindMapBuilderAPI && target_ea.targetView) {
|
||||
window.MindMapBuilderAPI.setView(target_ea.targetView);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1434,7 +1445,7 @@ async function start() {
|
||||
// 11. Inject onto Target Note using preGeneratedFrameID
|
||||
let clonedTemplateElementIds = [];
|
||||
if (format === "Visual") {
|
||||
const visualRes = await injectVisualFormat(target_ea, targetX, targetY, sectionRawText, todayDNPBasename, isCurrentDNP, preGeneratedFrameID, embeddedElementId, ontologyAction, originView.file.path);
|
||||
const visualRes = await injectVisualFormat(target_ea, targetX, targetY, sectionRawText, todayDNPBasename, isCurrentDNP, preGeneratedFrameID, embeddedElementId, ontologyAction, originView.file.path, opt);
|
||||
clonedTemplateElementIds = visualRes.clonedTemplateElementIds;
|
||||
} else {
|
||||
await injectMarkdownFormat(file, target_ea, targetX, targetY, sectionRawText, sectionWithBrackets, todayDNPBasename, isCurrentDNP, preGeneratedFrameID, embeddedElementId, ontologyAction, originView.file.path);
|
||||
@@ -1601,28 +1612,49 @@ function buildCaptureSearchBox(contentEl, state, callbacks) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Tokenize the query into individual words for partial matching
|
||||
const q = query.toLowerCase().trim();
|
||||
const searchTerms = q.split(/\s+/);
|
||||
// Helper to escape regex special characters
|
||||
const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const tokens = q.split(/\s+/);
|
||||
// Create an ordered regex pattern (e.g. "my.*search.*term")
|
||||
const fuzzyRegex = new RegExp(tokens.map(escapeRegex).join('.*'), 'i');
|
||||
|
||||
const uniqueItems = new Map();
|
||||
const scoredItems = new Map();
|
||||
|
||||
state.searchItems.forEach(item => {
|
||||
const searchableText = item.type === "alias" ? `${item.basename} ${item.alias}` : item.basename;
|
||||
const searchableTextLower = searchableText.toLowerCase();
|
||||
// Search against the full file path if available, otherwise fallback to basename
|
||||
const searchableText = item.file
|
||||
? item.file.path + (item.type === "alias" && item.alias ? " " + item.alias : "")
|
||||
: item.basename;
|
||||
|
||||
// Ensure all partial words are found
|
||||
const matches = searchTerms.every(term => searchableTextLower.includes(term));
|
||||
|
||||
if (matches) {
|
||||
if (fuzzyRegex.test(searchableText)) {
|
||||
// Evaluate if it's an exact match on either the basename or alias
|
||||
const isExactBasename = item.basename.toLowerCase() === q;
|
||||
const isExactAlias = item.type === "alias" && item.alias.toLowerCase() === q;
|
||||
const isExact = isExactBasename || isExactAlias;
|
||||
|
||||
const mtime = item.file?.stat?.mtime || 0;
|
||||
|
||||
// Include file path to differentiate identical basenames
|
||||
const pathSuffix = item.file ? `:${item.file.path}` : "";
|
||||
const key = item.type === "alias" ? `alias:${item.basename}:${item.alias}${pathSuffix}` : `${item.type}:${item.basename}${pathSuffix}`;
|
||||
if (!uniqueItems.has(key)) {
|
||||
uniqueItems.set(key, item);
|
||||
|
||||
const current = scoredItems.get(key);
|
||||
// Add to map if unique, or if it represents a higher scoring match instance
|
||||
if (!current || isExact > current.isExact || (isExact === current.isExact && mtime > current.mtime)) {
|
||||
scoredItems.set(key, { item, isExact, mtime });
|
||||
}
|
||||
}
|
||||
});
|
||||
matchedItems = Array.from(uniqueItems.values()).slice(0, 8);
|
||||
|
||||
// Sort exact matches to the top, then sort by most recently modified
|
||||
matchedItems = Array.from(scoredItems.values())
|
||||
.sort((a, b) => {
|
||||
if (a.isExact !== b.isExact) return a.isExact ? -1 : 1;
|
||||
return b.mtime - a.mtime;
|
||||
})
|
||||
.map(s => s.item)
|
||||
.slice(0, 8);
|
||||
|
||||
if (matchedItems.length > 0) {
|
||||
resultsDropdown.style.display = "block";
|
||||
@@ -2108,11 +2140,11 @@ function buildVisualSizingSection(contentEl) {
|
||||
.onChange(val => { settings.openNoteBBehavior = val; }));
|
||||
}
|
||||
|
||||
async function refreshTemplatePreview(previewDiv, alignSettingsDiv, refreshCallback) {
|
||||
async function refreshTemplatePreview(previewDiv, alignSettingsDiv, configObj, saveCallback, refreshCallback) {
|
||||
previewDiv.empty();
|
||||
alignSettingsDiv.empty();
|
||||
|
||||
if (!settings.visualTemplateJSON) {
|
||||
if (!configObj.visualTemplateJSON) {
|
||||
const pasteBtn = previewDiv.createEl("button", { text: "Paste Excalidraw Elements from Clipboard" });
|
||||
pasteBtn.addEventListener("click", async () => {
|
||||
try {
|
||||
@@ -2123,8 +2155,16 @@ async function refreshTemplatePreview(previewDiv, alignSettingsDiv, refreshCallb
|
||||
new Notice("Image elements are not supported in visual templates.");
|
||||
return;
|
||||
}
|
||||
settings.visualTemplateJSON = text;
|
||||
ea.setScriptSettings(settings);
|
||||
|
||||
// Run pasted elements through restoreElements
|
||||
parsed.elements = window.ExcalidrawLib.restoreElements(
|
||||
parsed.elements,
|
||||
null,
|
||||
{ refreshDimensions: true, repairBindings: true }
|
||||
);
|
||||
|
||||
configObj.visualTemplateJSON = JSON.stringify(parsed);
|
||||
saveCallback();
|
||||
refreshCallback();
|
||||
} else {
|
||||
new Notice("Clipboard does not contain valid Excalidraw elements.");
|
||||
@@ -2135,7 +2175,7 @@ async function refreshTemplatePreview(previewDiv, alignSettingsDiv, refreshCallb
|
||||
});
|
||||
} else {
|
||||
try {
|
||||
const parsed = JSON.parse(settings.visualTemplateJSON);
|
||||
const parsed = JSON.parse(configObj.visualTemplateJSON);
|
||||
const svg = await ea.createViewSVG({
|
||||
elementsOverride: parsed.elements,
|
||||
withBackground: false,
|
||||
@@ -2152,8 +2192,8 @@ async function refreshTemplatePreview(previewDiv, alignSettingsDiv, refreshCallb
|
||||
const delBtn = headerRow.createEl("button", { cls: "clickable-icon" });
|
||||
delBtn.innerHTML = ea.obsidian.getIcon("trash-2").outerHTML;
|
||||
delBtn.addEventListener("click", () => {
|
||||
settings.visualTemplateJSON = "";
|
||||
ea.setScriptSettings(settings);
|
||||
configObj.visualTemplateJSON = "";
|
||||
saveCallback();
|
||||
refreshCallback();
|
||||
});
|
||||
|
||||
@@ -2163,8 +2203,8 @@ async function refreshTemplatePreview(previewDiv, alignSettingsDiv, refreshCallb
|
||||
.addOption("top", "Top")
|
||||
.addOption("middle", "Middle")
|
||||
.addOption("bottom", "Bottom")
|
||||
.setValue(settings.visualTemplateVAlign || "middle")
|
||||
.onChange(v => { settings.visualTemplateVAlign = v; ea.setScriptSettings(settings); })
|
||||
.setValue(configObj.visualTemplateVAlign || "middle")
|
||||
.onChange(v => { configObj.visualTemplateVAlign = v; saveCallback(); })
|
||||
);
|
||||
|
||||
new ea.obsidian.Setting(alignSettingsDiv)
|
||||
@@ -2173,12 +2213,12 @@ async function refreshTemplatePreview(previewDiv, alignSettingsDiv, refreshCallb
|
||||
.addOption("left", "Left")
|
||||
.addOption("center", "Center")
|
||||
.addOption("right", "Right")
|
||||
.setValue(settings.visualTemplateHAlign || "center")
|
||||
.onChange(v => { settings.visualTemplateHAlign = v; ea.setScriptSettings(settings); })
|
||||
.setValue(configObj.visualTemplateHAlign || "center")
|
||||
.onChange(v => { configObj.visualTemplateHAlign = v; saveCallback(); })
|
||||
);
|
||||
} catch (e) {
|
||||
settings.visualTemplateJSON = "";
|
||||
ea.setScriptSettings(settings);
|
||||
configObj.visualTemplateJSON = "";
|
||||
saveCallback();
|
||||
refreshCallback();
|
||||
new Notice("Failed to load visual template preview.");
|
||||
}
|
||||
@@ -2192,7 +2232,13 @@ function buildVisualTemplateSection(contentEl) {
|
||||
const previewDiv = templateSection.createDiv();
|
||||
const alignSettingsDiv = templateSection.createDiv();
|
||||
|
||||
const refreshCallback = () => refreshTemplatePreview(previewDiv, alignSettingsDiv, refreshCallback);
|
||||
const refreshCallback = () => refreshTemplatePreview(
|
||||
previewDiv,
|
||||
alignSettingsDiv,
|
||||
settings,
|
||||
() => ea.setScriptSettings(settings),
|
||||
refreshCallback
|
||||
);
|
||||
refreshCallback();
|
||||
}
|
||||
|
||||
@@ -2604,6 +2650,26 @@ function openEditNoteTypeModal(noteTypeKey, saveCallback) {
|
||||
});
|
||||
|
||||
renderChips();
|
||||
|
||||
// Note Type Specific Visual Template Elements
|
||||
const templateSection = contentEl.createEl("details", { cls: "setting-sub-section", attr: { style: "margin-top: 15px;" } });
|
||||
templateSection.createEl("summary", { text: "Note Type Specific Visual Template Elements" });
|
||||
templateSection.createEl("p", {
|
||||
text: "If defined, these elements will override the global visual template.",
|
||||
attr: { style: "color: var(--text-muted); font-size: 0.9em; margin-bottom: 10px;" }
|
||||
});
|
||||
|
||||
const previewDiv = templateSection.createDiv();
|
||||
const alignSettingsDiv = templateSection.createDiv();
|
||||
|
||||
const refreshVisualTemplateCallback = () => refreshTemplatePreview(
|
||||
previewDiv,
|
||||
alignSettingsDiv,
|
||||
typeConfig,
|
||||
() => {}, // Changes will be formally persisted when the modal "Save" button is clicked
|
||||
refreshVisualTemplateCallback
|
||||
);
|
||||
refreshVisualTemplateCallback();
|
||||
};
|
||||
|
||||
modal.onClose = () => {
|
||||
@@ -2615,4 +2681,4 @@ function openEditNoteTypeModal(noteTypeKey, saveCallback) {
|
||||
// -------------------------------------------------------------
|
||||
// 8. Run Trigger
|
||||
// -------------------------------------------------------------
|
||||
await start();
|
||||
await start();
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,10 @@
|
||||
<svg class="svg-icon lucide-swatch-book" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<!-- bottom swatch card (peeking out) -->
|
||||
<path d="M8 13H19a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H6V13Z" fill="#FFD23F"/>
|
||||
<!-- back / cover card with binder ring -->
|
||||
<path d="M11 17a4 4 0 0 1-8 0V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2Z" fill="#FF6B6B"/>
|
||||
<!-- flipped-open top card -->
|
||||
<path d="m11 8 2.3-2.3a2.4 2.4 0 0 1 3.404.004L18.6 7.6a2.4 2.4 0 0 1 .026 3.434L9.9 19.8Z" fill="#4ECDC4"/>
|
||||
<!-- binder ring hole -->
|
||||
<path d="M7 17h.01"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 668 B |
@@ -349,6 +349,34 @@ const STRINGS = {
|
||||
MANUAL_JITTER_RANGE: "Manual-layout Jitter Range",
|
||||
DESC_LAYOUT_MANUAL_JITTER: "Random position offset when adding nodes while Auto-Layout is disabled.",
|
||||
|
||||
CALENDAR_DATE_INDEX: "Date {index} of {total}",
|
||||
CALENDAR_DATE_LABEL: "Date",
|
||||
CALENDAR_DATE_TYPE: "Date Type",
|
||||
CALENDAR_PRIORITY: "Priority",
|
||||
CALENDAR_RECURRENCE: "Recurrence",
|
||||
CALENDAR_RECURRENCE_PLACEHOLDER: "every day",
|
||||
CALENDAR_RECURRENCE_DESC: "e.g., 'every day', 'every 2 weeks' <br><a href=\"https://publish.obsidian.md/tasks/Getting+Started/Recurring+Tasks\" target=\"_blank\" tabindex=\"-1\">Tasks recurrence docs</a>",
|
||||
CALENDAR_INJECT_LINK: "Inject node link",
|
||||
CALENDAR_INJECT_LINK_DESC: "Adds a link to the node at the end of the task.",
|
||||
CALENDAR_ALIAS_PLACEHOLDER: "Alias",
|
||||
CALENDAR_BTN_CANCEL: "Cancel",
|
||||
CALENDAR_BTN_TASK_ONLY: "Task Only",
|
||||
CALENDAR_BTN_ADD_DATE_TASK: "Add Date & Task",
|
||||
|
||||
CALENDAR_PRIORITY_HIGHEST: "Highest",
|
||||
CALENDAR_PRIORITY_HIGH: "High",
|
||||
CALENDAR_PRIORITY_MEDIUM: "Medium",
|
||||
CALENDAR_PRIORITY_NORMAL: "Normal",
|
||||
CALENDAR_PRIORITY_LOW: "Low",
|
||||
CALENDAR_PRIORITY_LOWEST: "Lowest",
|
||||
|
||||
CALENDAR_DATETYPE_DUE: "Due",
|
||||
CALENDAR_DATETYPE_START: "Start",
|
||||
CALENDAR_DATETYPE_SCHEDULED: "Scheduled",
|
||||
CALENDAR_DATETYPE_CREATED: "Created",
|
||||
CALENDAR_DATETYPE_DONE: "Done",
|
||||
CALENDAR_DATETYPE_CANCELLED: "Cancelled",
|
||||
|
||||
// Misc
|
||||
INPUT_TITLE_PASTE_ROOT: "Mindmap Builder Paste",
|
||||
INSTRUCTIONS: "> [!Tip]\n" +
|
||||
@@ -598,6 +626,34 @@ addLocale("zh", {
|
||||
MANUAL_JITTER_RANGE: "手动布局抖动范围",
|
||||
DESC_LAYOUT_MANUAL_JITTER: "禁用自动布局时添加节点的随机位置偏移。",
|
||||
|
||||
CALENDAR_DATE_INDEX: "第 {index} 个日期,共 {total} 个",
|
||||
CALENDAR_DATE_LABEL: "日期",
|
||||
CALENDAR_DATE_TYPE: "日期类型",
|
||||
CALENDAR_PRIORITY: "优先级",
|
||||
CALENDAR_RECURRENCE: "重复",
|
||||
CALENDAR_RECURRENCE_PLACEHOLDER: "每天",
|
||||
CALENDAR_RECURRENCE_DESC: "例如,'every day'(每天),'every 2 weeks'(每两周)<br><a href=\"https://publish.obsidian.md/tasks/Getting+Started/Recurring+Tasks\" target=\"_blank\" tabindex=\"-1\">Tasks 插件重复任务文档</a>",
|
||||
CALENDAR_INJECT_LINK: "插入节点链接",
|
||||
CALENDAR_INJECT_LINK_DESC: "在任务末尾添加指向该节点的链接。",
|
||||
CALENDAR_ALIAS_PLACEHOLDER: "别名",
|
||||
CALENDAR_BTN_CANCEL: "取消",
|
||||
CALENDAR_BTN_TASK_ONLY: "仅任务",
|
||||
CALENDAR_BTN_ADD_DATE_TASK: "添加日期和任务",
|
||||
|
||||
CALENDAR_PRIORITY_HIGHEST: "最高",
|
||||
CALENDAR_PRIORITY_HIGH: "高",
|
||||
CALENDAR_PRIORITY_MEDIUM: "中",
|
||||
CALENDAR_PRIORITY_NORMAL: "普通",
|
||||
CALENDAR_PRIORITY_LOW: "低",
|
||||
CALENDAR_PRIORITY_LOWEST: "最低",
|
||||
|
||||
CALENDAR_DATETYPE_DUE: "截止",
|
||||
CALENDAR_DATETYPE_START: "开始",
|
||||
CALENDAR_DATETYPE_SCHEDULED: "计划",
|
||||
CALENDAR_DATETYPE_CREATED: "创建",
|
||||
CALENDAR_DATETYPE_DONE: "完成",
|
||||
CALENDAR_DATETYPE_CANCELLED: "取消",
|
||||
|
||||
// Misc
|
||||
INPUT_TITLE_PASTE_ROOT: "MindMap Builder 粘贴",
|
||||
INSTRUCTIONS: "> [!Tip]\n" +
|
||||
@@ -838,6 +894,34 @@ addLocale("zh-tw", {
|
||||
MANUAL_JITTER_RANGE: "手動佈局抖動範圍",
|
||||
DESC_LAYOUT_MANUAL_JITTER: "停用自動佈局時新增節點的隨機位置偏移。",
|
||||
|
||||
CALENDAR_DATE_INDEX: "第 {index} 個日期,共 {total} 個",
|
||||
CALENDAR_DATE_LABEL: "日期",
|
||||
CALENDAR_DATE_TYPE: "日期類型",
|
||||
CALENDAR_PRIORITY: "優先級",
|
||||
CALENDAR_RECURRENCE: "重複",
|
||||
CALENDAR_RECURRENCE_PLACEHOLDER: "每天",
|
||||
CALENDAR_RECURRENCE_DESC: "例如,'every day'(每天),'every 2 weeks'(每兩週)<br><a href=\"https://publish.obsidian.md/tasks/Getting+Started/Recurring+Tasks\" target=\"_blank\" tabindex=\"-1\">Tasks 外掛重複任務文件</a>",
|
||||
CALENDAR_INJECT_LINK: "插入節點連結",
|
||||
CALENDAR_INJECT_LINK_DESC: "在任務末尾新增指向該節點的連結。",
|
||||
CALENDAR_ALIAS_PLACEHOLDER: "別名",
|
||||
CALENDAR_BTN_CANCEL: "取消",
|
||||
CALENDAR_BTN_TASK_ONLY: "僅任務",
|
||||
CALENDAR_BTN_ADD_DATE_TASK: "新增日期和任務",
|
||||
|
||||
CALENDAR_PRIORITY_HIGHEST: "最高",
|
||||
CALENDAR_PRIORITY_HIGH: "高",
|
||||
CALENDAR_PRIORITY_MEDIUM: "中",
|
||||
CALENDAR_PRIORITY_NORMAL: "普通",
|
||||
CALENDAR_PRIORITY_LOW: "低",
|
||||
CALENDAR_PRIORITY_LOWEST: "最低",
|
||||
|
||||
CALENDAR_DATETYPE_DUE: "截止",
|
||||
CALENDAR_DATETYPE_START: "開始",
|
||||
CALENDAR_DATETYPE_SCHEDULED: "計畫",
|
||||
CALENDAR_DATETYPE_CREATED: "建立",
|
||||
CALENDAR_DATETYPE_DONE: "完成",
|
||||
CALENDAR_DATETYPE_CANCELLED: "取消",
|
||||
|
||||
// Misc
|
||||
INPUT_TITLE_PASTE_ROOT: "MindMap Builder 貼上",
|
||||
INSTRUCTIONS: "> [!Tip]\n" +
|
||||
@@ -941,6 +1025,17 @@ const K_PALETTE = "Custom Palette";
|
||||
const K_LAYOUT = "Layout Config";
|
||||
const K_ARROW_TYPE = "Arrow Type";
|
||||
const K_FILL_SWEEP = "Fill Sweep";
|
||||
const K_INJECT_LINK = "Inject Node Link";
|
||||
const K_LINK_ALIAS = "Node Link Alias";
|
||||
|
||||
let injectNodeLink = getVal(K_INJECT_LINK, true);
|
||||
let nodeLinkAlias = getVal(K_LINK_ALIAS, "(link)");
|
||||
|
||||
const isExcaliBrainView = () => {
|
||||
if (!ea.targetView || !ea.targetView.file) return false;
|
||||
const eb = app.plugins.plugins["excalibrain"];
|
||||
return eb && eb.settings?.excalibrainFilepath === ea.targetView.file.path;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Layout & Geometry Settings
|
||||
@@ -5408,6 +5503,14 @@ const addNode = async (text, follow = false, skipFinalLayout = false, batchModeA
|
||||
if (!isViewSet()) return;
|
||||
if (!text || text.trim() === "") return;
|
||||
|
||||
const preGenTextId = ea.generateElementId();
|
||||
if (text.includes("__NODE_LINK_PLACEHOLDER__")) {
|
||||
const file = app.workspace.getActiveFile();
|
||||
const fileName = file ? file.basename : "";
|
||||
const linkStr = `[[${fileName}#^group=${preGenTextId}|${nodeLinkAlias}]]`;
|
||||
text = text.replace("__NODE_LINK_PLACEHOLDER__", linkStr);
|
||||
}
|
||||
|
||||
const st = getAppState();
|
||||
const isBatchMode = batchModeAllElements !== null;
|
||||
|
||||
@@ -5480,6 +5583,30 @@ const addNode = async (text, follow = false, skipFinalLayout = false, batchModeA
|
||||
nodeColor = parent.strokeColor;
|
||||
}
|
||||
}
|
||||
|
||||
const effectiveMulticolor = rootCfgForAdd?.multicolor ?? multicolor;
|
||||
const effectiveIsSolidArrow = rootCfgForAdd?.isSolidArrow ?? isSolidArrow;
|
||||
|
||||
// If multicolor is disabled AND "Use scene stroke style" is enabled (!effectiveIsSolidArrow)
|
||||
if (!effectiveMulticolor && !effectiveIsSolidArrow) {
|
||||
const parentStrokeColor = (parent.strokeColor || "transparent").toLowerCase();
|
||||
const isTransparent = parentStrokeColor === "transparent";
|
||||
|
||||
let isSameAsBg = false;
|
||||
if (!isTransparent) {
|
||||
const parentColorCM = ea.getCM(parent.strokeColor);
|
||||
const bgColorCM = ea.getCM(st.viewBackgroundColor);
|
||||
if (parentColorCM && bgColorCM && parentColorCM.stringHEX() === bgColorCM.stringHEX()) {
|
||||
isSameAsBg = true;
|
||||
}
|
||||
}
|
||||
|
||||
// If the parent's stroke is transparent or matches the view background,
|
||||
// invert the scene color for the new node and branch
|
||||
if (isTransparent || isSameAsBg) {
|
||||
nodeColor = ea.getCM(st.viewBackgroundColor).invert().stringHEX({ alpha: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const fontScale = getFontScale(rootCfgForAdd?.fontsizeScale ?? fontsizeScale);
|
||||
@@ -5553,7 +5680,7 @@ const addNode = async (text, follow = false, skipFinalLayout = false, batchModeA
|
||||
width: shouldWrap ? curMaxW : undefined,
|
||||
height: shouldWrap ? curMaxH : undefined,
|
||||
autoResize: !shouldWrap,
|
||||
});
|
||||
}, preGenTextId);
|
||||
ea.style.backgroundColor = "transparent";
|
||||
}
|
||||
|
||||
@@ -5721,7 +5848,7 @@ const addNode = async (text, follow = false, skipFinalLayout = false, batchModeA
|
||||
width: shouldWrap ? curMaxW : undefined,
|
||||
height: shouldWrap ? curMaxH : undefined,
|
||||
autoResize: !shouldWrap,
|
||||
});
|
||||
}, preGenTextId);
|
||||
}
|
||||
|
||||
if (depth === 1) {
|
||||
@@ -8951,6 +9078,11 @@ const updateUI = (sel) => {
|
||||
setButtonDisabled(focusBtn, false);
|
||||
setButtonDisabled(floatingZoomBtn, false);
|
||||
}
|
||||
// Enable task buttons if there's text input
|
||||
if (inputEl && inputEl.value.trim() !== "") {
|
||||
if (toggleCheckboxBtn) setButtonDisabled(toggleCheckboxBtn, false);
|
||||
if (calendarBtn) setButtonDisabled(calendarBtn, false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -9818,7 +9950,7 @@ const renderInput = (container, isFloating = false) => {
|
||||
ignoreFocusChanges = true;
|
||||
setTimeout(() => {
|
||||
ignoreFocusChanges = false;
|
||||
lastFocusedInput.focus();
|
||||
if (lastFocusedInput) lastFocusedInput.focus();
|
||||
}, 200);
|
||||
container.empty();
|
||||
|
||||
@@ -9839,7 +9971,6 @@ const renderInput = (container, isFloating = false) => {
|
||||
inputRow.controlEl.style.marginTop = "8px";
|
||||
} else {
|
||||
container.style.width = "85vw";
|
||||
// Updated max width limit to fit up to 18 icons long as requested
|
||||
container.style.maxWidth = "calc((var(--icon-size) + 2 * var(--size-2-3)) * 18)";
|
||||
inputRow.settingEl.style.border = "none";
|
||||
inputRow.settingEl.style.padding = "0";
|
||||
@@ -9852,28 +9983,27 @@ const renderInput = (container, isFloating = false) => {
|
||||
secondaryButtonContainer.style.flexWrap = "wrap";
|
||||
secondaryButtonContainer.style.gap = "0px";
|
||||
secondaryButtonContainer.style.marginTop = "6px";
|
||||
secondaryButtonContainer.style.flexWrap = "wrap";
|
||||
}
|
||||
|
||||
// Clear default control element to build custom two-input layout
|
||||
inputRow.controlEl.empty();
|
||||
|
||||
const wrapper = inputRow.controlEl.createDiv("mindmap-input-wrapper");
|
||||
|
||||
// --- Ontology Input ---
|
||||
ontologyEl = wrapper.createEl("input", {
|
||||
type: "text",
|
||||
cls: "mindmap-input-ontology",
|
||||
placeholder: t("ONTOLOGY_PLACEHOLDER")
|
||||
});
|
||||
|
||||
// --- Main Input ---
|
||||
inputEl = wrapper.createEl("input", {
|
||||
type: "text",
|
||||
cls: "mindmap-input-main",
|
||||
placeholder: t("INPUT_PLACEHOLDER")
|
||||
});
|
||||
|
||||
inputEl.addEventListener("input", () => updateUI());
|
||||
ontologyEl.addEventListener("input", () => updateUI());
|
||||
|
||||
const updateFocusState = (focusedElement) => {
|
||||
if (ignoreFocusChanges) return;
|
||||
isOntologyFocused = (focusedElement === ontologyEl);
|
||||
@@ -9928,7 +10058,6 @@ const renderInput = (container, isFloating = false) => {
|
||||
linkSuggester.modifyInput = (input) => input.replace(/\./g, " ");
|
||||
}
|
||||
|
||||
// Accessibility / ARIA labels
|
||||
const ariaHelp = [
|
||||
`${getActionLabel(ACTION_ADD)} (Enter)`,
|
||||
`${getActionLabel(ACTION_ADD_FOLLOW)} ${getActionHotkeyString(ACTION_ADD_FOLLOW)}`,
|
||||
@@ -9988,7 +10117,6 @@ const renderInput = (container, isFloating = false) => {
|
||||
btn.onClick(() => performAction(ACTION_TOGGLE_CHECKBOX));
|
||||
}, true);
|
||||
|
||||
// Added calendar task date ontologies button
|
||||
addButton((btn) => {
|
||||
calendarBtn = btn;
|
||||
btn.setIcon("calendar");
|
||||
@@ -10862,6 +10990,34 @@ const registerStyles = () => {
|
||||
".mindmap-input-main { flex: 17; transition: flex-grow 0.3s ease; min-width: 0; }",
|
||||
".mindmap-input-ontology.is-focused { flex: 17; }",
|
||||
".mindmap-input-main.is-shrunk { flex: 1; }",
|
||||
// Drag Handle Styles
|
||||
".excalidraw-mindmap-ui .mindmap-drag-handle {",
|
||||
" position: absolute;",
|
||||
" right: 0;",
|
||||
" top: 0;",
|
||||
" bottom: 0;",
|
||||
" width: 20px;",
|
||||
" cursor: grab;",
|
||||
" display: flex;",
|
||||
" align-items: center;",
|
||||
" justify-content: center;",
|
||||
" opacity: 0.4;",
|
||||
" color: var(--text-muted);",
|
||||
" transition: opacity 0.2s ease, color 0.2s ease;",
|
||||
" background: var(--background-secondary);",
|
||||
" border-left: 1px solid var(--background-modifier-border);",
|
||||
" border-top-right-radius: 6px;",
|
||||
" border-bottom-right-radius: 6px;",
|
||||
"}",
|
||||
".excalidraw-mindmap-ui:focus-within .mindmap-drag-handle,",
|
||||
".excalidraw-mindmap-ui .mindmap-drag-handle:hover,",
|
||||
".excalidraw-mindmap-ui .mindmap-drag-handle:active {",
|
||||
" opacity: 1;",
|
||||
" color: var(--text-normal);",
|
||||
"}",
|
||||
".excalidraw-mindmap-ui.is-dragging .mindmap-drag-handle {",
|
||||
" cursor: grabbing;",
|
||||
"}"
|
||||
].join("\n");
|
||||
document.head.appendChild(styleEl);
|
||||
};
|
||||
@@ -10970,12 +11126,61 @@ const toggleDock = async ({
|
||||
headerEl.style.display = "none";
|
||||
modalEl.style.opacity = `${FLOAT_MODAL_OPACITY}`;
|
||||
modalEl.style.padding = "6px";
|
||||
modalEl.style.paddingRight = "26px"; // Make room for the drag handle
|
||||
modalEl.style.minHeight = "0px";
|
||||
modalEl.style.width = "fit-content";
|
||||
modalEl.style.height = "auto";
|
||||
modalEl.style.maxHeight = FLOAT_MODAL_MAX_HEIGHT;
|
||||
|
||||
if (isExcaliBrainView()) {
|
||||
modalEl.style.display = "none";
|
||||
}
|
||||
|
||||
const container = floatingInputModal.contentEl.createDiv();
|
||||
renderInput(container, true);
|
||||
|
||||
// Setup Drag Handle
|
||||
const dragHandle = modalEl.createDiv("mindmap-drag-handle");
|
||||
dragHandle.innerHTML = ea.obsidian.getIcon("grip-vertical").outerHTML;
|
||||
|
||||
let isDragging = false;
|
||||
let startX, startY, initialLeft, initialTop;
|
||||
|
||||
dragHandle.addEventListener("pointerdown", (e) => {
|
||||
isDragging = true;
|
||||
startX = e.clientX;
|
||||
startY = e.clientY;
|
||||
const rect = modalEl.getBoundingClientRect();
|
||||
initialLeft = rect.left;
|
||||
initialTop = rect.top;
|
||||
dragHandle.setPointerCapture(e.pointerId);
|
||||
modalEl.classList.add("is-dragging");
|
||||
e.preventDefault();
|
||||
});
|
||||
|
||||
dragHandle.addEventListener("pointermove", (e) => {
|
||||
if(!isDragging) return;
|
||||
const dx = e.clientX - startX;
|
||||
const dy = e.clientY - startY;
|
||||
modalEl.style.left = `${initialLeft + dx}px`;
|
||||
modalEl.style.top = `${initialTop + dy}px`;
|
||||
});
|
||||
|
||||
dragHandle.addEventListener("pointerup", (e) => {
|
||||
isDragging = false;
|
||||
dragHandle.releasePointerCapture(e.pointerId);
|
||||
modalEl.classList.remove("is-dragging");
|
||||
});
|
||||
|
||||
dragHandle.addEventListener("dblclick", (e) => {
|
||||
const { x, y } = ea.targetView.contentEl.getBoundingClientRect();
|
||||
const desktopShift = !!ea.targetView.contentEl.querySelector(".App-bottom-bar .App-toolbar") ?
|
||||
0 :
|
||||
(ea.targetView.contentEl.clientWidth < 1200 ? 36 : 0);
|
||||
modalEl.style.top = `${y + FLOAT_MODAL_OFFSET + desktopShift}px`;
|
||||
modalEl.style.left = `${x + FLOAT_MODAL_OFFSET}px`;
|
||||
});
|
||||
|
||||
setTimeout(() => {
|
||||
//the modalEl is repositioned after a delay
|
||||
//otherwise the event handlers in FloatingModal would override the move
|
||||
@@ -11419,7 +11624,7 @@ const openCalendarModal = async () => {
|
||||
};
|
||||
|
||||
leftNav.createSpan({
|
||||
text: `Date ${activeDateIndex + 1} of ${dates.length}`
|
||||
text: t("CALENDAR_DATE_INDEX", { index: activeDateIndex + 1, total: dates.length })
|
||||
});
|
||||
|
||||
const nextBtn = leftNav.createEl("button");
|
||||
@@ -11455,7 +11660,7 @@ const openCalendarModal = async () => {
|
||||
|
||||
// 1) Date picker input (Focus First)
|
||||
new ea.obsidian.Setting(contentEl)
|
||||
.setName("Date")
|
||||
.setName(t("CALENDAR_DATE_LABEL"))
|
||||
.addText(text => {
|
||||
dateInputComp = text;
|
||||
text.inputEl.type = "date";
|
||||
@@ -11482,7 +11687,7 @@ const openCalendarModal = async () => {
|
||||
|
||||
// 2) Field type configuration selector matching active schema ontology
|
||||
new ea.obsidian.Setting(contentEl)
|
||||
.setName("Date Type")
|
||||
.setName(t("CALENDAR_DATE_TYPE"))
|
||||
.addDropdown(dropdown => {
|
||||
typeDropdownComp = dropdown;
|
||||
if (uiOpts.mode === 'dataview') {
|
||||
@@ -11493,12 +11698,12 @@ const openCalendarModal = async () => {
|
||||
dropdown.addOption("done", "✅ [done:: ]");
|
||||
dropdown.addOption("cancelled", "❌ [cancelled:: ]");
|
||||
} else {
|
||||
dropdown.addOption("due", "📅 Due");
|
||||
dropdown.addOption("start", "🛫 Start");
|
||||
dropdown.addOption("scheduled", "⏳ Scheduled");
|
||||
dropdown.addOption("created", "➕ Created");
|
||||
dropdown.addOption("done", "✅ Done");
|
||||
dropdown.addOption("cancelled", "❌ Cancelled");
|
||||
dropdown.addOption("due", `📅 ${t("CALENDAR_DATETYPE_DUE")}`);
|
||||
dropdown.addOption("start", `🛫 ${t("CALENDAR_DATETYPE_START")}`);
|
||||
dropdown.addOption("scheduled", `⏳ ${t("CALENDAR_DATETYPE_SCHEDULED")}`);
|
||||
dropdown.addOption("created", `➕ ${t("CALENDAR_DATETYPE_CREATED")}`);
|
||||
dropdown.addOption("done", `✅ ${t("CALENDAR_DATETYPE_DONE")}`);
|
||||
dropdown.addOption("cancelled", `❌ ${t("CALENDAR_DATETYPE_CANCELLED")}`);
|
||||
}
|
||||
dropdown.setValue(activeDateObj.type);
|
||||
dropdown.onChange(val => {
|
||||
@@ -11508,14 +11713,14 @@ const openCalendarModal = async () => {
|
||||
|
||||
// 3) Priority selector mapped to native Tasks emojis
|
||||
new ea.obsidian.Setting(contentEl)
|
||||
.setName("Priority")
|
||||
.setName(t("CALENDAR_PRIORITY"))
|
||||
.addDropdown(dropdown => {
|
||||
dropdown.addOption("highest", "🔺 Highest");
|
||||
dropdown.addOption("high", "⏫ High");
|
||||
dropdown.addOption("medium", "🔼 Medium");
|
||||
dropdown.addOption("normal", " Normal");
|
||||
dropdown.addOption("low", "🔽 Low");
|
||||
dropdown.addOption("lowest", "⏬ Lowest");
|
||||
dropdown.addOption("highest", `🔺 ${t("CALENDAR_PRIORITY_HIGHEST")}`);
|
||||
dropdown.addOption("high", `⏫ ${t("CALENDAR_PRIORITY_HIGH")}`);
|
||||
dropdown.addOption("medium", `🔼 ${t("CALENDAR_PRIORITY_MEDIUM")}`);
|
||||
dropdown.addOption("normal", ` ${t("CALENDAR_PRIORITY_NORMAL")}`);
|
||||
dropdown.addOption("low", `🔽 ${t("CALENDAR_PRIORITY_LOW")}`);
|
||||
dropdown.addOption("lowest", `⏬ ${t("CALENDAR_PRIORITY_LOWEST")}`);
|
||||
dropdown.setValue(priority);
|
||||
dropdown.onChange(val => {
|
||||
priority = val;
|
||||
@@ -11524,15 +11729,44 @@ const openCalendarModal = async () => {
|
||||
|
||||
// 4) Recurrence free text input
|
||||
const recSetting = new ea.obsidian.Setting(contentEl)
|
||||
.setName("Recurrence")
|
||||
.setName(t("CALENDAR_RECURRENCE"))
|
||||
.addText(text => {
|
||||
text.setPlaceholder("every day")
|
||||
text.setPlaceholder(t("CALENDAR_RECURRENCE_PLACEHOLDER"))
|
||||
.setValue(recurrence)
|
||||
.onChange(val => {
|
||||
recurrence = val;
|
||||
});
|
||||
});
|
||||
recSetting.descEl.innerHTML = `e.g., 'every day', 'every 2 weeks' <br><a href="https://publish.obsidian.md/tasks/Getting+Started/Recurring+Tasks" target="_blank" tabindex="-1">Tasks recurrence docs</a>`;
|
||||
recSetting.descEl.innerHTML = t("CALENDAR_RECURRENCE_DESC");
|
||||
|
||||
// 5) Inject Node Link toggle
|
||||
const linkSettingsRow = new ea.obsidian.Setting(contentEl)
|
||||
.setName(t("CALENDAR_INJECT_LINK"))
|
||||
.setDesc(t("CALENDAR_INJECT_LINK_DESC"));
|
||||
|
||||
let aliasTextComp;
|
||||
linkSettingsRow.addToggle(toggle => {
|
||||
toggle.setValue(injectNodeLink)
|
||||
.onChange(val => {
|
||||
injectNodeLink = val;
|
||||
setVal(K_INJECT_LINK, val);
|
||||
dirty = true;
|
||||
aliasTextComp.inputEl.style.display = val ? "" : "none";
|
||||
});
|
||||
});
|
||||
linkSettingsRow.addText(text => {
|
||||
aliasTextComp = text;
|
||||
text.setPlaceholder(t("CALENDAR_ALIAS_PLACEHOLDER"))
|
||||
.setValue(nodeLinkAlias)
|
||||
.onChange(val => {
|
||||
nodeLinkAlias = val || "link";
|
||||
setVal(K_LINK_ALIAS, nodeLinkAlias);
|
||||
dirty = true;
|
||||
});
|
||||
text.inputEl.style.display = injectNodeLink ? "" : "none";
|
||||
text.inputEl.style.width = "100px";
|
||||
text.inputEl.style.marginLeft = "10px";
|
||||
});
|
||||
|
||||
// Controls button block
|
||||
const btnContainer = contentEl.createDiv({
|
||||
@@ -11542,15 +11776,20 @@ const openCalendarModal = async () => {
|
||||
});
|
||||
|
||||
const cancelBtn = btnContainer.createEl("button", {
|
||||
text: "Cancel"
|
||||
text: t("CALENDAR_BTN_CANCEL")
|
||||
});
|
||||
cancelBtn.onclick = () => modal.close();
|
||||
|
||||
const taskOnlyBtn = btnContainer.createEl("button", {
|
||||
text: t("CALENDAR_BTN_TASK_ONLY")
|
||||
});
|
||||
taskOnlyBtn.onclick = () => handleSave(false);
|
||||
|
||||
const saveBtn = btnContainer.createEl("button", {
|
||||
text: "Apply",
|
||||
text: t("CALENDAR_BTN_ADD_DATE_TASK"),
|
||||
cls: "mod-cta"
|
||||
});
|
||||
saveBtn.onclick = handleSave;
|
||||
saveBtn.onclick = () => handleSave(true);
|
||||
|
||||
// Date picker auto-open / focus
|
||||
setTimeout(() => {
|
||||
@@ -11565,66 +11804,83 @@ const openCalendarModal = async () => {
|
||||
}, 50);
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
const handleSave = async (includeDate = true) => {
|
||||
modal.close();
|
||||
|
||||
let tasksString = "";
|
||||
const validDates = dates.filter(d => d.date);
|
||||
|
||||
if (uiOpts.mode === 'dataview') {
|
||||
let priorityStr = "";
|
||||
const priorityMap = {
|
||||
'highest': '🔺',
|
||||
'high': '⏫',
|
||||
'medium': '🔼',
|
||||
'normal': '',
|
||||
'low': '🔽',
|
||||
'lowest': '⏬'
|
||||
};
|
||||
if (priority !== 'normal') priorityStr = priorityMap[priority];
|
||||
if (includeDate) {
|
||||
const validDates = dates.filter(d => d.date);
|
||||
if (uiOpts.mode === 'dataview') {
|
||||
let priorityStr = "";
|
||||
const priorityMap = {
|
||||
'highest': '🔺',
|
||||
'high': '⏫',
|
||||
'medium': '🔼',
|
||||
'normal': '',
|
||||
'low': '🔽',
|
||||
'lowest': '⏬'
|
||||
};
|
||||
if (priority !== 'normal') priorityStr = priorityMap[priority];
|
||||
|
||||
let dateStrs = validDates.map(d => `[${d.type}:: ${d.date}]`);
|
||||
let recStr = recurrence ? `[recurrence:: ${recurrence}]` : "";
|
||||
let dateStrs = validDates.map(d => `[${d.type}:: ${d.date}]`);
|
||||
let recStr = recurrence ? `[recurrence:: ${recurrence}]` : "";
|
||||
|
||||
const parts = [priorityStr, ...dateStrs, recStr].filter(Boolean);
|
||||
if (parts.length > 0) tasksString = " " + parts.join(" ");
|
||||
} else {
|
||||
let priorityStr = "";
|
||||
const priorityMap = {
|
||||
'highest': ' 🔺',
|
||||
'high': ' ⏫',
|
||||
'medium': ' 🔼',
|
||||
'normal': '',
|
||||
'low': ' 🔽',
|
||||
'lowest': ' ⏬'
|
||||
};
|
||||
priorityStr = priorityMap[priority] || "";
|
||||
const parts = [priorityStr, ...dateStrs, recStr].filter(Boolean);
|
||||
if (parts.length > 0) tasksString = " " + parts.join(" ");
|
||||
} else {
|
||||
let priorityStr = "";
|
||||
const priorityMap = {
|
||||
'highest': ' 🔺',
|
||||
'high': ' ⏫',
|
||||
'medium': ' 🔼',
|
||||
'normal': '',
|
||||
'low': ' 🔽',
|
||||
'lowest': ' ⏬'
|
||||
};
|
||||
priorityStr = priorityMap[priority] || "";
|
||||
|
||||
const emojiMap = {
|
||||
'due': '📅',
|
||||
'start': '🛫',
|
||||
'scheduled': '⏳',
|
||||
'created': '➕',
|
||||
'done': '✅',
|
||||
'cancelled': '❌'
|
||||
};
|
||||
let dateStrs = validDates.map(d => ` ${emojiMap[d.type]} ${d.date}`);
|
||||
let recStr = recurrence ? ` 🔁 ${recurrence}` : "";
|
||||
const emojiMap = {
|
||||
'due': '📅',
|
||||
'start': '🛫',
|
||||
'scheduled': '⏳',
|
||||
'created': '➕',
|
||||
'done': '✅',
|
||||
'cancelled': '❌'
|
||||
};
|
||||
let dateStrs = validDates.map(d => ` ${emojiMap[d.type]} ${d.date}`);
|
||||
let recStr = recurrence ? ` 🔁 ${recurrence}` : "";
|
||||
|
||||
tasksString = `${priorityStr}${dateStrs.join("")}${recStr}`;
|
||||
tasksString = `${priorityStr}${dateStrs.join("")}${recStr}`;
|
||||
}
|
||||
}
|
||||
|
||||
const taskRegex = /^- \[([ xX])\] (.*)/s;
|
||||
const match = targetText.match(taskRegex);
|
||||
|
||||
let cleanText = cleanTasksString(match ? match[2] : targetText);
|
||||
|
||||
// Ensure we don't duplicate an existing auto-generated link at the end
|
||||
const linkRegex = /\s*\(\[\[[^\]]+#\^group=[a-zA-Z0-9_-]+\|[^\]]+\]\]\)$/;
|
||||
if (linkRegex.test(cleanText)) {
|
||||
cleanText = cleanText.replace(linkRegex, "");
|
||||
}
|
||||
|
||||
let finalPrefix = match ? `- [${match[1]}] ` : "- [ ] ";
|
||||
|
||||
let newText = `${finalPrefix}${cleanText}${tasksString}`;
|
||||
|
||||
if (injectNodeLink) {
|
||||
if (isInputEl) {
|
||||
newText += ` __NODE_LINK_PLACEHOLDER__`;
|
||||
} else {
|
||||
const file = app.workspace.getActiveFile();
|
||||
const fileName = file ? file.basename : "";
|
||||
newText += ` ([[${fileName}#^group=${textElId}|${nodeLinkAlias}]])`;
|
||||
}
|
||||
}
|
||||
|
||||
if (isInputEl) {
|
||||
inputEl.value = newText;
|
||||
debugger;
|
||||
updateUI();
|
||||
} else {
|
||||
const all = ea.getViewElements();
|
||||
@@ -11661,7 +11917,7 @@ const openCalendarModal = async () => {
|
||||
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
handleSave();
|
||||
handleSave(true);
|
||||
}
|
||||
// Prevent Escape from propagating to the underlying floating modal or canvas
|
||||
if (e.key === "Escape") {
|
||||
@@ -13148,6 +13404,7 @@ const handleCanvasPointerDown = (e) => {
|
||||
}, 50);
|
||||
};
|
||||
|
||||
/* --- Initialization Logic --- */
|
||||
/* --- Initialization Logic --- */
|
||||
ea.createSidepanelTab(t("DOCK_TITLE"), true, true).then((tab) => {
|
||||
|
||||
@@ -13279,9 +13536,15 @@ ea.createSidepanelTab(t("DOCK_TITLE"), true, true).then((tab) => {
|
||||
const {
|
||||
modalEl
|
||||
} = floatingInputModal
|
||||
if (modalEl.style.display === "none") {
|
||||
modalEl.style.display = "";
|
||||
|
||||
if (isExcaliBrainView()) {
|
||||
modalEl.style.display = "none";
|
||||
} else {
|
||||
if (modalEl.style.display === "none") {
|
||||
modalEl.style.display = "";
|
||||
}
|
||||
}
|
||||
|
||||
if (ea.targetView && modalEl.ownerDocument !== ea.targetView.ownerDocument) {
|
||||
ea.targetView.ownerDocument.body.appendChild(modalEl);
|
||||
linkSuggester?.close();
|
||||
|
||||
+535
-499
File diff suppressed because it is too large.
Load diff
@@ -1 +1,682 @@
|
||||
[{"fname":"Mindmap connector.md","mtime":1658686599427},{"fname":"Mindmap connector.svg","mtime":1658686599427},{"fname":"Add Connector Point.md","mtime":1735420748564},{"fname":"Add Connector Point.svg","mtime":1645944722000},{"fname":"Add Link to Existing File and Open.md","mtime":1647807918345},{"fname":"Add Link to Existing File and Open.svg","mtime":1645964261000},{"fname":"Add Link to New Page and Open.md","mtime":1654168862138},{"fname":"Add Link to New Page and Open.svg","mtime":1645960639000},{"fname":"Add Next Step in Process.md","mtime":1688304760357},{"fname":"Add Next Step in Process.svg","mtime":1645960639000},{"fname":"Box Each Selected Groups.md","mtime":1645305706000},{"fname":"Box Each Selected Groups.svg","mtime":1645967510000},{"fname":"Box Selected Elements.md","mtime":1645305706000},{"fname":"Box Selected Elements.svg","mtime":1645960639000},{"fname":"Change shape of selected elements.md","mtime":1652701169236},{"fname":"Change shape of selected elements.svg","mtime":1645960775000},{"fname":"Connect elements.md","mtime":1645305706000},{"fname":"Connect elements.svg","mtime":1645960639000},{"fname":"Convert freedraw to line.md","mtime":1645305706000},{"fname":"Convert freedraw to line.svg","mtime":1645960639000},{"fname":"Convert selected text elements to sticky notes.md","mtime":1670169501383},{"fname":"Convert selected text elements to sticky notes.svg","mtime":1645960639000},{"fname":"Convert text to link with folder and alias.md","mtime":1641639819000},{"fname":"Convert text to link with folder and alias.svg","mtime":1645960639000},{"fname":"Copy Selected Element Styles to Global.md","mtime":1642232088000},{"fname":"Copy Selected Element Styles to Global.svg","mtime":1645960639000},{"fname":"Create new markdown file and embed into active drawing.md","mtime":1640866935000},{"fname":"Create new markdown file and embed into active drawing.svg","mtime":1645960639000},{"fname":"Darken background color.md","mtime":1663059051059},{"fname":"Darken background color.svg","mtime":1645960639000},{"fname":"Elbow connectors.md","mtime":1671126911490},{"fname":"Elbow connectors.svg","mtime":1645960639000},{"fname":"Expand rectangles horizontally keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles horizontally keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles horizontally.md","mtime":1644950235000},{"fname":"Expand rectangles horizontally.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles vertically keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically.md","mtime":1658686599427},{"fname":"Expand rectangles vertically.svg","mtime":1645967510000},{"fname":"Fixed horizontal distance between centers.md","mtime":1646743234000},{"fname":"Fixed horizontal distance between centers.svg","mtime":1645960639000},{"fname":"Fixed inner distance.md","mtime":1646743234000},{"fname":"Fixed inner distance.svg","mtime":1645960639000},{"fname":"Fixed spacing.md","mtime":1646743234000},{"fname":"Fixed spacing.svg","mtime":1645967510000},{"fname":"Fixed vertical distance between centers.md","mtime":1646743234000},{"fname":"Fixed vertical distance between centers.svg","mtime":1645967510000},{"fname":"Fixed vertical distance.md","mtime":1646743234000},{"fname":"Fixed vertical distance.svg","mtime":1645967510000},{"fname":"Lighten background color.md","mtime":1663059051059},{"fname":"Lighten background color.svg","mtime":1645959546000},{"fname":"Modify background color opacity.md","mtime":1644924415000},{"fname":"Modify background color opacity.svg","mtime":1645944722000},{"fname":"Normalize Selected Arrows.md","mtime":1670403743278},{"fname":"Normalize Selected Arrows.svg","mtime":1645960639000},{"fname":"Organic Line.md","mtime":1672920172531},{"fname":"Organic Line.svg","mtime":1645964261000},{"fname":"Organic Line Legacy.md","mtime":1690607372668},{"fname":"Organic Line Legacy.svg","mtime":1690607372668},{"fname":"README.md","mtime":1645175700000},{"fname":"Repeat Elements.md","mtime":1663059051059},{"fname":"Repeat Elements.svg","mtime":1645960639000},{"fname":"Reverse arrows.md","mtime":1645305706000},{"fname":"Reverse arrows.svg","mtime":1645960639000},{"fname":"Scribble Helper.md","mtime":1767536720161},{"fname":"Scribble Helper.svg","mtime":1645944722000},{"fname":"Select Elements of Type.md","mtime":1643464321000},{"fname":"Select Elements of Type.svg","mtime":1645960639000},{"fname":"Set Dimensions.md","mtime":1645305706000},{"fname":"Set Dimensions.svg","mtime":1645944722000},{"fname":"Set Font Family.md","mtime":1645305706000},{"fname":"Set Font Family.svg","mtime":1645944722000},{"fname":"Set Grid.md","mtime":1693725826368},{"fname":"Set Grid.svg","mtime":1645960639000},{"fname":"Set Link Alias.md","mtime":1645305706000},{"fname":"Set Link Alias.svg","mtime":1645960639000},{"fname":"Set Stroke Width of Selected Elements.md","mtime":1748189277Line truncated
|
||||
[
|
||||
{
|
||||
"fname": "Mindmap connector.md",
|
||||
"mtime": 1658686599427
|
||||
},
|
||||
{
|
||||
"fname": "Mindmap connector.svg",
|
||||
"mtime": 1658686599427
|
||||
},
|
||||
{
|
||||
"fname": "Add Connector Point.md",
|
||||
"mtime": 1735420748564
|
||||
},
|
||||
{
|
||||
"fname": "Add Connector Point.svg",
|
||||
"mtime": 1645944722000
|
||||
},
|
||||
{
|
||||
"fname": "Add Link to Existing File and Open.md",
|
||||
"mtime": 1647807918345
|
||||
},
|
||||
{
|
||||
"fname": "Add Link to Existing File and Open.svg",
|
||||
"mtime": 1645964261000
|
||||
},
|
||||
{
|
||||
"fname": "Add Link to New Page and Open.md",
|
||||
"mtime": 1654168862138
|
||||
},
|
||||
{
|
||||
"fname": "Add Link to New Page and Open.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Add Next Step in Process.md",
|
||||
"mtime": 1688304760357
|
||||
},
|
||||
{
|
||||
"fname": "Add Next Step in Process.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Box Each Selected Groups.md",
|
||||
"mtime": 1645305706000
|
||||
},
|
||||
{
|
||||
"fname": "Box Each Selected Groups.svg",
|
||||
"mtime": 1645967510000
|
||||
},
|
||||
{
|
||||
"fname": "Box Selected Elements.md",
|
||||
"mtime": 1645305706000
|
||||
},
|
||||
{
|
||||
"fname": "Box Selected Elements.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Change shape of selected elements.md",
|
||||
"mtime": 1652701169236
|
||||
},
|
||||
{
|
||||
"fname": "Change shape of selected elements.svg",
|
||||
"mtime": 1645960775000
|
||||
},
|
||||
{
|
||||
"fname": "Connect elements.md",
|
||||
"mtime": 1645305706000
|
||||
},
|
||||
{
|
||||
"fname": "Connect elements.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Convert freedraw to line.md",
|
||||
"mtime": 1645305706000
|
||||
},
|
||||
{
|
||||
"fname": "Convert freedraw to line.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Convert selected text elements to sticky notes.md",
|
||||
"mtime": 1670169501383
|
||||
},
|
||||
{
|
||||
"fname": "Convert selected text elements to sticky notes.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Convert text to link with folder and alias.md",
|
||||
"mtime": 1641639819000
|
||||
},
|
||||
{
|
||||
"fname": "Convert text to link with folder and alias.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Copy Selected Element Styles to Global.md",
|
||||
"mtime": 1642232088000
|
||||
},
|
||||
{
|
||||
"fname": "Copy Selected Element Styles to Global.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Create new markdown file and embed into active drawing.md",
|
||||
"mtime": 1640866935000
|
||||
},
|
||||
{
|
||||
"fname": "Create new markdown file and embed into active drawing.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Darken background color.md",
|
||||
"mtime": 1663059051059
|
||||
},
|
||||
{
|
||||
"fname": "Darken background color.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Elbow connectors.md",
|
||||
"mtime": 1671126911490
|
||||
},
|
||||
{
|
||||
"fname": "Elbow connectors.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Expand rectangles horizontally keep text centered.md",
|
||||
"mtime": 1646563692000
|
||||
},
|
||||
{
|
||||
"fname": "Expand rectangles horizontally keep text centered.svg",
|
||||
"mtime": 1645967510000
|
||||
},
|
||||
{
|
||||
"fname": "Expand rectangles horizontally.md",
|
||||
"mtime": 1644950235000
|
||||
},
|
||||
{
|
||||
"fname": "Expand rectangles horizontally.svg",
|
||||
"mtime": 1645967510000
|
||||
},
|
||||
{
|
||||
"fname": "Expand rectangles vertically keep text centered.md",
|
||||
"mtime": 1646563692000
|
||||
},
|
||||
{
|
||||
"fname": "Expand rectangles vertically keep text centered.svg",
|
||||
"mtime": 1645967510000
|
||||
},
|
||||
{
|
||||
"fname": "Expand rectangles vertically.md",
|
||||
"mtime": 1658686599427
|
||||
},
|
||||
{
|
||||
"fname": "Expand rectangles vertically.svg",
|
||||
"mtime": 1645967510000
|
||||
},
|
||||
{
|
||||
"fname": "Fixed horizontal distance between centers.md",
|
||||
"mtime": 1646743234000
|
||||
},
|
||||
{
|
||||
"fname": "Fixed horizontal distance between centers.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Fixed inner distance.md",
|
||||
"mtime": 1646743234000
|
||||
},
|
||||
{
|
||||
"fname": "Fixed inner distance.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Fixed spacing.md",
|
||||
"mtime": 1646743234000
|
||||
},
|
||||
{
|
||||
"fname": "Fixed spacing.svg",
|
||||
"mtime": 1645967510000
|
||||
},
|
||||
{
|
||||
"fname": "Fixed vertical distance between centers.md",
|
||||
"mtime": 1646743234000
|
||||
},
|
||||
{
|
||||
"fname": "Fixed vertical distance between centers.svg",
|
||||
"mtime": 1645967510000
|
||||
},
|
||||
{
|
||||
"fname": "Fixed vertical distance.md",
|
||||
"mtime": 1646743234000
|
||||
},
|
||||
{
|
||||
"fname": "Fixed vertical distance.svg",
|
||||
"mtime": 1645967510000
|
||||
},
|
||||
{
|
||||
"fname": "Lighten background color.md",
|
||||
"mtime": 1663059051059
|
||||
},
|
||||
{
|
||||
"fname": "Lighten background color.svg",
|
||||
"mtime": 1645959546000
|
||||
},
|
||||
{
|
||||
"fname": "Modify background color opacity.md",
|
||||
"mtime": 1644924415000
|
||||
},
|
||||
{
|
||||
"fname": "Modify background color opacity.svg",
|
||||
"mtime": 1645944722000
|
||||
},
|
||||
{
|
||||
"fname": "Normalize Selected Arrows.md",
|
||||
"mtime": 1670403743278
|
||||
},
|
||||
{
|
||||
"fname": "Normalize Selected Arrows.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Organic Line.md",
|
||||
"mtime": 1672920172531
|
||||
},
|
||||
{
|
||||
"fname": "Organic Line.svg",
|
||||
"mtime": 1645964261000
|
||||
},
|
||||
{
|
||||
"fname": "Organic Line Legacy.md",
|
||||
"mtime": 1690607372668
|
||||
},
|
||||
{
|
||||
"fname": "Organic Line Legacy.svg",
|
||||
"mtime": 1690607372668
|
||||
},
|
||||
{
|
||||
"fname": "README.md",
|
||||
"mtime": 1645175700000
|
||||
},
|
||||
{
|
||||
"fname": "Repeat Elements.md",
|
||||
"mtime": 1663059051059
|
||||
},
|
||||
{
|
||||
"fname": "Repeat Elements.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Reverse arrows.md",
|
||||
"mtime": 1645305706000
|
||||
},
|
||||
{
|
||||
"fname": "Reverse arrows.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Scribble Helper.md",
|
||||
"mtime": 1767536720161
|
||||
},
|
||||
{
|
||||
"fname": "Scribble Helper.svg",
|
||||
"mtime": 1645944722000
|
||||
},
|
||||
{
|
||||
"fname": "Select Elements of Type.md",
|
||||
"mtime": 1643464321000
|
||||
},
|
||||
{
|
||||
"fname": "Select Elements of Type.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Set Dimensions.md",
|
||||
"mtime": 1645305706000
|
||||
},
|
||||
{
|
||||
"fname": "Set Dimensions.svg",
|
||||
"mtime": 1645944722000
|
||||
},
|
||||
{
|
||||
"fname": "Set Font Family.md",
|
||||
"mtime": 1645305706000
|
||||
},
|
||||
{
|
||||
"fname": "Set Font Family.svg",
|
||||
"mtime": 1645944722000
|
||||
},
|
||||
{
|
||||
"fname": "Set Grid.md",
|
||||
"mtime": 1693725826368
|
||||
},
|
||||
{
|
||||
"fname": "Set Grid.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Set Link Alias.md",
|
||||
"mtime": 1645305706000
|
||||
},
|
||||
{
|
||||
"fname": "Set Link Alias.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Set Stroke Width of Selected Elements.md",
|
||||
"mtime": 1748189277103
|
||||
},
|
||||
{
|
||||
"fname": "Set Stroke Width of Selected Elements.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Set Text Alignment.md",
|
||||
"mtime": 1645305706000
|
||||
},
|
||||
{
|
||||
"fname": "Set Text Alignment.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Set background color of unclosed line object by adding a shadow clone.md",
|
||||
"mtime": 1681665030892
|
||||
},
|
||||
{
|
||||
"fname": "Set background color of unclosed line object by adding a shadow clone.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "Split text by lines.md",
|
||||
"mtime": 1773076990493
|
||||
},
|
||||
{
|
||||
"fname": "Split text by lines.svg",
|
||||
"mtime": 1645944722000
|
||||
},
|
||||
{
|
||||
"fname": "Zoom to Fit Selected Elements.md",
|
||||
"mtime": 1640770602000
|
||||
},
|
||||
{
|
||||
"fname": "Zoom to Fit Selected Elements.svg",
|
||||
"mtime": 1645960639000
|
||||
},
|
||||
{
|
||||
"fname": "directory-info.json",
|
||||
"mtime": 1646583437000
|
||||
},
|
||||
{
|
||||
"fname": "index-new.md",
|
||||
"mtime": 1645986149000
|
||||
},
|
||||
{
|
||||
"fname": "index.md",
|
||||
"mtime": 1645175700000
|
||||
},
|
||||
{
|
||||
"fname": "Grid Selected Images.md",
|
||||
"mtime": 1701630797839
|
||||
},
|
||||
{
|
||||
"fname": "Grid Selected Images.svg",
|
||||
"mtime": 1649614401982
|
||||
},
|
||||
{
|
||||
"fname": "Palette loader.md",
|
||||
"mtime": 1686511890942
|
||||
},
|
||||
{
|
||||
"fname": "Palette loader.svg",
|
||||
"mtime": 1649614401982
|
||||
},
|
||||
{
|
||||
"fname": "Rename Image.md",
|
||||
"mtime": 1663678478785
|
||||
},
|
||||
{
|
||||
"fname": "Rename Image.svg",
|
||||
"mtime": 1663678478785
|
||||
},
|
||||
{
|
||||
"fname": "Text to Path.md",
|
||||
"mtime": 1775680971589
|
||||
},
|
||||
{
|
||||
"fname": "Text to Path.svg",
|
||||
"mtime": 1748193397572
|
||||
},
|
||||
{
|
||||
"fname": "Deconstruct selected elements into new drawing.md",
|
||||
"mtime": 1771009405621
|
||||
},
|
||||
{
|
||||
"fname": "Deconstruct selected elements into new drawing.svg",
|
||||
"mtime": 1668541145255
|
||||
},
|
||||
{
|
||||
"fname": "Slideshow.md",
|
||||
"mtime": 1764868375422
|
||||
},
|
||||
{
|
||||
"fname": "Slideshow.svg",
|
||||
"mtime": 1670017348333
|
||||
},
|
||||
{
|
||||
"fname": "Auto Layout.md",
|
||||
"mtime": 1670403743278
|
||||
},
|
||||
{
|
||||
"fname": "Auto Layout.svg",
|
||||
"mtime": 1670175947081
|
||||
},
|
||||
{
|
||||
"fname": "Uniform size.md",
|
||||
"mtime": 1670175947081
|
||||
},
|
||||
{
|
||||
"fname": "Uniform size.svg",
|
||||
"mtime": 1670175947081
|
||||
},
|
||||
{
|
||||
"fname": "Mindmap format.md",
|
||||
"mtime": 1684484694228
|
||||
},
|
||||
{
|
||||
"fname": "Mindmap format.svg",
|
||||
"mtime": 1674944958059
|
||||
},
|
||||
{
|
||||
"fname": "Text to Sticky Notes.md",
|
||||
"mtime": 1678537561724
|
||||
},
|
||||
{
|
||||
"fname": "Text to Sticky Notes.svg",
|
||||
"mtime": 1678537561724
|
||||
},
|
||||
{
|
||||
"fname": "Folder Note Core - Make Current Drawing a Folder.md",
|
||||
"mtime": 1678973697470
|
||||
},
|
||||
{
|
||||
"fname": "Folder Note Core - Make Current Drawing a Folder.svg",
|
||||
"mtime": 1678973697470
|
||||
},
|
||||
{
|
||||
"fname": "Invert colors.md",
|
||||
"mtime": 1761230648413
|
||||
},
|
||||
{
|
||||
"fname": "Invert colors.svg",
|
||||
"mtime": 1678973697470
|
||||
},
|
||||
{
|
||||
"fname": "PDF Page Text to Clipboard.md",
|
||||
"mtime": 1683984041712
|
||||
},
|
||||
{
|
||||
"fname": "PDF Page Text to Clipboard.svg",
|
||||
"mtime": 1680418321236
|
||||
},
|
||||
{
|
||||
"fname": "Excalidraw Collaboration Frame.md",
|
||||
"mtime": 1767536720161
|
||||
},
|
||||
{
|
||||
"fname": "Excalidraw Collaboration Frame.svg",
|
||||
"mtime": 1687881495985
|
||||
},
|
||||
{
|
||||
"fname": "Create DrawIO file.md",
|
||||
"mtime": 1688243858267
|
||||
},
|
||||
{
|
||||
"fname": "Create DrawIO file.svg",
|
||||
"mtime": 1688243858267
|
||||
},
|
||||
{
|
||||
"fname": "Ellipse Selected Elements.md",
|
||||
"mtime": 1690131476331
|
||||
},
|
||||
{
|
||||
"fname": "Ellipse Selected Elements.svg",
|
||||
"mtime": 1690131476331
|
||||
},
|
||||
{
|
||||
"fname": "Select Similar Elements.md",
|
||||
"mtime": 1736077716908
|
||||
},
|
||||
{
|
||||
"fname": "Select Similar Elements.svg",
|
||||
"mtime": 1691270949338
|
||||
},
|
||||
{
|
||||
"fname": "Toggle Grid.md",
|
||||
"mtime": 1692125382945
|
||||
},
|
||||
{
|
||||
"fname": "Toggle Grid.svg",
|
||||
"mtime": 1692124753386
|
||||
},
|
||||
{
|
||||
"fname": "Split Ellipse.md",
|
||||
"mtime": 1747585400113
|
||||
},
|
||||
{
|
||||
"fname": "Split Ellipse.svg",
|
||||
"mtime": 1693134104356
|
||||
},
|
||||
{
|
||||
"fname": "Text Aura.md",
|
||||
"mtime": 1693731979540
|
||||
},
|
||||
{
|
||||
"fname": "Text Aura.svg",
|
||||
"mtime": 1693731979540
|
||||
},
|
||||
{
|
||||
"fname": "Boolean Operations.md",
|
||||
"mtime": 1748278607255
|
||||
},
|
||||
{
|
||||
"fname": "Boolean Operations.svg",
|
||||
"mtime": 1695746839537
|
||||
},
|
||||
{
|
||||
"fname": "Concatenate lines.md",
|
||||
"mtime": 1736073478644
|
||||
},
|
||||
{
|
||||
"fname": "Concatenate lines.svg",
|
||||
"mtime": 1696175301525
|
||||
},
|
||||
{
|
||||
"fname": "GPT-Draw-a-UI.md",
|
||||
"mtime": 1703324727900
|
||||
},
|
||||
{
|
||||
"fname": "GPT-Draw-a-UI.svg",
|
||||
"mtime": 1700511998048
|
||||
},
|
||||
{
|
||||
"fname": "ExcaliAI.md",
|
||||
"mtime": 1779295681335
|
||||
},
|
||||
{
|
||||
"fname": "ExcaliAI.svg",
|
||||
"mtime": 1701011028767
|
||||
},
|
||||
{
|
||||
"fname": "Repeat Texts.md",
|
||||
"mtime": 1701969627758
|
||||
},
|
||||
{
|
||||
"fname": "Repeat Texts.svg",
|
||||
"mtime": 1701969627758
|
||||
},
|
||||
{
|
||||
"fname": "Relative Font Size Cycle.md",
|
||||
"mtime": 1701969627758
|
||||
},
|
||||
{
|
||||
"fname": "Relative Font Size Cycle.svg",
|
||||
"mtime": 1701969627758
|
||||
},
|
||||
{
|
||||
"fname": "Golden Ratio.md",
|
||||
"mtime": 1725174200469
|
||||
},
|
||||
{
|
||||
"fname": "Golden Ratio.svg",
|
||||
"mtime": 1702812404286
|
||||
},
|
||||
{
|
||||
"fname": "Crop Vintage Mask.md",
|
||||
"mtime": 1706565166174
|
||||
},
|
||||
{
|
||||
"fname": "Crop Vintage Mask.svg",
|
||||
"mtime": 1705836797730
|
||||
},
|
||||
{
|
||||
"fname": "Custom Zoom.md",
|
||||
"mtime": 1710424027192
|
||||
},
|
||||
{
|
||||
"fname": "Custom Zoom.svg",
|
||||
"mtime": 1710424027192
|
||||
},
|
||||
{
|
||||
"fname": "Excalidraw Writing Machine.md",
|
||||
"mtime": 1769960863134
|
||||
},
|
||||
{
|
||||
"fname": "Excalidraw Writing Machine.svg",
|
||||
"mtime": 1724356709706
|
||||
},
|
||||
{
|
||||
"fname": "Reset LaTeX Size.md",
|
||||
"mtime": 1725296010813
|
||||
},
|
||||
{
|
||||
"fname": "Reset LaTeX Size.svg",
|
||||
"mtime": 1725296010813
|
||||
},
|
||||
{
|
||||
"fname": "Shade Master.md",
|
||||
"mtime": 1779643017184
|
||||
},
|
||||
{
|
||||
"fname": "Shade Master.svg",
|
||||
"mtime": 1735252821829
|
||||
},
|
||||
{
|
||||
"fname": "Image Occlusion.md",
|
||||
"mtime": 1779555635845
|
||||
},
|
||||
{
|
||||
"fname": "Image Occlusion.svg",
|
||||
"mtime": 1735465948353
|
||||
},
|
||||
{
|
||||
"fname": "Full-Year Calendar Generator.md",
|
||||
"mtime": 1735465948353
|
||||
},
|
||||
{
|
||||
"fname": "Full-Year Calendar Generator.svg",
|
||||
"mtime": 1735465948353
|
||||
},
|
||||
{
|
||||
"fname": "Printable Layout Wizard.md",
|
||||
"mtime": 1755349206019
|
||||
},
|
||||
{
|
||||
"fname": "Printable Layout Wizard.svg",
|
||||
"mtime": 1753293096307
|
||||
},
|
||||
{
|
||||
"fname": "Palm Guard.md",
|
||||
"mtime": 1773670411373
|
||||
},
|
||||
{
|
||||
"fname": "Palm Guard.svg",
|
||||
"mtime": 1754718656757
|
||||
},
|
||||
{
|
||||
"fname": "Mindmap Builder.md",
|
||||
"mtime": 1781460603530
|
||||
},
|
||||
{
|
||||
"fname": "Mindmap Builder.svg",
|
||||
"mtime": 1766352440627
|
||||
},
|
||||
{
|
||||
"fname": "Linear Calendar Generator.md",
|
||||
"mtime": 1766386098306
|
||||
},
|
||||
{
|
||||
"fname": "Linear Calendar Generator.svg",
|
||||
"mtime": 1766386098306
|
||||
},
|
||||
{
|
||||
"fname": "Capture Note.md",
|
||||
"mtime": 1780986335837
|
||||
},
|
||||
{
|
||||
"fname": "Capture Note.svg",
|
||||
"mtime": 1780256122182
|
||||
},
|
||||
{
|
||||
"fname": "Color Scheme Manager.md",
|
||||
"mtime": 1781294249453
|
||||
},
|
||||
{
|
||||
"fname": "Color Scheme Manager.svg",
|
||||
"mtime": 1780595297314
|
||||
}
|
||||
]
|
||||
@@ -134,6 +134,7 @@ These are the scripts I use most often. I tried to order them by importance, but
|
||||
| | |
|
||||
|----|-----|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Change%20shape%20of%20selected%20elements.svg"/></div>|[[#Change shape of selected elements]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Color%20Scheme%20Manager.svg"/></div>|[[#Color Scheme Manager]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Darken%20background%20color.svg"/></div>|[[#Darken background color]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Invert%20colors.svg"/></div>|[[#Invert colors]]|
|
||||
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Lighten%20background%20color.svg"/></div>|[[#Lighten background color]]|
|
||||
@@ -277,6 +278,12 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Change%20shape%20of%20selected%20elements.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">The script allows you to change the shape and fill style of selected Rectangles, Diamonds, Ellipses, Lines, Arrows and Freedraw.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-change-shape.jpg'></td></tr></table>
|
||||
|
||||
## Color Scheme Manager
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Color%20Scheme%20Manager.md
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/iwanhoogendoorn'>@iwanhoogendoorn</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Color%20Scheme%20Manager.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Swap the entire Stroke and Background/Fill colour palettes between named, categorized themes (Cloud Providers, Code Editors, Tech Brands, Design Systems, Nature, and more) from a docked side panel. Applying a theme recolours your selection (or sets the active colour) and repaints the native picker — both the quick-pick rows and the extended 3×5 grid with shades. Create your own schemes, import from a flat hex list, a labelled STROKE/FILL text format, or a raw appState colorPalette JSON (paste or .txt/.json file), hand-pick a custom picker, and export the current palette. When the MindMap Builder script is installed, an optional toggle recolours mind maps branch-by-branch. The canvas background is always left white.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/color-scheme-manager.gif' style="width:560px;"></td></tr></table>
|
||||
|
||||
## Concatenate lines
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Concatenate%20lines.md
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
const { FlatCompat } = require("@eslint/eslintrc");
|
||||
|
||||
const compat = new FlatCompat({
|
||||
baseDirectory: __dirname,
|
||||
});
|
||||
|
||||
const legacyConfig = require("./.eslintrc.json");
|
||||
|
||||
module.exports = (async () => {
|
||||
const { default: obsidianmd } = await import("eslint-plugin-obsidianmd");
|
||||
const tsRulesOffForJs = Object.fromEntries(
|
||||
[
|
||||
"@typescript-eslint/await-thenable",
|
||||
"@typescript-eslint/ban-ts-comment",
|
||||
"@typescript-eslint/no-array-constructor",
|
||||
"@typescript-eslint/no-array-delete",
|
||||
"@typescript-eslint/no-base-to-string",
|
||||
"@typescript-eslint/no-deprecated",
|
||||
"@typescript-eslint/no-duplicate-enum-values",
|
||||
"@typescript-eslint/no-duplicate-type-constituents",
|
||||
"@typescript-eslint/no-empty-object-type",
|
||||
"@typescript-eslint/no-explicit-any",
|
||||
"@typescript-eslint/no-extra-non-null-assertion",
|
||||
"@typescript-eslint/no-floating-promises",
|
||||
"@typescript-eslint/no-for-in-array",
|
||||
"@typescript-eslint/no-implied-eval",
|
||||
"@typescript-eslint/no-misused-new",
|
||||
"@typescript-eslint/no-misused-promises",
|
||||
"@typescript-eslint/no-namespace",
|
||||
"@typescript-eslint/no-non-null-asserted-optional-chain",
|
||||
"@typescript-eslint/no-redundant-type-constituents",
|
||||
"@typescript-eslint/no-require-imports",
|
||||
"@typescript-eslint/no-this-alias",
|
||||
"@typescript-eslint/no-unnecessary-type-assertion",
|
||||
"@typescript-eslint/no-unnecessary-type-constraint",
|
||||
"@typescript-eslint/no-unsafe-argument",
|
||||
"@typescript-eslint/no-unsafe-assignment",
|
||||
"@typescript-eslint/no-unsafe-call",
|
||||
"@typescript-eslint/no-unsafe-declaration-merging",
|
||||
"@typescript-eslint/no-unsafe-enum-comparison",
|
||||
"@typescript-eslint/no-unsafe-function-type",
|
||||
"@typescript-eslint/no-unsafe-member-access",
|
||||
"@typescript-eslint/no-unsafe-return",
|
||||
"@typescript-eslint/no-unsafe-unary-minus",
|
||||
"@typescript-eslint/no-unused-expressions",
|
||||
"@typescript-eslint/no-unused-vars",
|
||||
"@typescript-eslint/no-wrapper-object-types",
|
||||
"@typescript-eslint/only-throw-error",
|
||||
"@typescript-eslint/prefer-as-const",
|
||||
"@typescript-eslint/prefer-namespace-keyword",
|
||||
"@typescript-eslint/prefer-promise-reject-errors",
|
||||
"@typescript-eslint/require-await",
|
||||
"@typescript-eslint/restrict-plus-operands",
|
||||
"@typescript-eslint/restrict-template-expressions",
|
||||
"@typescript-eslint/triple-slash-reference",
|
||||
"@typescript-eslint/unbound-method",
|
||||
].map((rule) => [rule, "off"]),
|
||||
);
|
||||
const obsidianTypedRulesOffForJs = {
|
||||
"obsidianmd/no-plugin-as-component": "off",
|
||||
"obsidianmd/no-view-references-in-plugin": "off",
|
||||
"obsidianmd/no-unsupported-api": "off",
|
||||
"obsidianmd/prefer-file-manager-trash-file": "off",
|
||||
"obsidianmd/prefer-instanceof": "off",
|
||||
};
|
||||
|
||||
return [
|
||||
{
|
||||
ignores: [
|
||||
"lib/**",
|
||||
"dist/**",
|
||||
"node_modules/**",
|
||||
".github/**",
|
||||
"MathjaxToSVG/**",
|
||||
"docs/**",
|
||||
"ea-scripts/**",
|
||||
"images/**",
|
||||
"test-data/**",
|
||||
],
|
||||
},
|
||||
...compat.config(legacyConfig),
|
||||
...obsidianmd.configs.recommended,
|
||||
{
|
||||
files: ["**/*.{js,jsx}"],
|
||||
rules: {
|
||||
...tsRulesOffForJs,
|
||||
...obsidianTypedRulesOffForJs,
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ["**/*.{ts,tsx}"],
|
||||
languageOptions: {
|
||||
parser: require("@typescript-eslint/parser"),
|
||||
parserOptions: {
|
||||
project: "./tsconfig.json",
|
||||
tsconfigRootDir: __dirname,
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
"obsidianmd/prefer-instanceof": "off",
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ["**/*.{ts,tsx,js,jsx}"],
|
||||
rules: {
|
||||
"no-unused-vars": "off",
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
"error",
|
||||
{
|
||||
args: "after-used",
|
||||
argsIgnorePattern: "^_",
|
||||
varsIgnorePattern: "^_",
|
||||
ignoreRestSiblings: true,
|
||||
caughtErrors: "all",
|
||||
caughtErrorsIgnorePattern: "^_",
|
||||
},
|
||||
],
|
||||
"no-useless-escape": "error",
|
||||
},
|
||||
},
|
||||
];
|
||||
})();
|
||||
@@ -0,0 +1,43 @@
|
||||
import tseslint from 'typescript-eslint';
|
||||
import obsidianmd from 'eslint-plugin-obsidianmd';
|
||||
import globals from 'globals';
|
||||
import { globalIgnores } from 'eslint/config';
|
||||
|
||||
export default tseslint.config(
|
||||
globalIgnores([
|
||||
'node_modules',
|
||||
'dist',
|
||||
'esbuild.config.mjs',
|
||||
'rollup.config.mjs',
|
||||
'version-bump.mjs',
|
||||
'versions.json',
|
||||
'main.js',
|
||||
'package.json',
|
||||
'package-lock.json',
|
||||
'tsconfig.json',
|
||||
'tsconfig.api.json',
|
||||
'api',
|
||||
"scripts",
|
||||
"ea-scripts",
|
||||
"docs",
|
||||
"lib",
|
||||
"images",
|
||||
"assets",
|
||||
]),
|
||||
{
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.browser,
|
||||
},
|
||||
parserOptions: {
|
||||
projectService: {
|
||||
allowDefaultProject: ['eslint.config.mts', 'manifest.json'],
|
||||
},
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
extraFileExtensions: ['.json'],
|
||||
},
|
||||
},
|
||||
},
|
||||
...obsidianmd.configs.recommended,
|
||||
|
||||
);
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.6 MiB |
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.23.8",
|
||||
"version": "2.24.2",
|
||||
"minAppVersion": "1.8.7",
|
||||
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.23.8",
|
||||
"version": "2.24.2",
|
||||
"minAppVersion": "1.8.7",
|
||||
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
Generated
+746
-227
File diff suppressed because it is too large.
Load diff
+19
-16
@@ -8,39 +8,38 @@
|
||||
"lib/**/*"
|
||||
],
|
||||
"scripts": {
|
||||
"predev": "node scripts/build-mathjax.mjs",
|
||||
"dev": "cross-env NODE_ENV=development rollup --config rollup.config.mjs",
|
||||
"prebuild": "node scripts/build-mathjax.mjs",
|
||||
"build": "cross-env NODE_ENV=production rollup --config rollup.config.mjs",
|
||||
"prelib": "node scripts/build-mathjax.mjs",
|
||||
"lib": "cross-env NODE_ENV=lib rollup --config rollup.config.mjs",
|
||||
"code": "eslint --max-warnings=0 --ext .ts,.tsx ./src",
|
||||
"code:fix": "eslint --max-warnings=0 --ext .ts,.tsx ./src --fix",
|
||||
"code:unused": "eslint --max-warnings=0 --ext .ts,.tsx ./src --quiet --format json | node -e \"let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{const r=JSON.parse(d);for(const f of r){for(const m of f.messages||[]){if(m.ruleId==='@typescript-eslint/no-unused-vars'||m.ruleId==='no-unused-vars'){console.log(f.filePath+':'+m.line+':'+m.column+' '+m.ruleId+' '+m.message);}}}})\"",
|
||||
"code:escape": "eslint --max-warnings=0 --ext .ts,.tsx ./src --quiet --format json | node -e \"let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{const r=JSON.parse(d);for(const f of r){for(const m of f.messages||[]){if(m.ruleId==='no-useless-escape'){console.log(f.filePath+':'+m.line+':'+m.column+' '+m.ruleId+' '+m.message);}}}})\"",
|
||||
"madge": "madge --circular .",
|
||||
"build:mathjax": "cd MathjaxToSVG && npm run build",
|
||||
"build:all": "npm run build:mathjax && npm run build",
|
||||
"dev:mathjax": "cd MathjaxToSVG && npm run dev",
|
||||
"dev:all": "npm run dev:mathjax && npm run dev",
|
||||
"doc": "npm run lib && node scripts/generate-script-library.js",
|
||||
"mindmap": "node scripts/deploy-mindmap-builder.js"
|
||||
"doc": "npm run lib && node scripts/generate-script-library.mjs",
|
||||
"mindmap": "node scripts/deploy-mindmap-builder.mjs",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "npx prettier --write \"src/**/*.{ts,tsx}\" && eslint --max-warnings=0 --ext .ts,.tsx ./src --fix"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lezer/lr": "^1.4.10",
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.97",
|
||||
"@zsviczian/excalidraw": "0.18.106",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
"gl-matrix": "^3.4.3",
|
||||
"mathjax-full": "^3.2.2",
|
||||
"lz-string": "^1.5.0",
|
||||
"monkey-around": "^2.3.0",
|
||||
"nanoid": "^5.1.11",
|
||||
"opentype.js": "^1.3.4",
|
||||
"pako": "^2.1.0",
|
||||
"points-on-path": "^0.2.1",
|
||||
"polybooljs": "^1.2.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
@@ -57,8 +56,6 @@
|
||||
"@codemirror/search": "6.5.11",
|
||||
"@codemirror/state": "6.5.0",
|
||||
"@codemirror/view": "6.38.6",
|
||||
"@eslint/eslintrc": "^3.1.0",
|
||||
"@excalidraw/eslint-config": "^1.0.3",
|
||||
"@excalidraw/prettier-config": "^1.0.2",
|
||||
"@rollup/plugin-babel": "^6.0.3",
|
||||
"@rollup/plugin-commonjs": "^26.0.1",
|
||||
@@ -73,20 +70,22 @@
|
||||
"@types/opentype.js": "^1.3.8",
|
||||
"@types/react": "^18.2.45",
|
||||
"@types/react-dom": "^18.2.18",
|
||||
"@zsviczian/excalidraw-extras-api": "^0.0.13",
|
||||
"@zsviczian/rollup-plugin-postprocess": "^1.0.3",
|
||||
"cross-env": "^7.0.3",
|
||||
"cssnano": "^6.0.2",
|
||||
"eslint": "^9.27.0",
|
||||
"eslint": "^9.39.4",
|
||||
"eslint-config-prettier": "^9.0.0",
|
||||
"eslint-plugin-obsidianmd": "^0.3.0",
|
||||
"eslint-plugin-prettier": "^5.0.0",
|
||||
"jiti": "^2.6.1",
|
||||
"jsesc": "^3.0.2",
|
||||
"lz-string": "^1.5.0",
|
||||
"obsidian": "1.8.7",
|
||||
"postcss": "^8.4.31",
|
||||
"prettier": "^3.0.1",
|
||||
"rollup": "^4.14.0",
|
||||
"rollup-plugin-copy": "^3.5.0",
|
||||
"rollup-plugin-visualizer": "^7.0.1",
|
||||
"tslib": "^2.8.1",
|
||||
"typescript": "5.9.3",
|
||||
"uglify-js": "^3.19.3"
|
||||
@@ -94,7 +93,11 @@
|
||||
"overrides": {
|
||||
"lodash": "^4.18.1",
|
||||
"lodash-es": "^4.18.1",
|
||||
"serialize-javascript": "^7.0.5"
|
||||
"serialize-javascript": "^7.0.5",
|
||||
"nanoid": "^5.1.11"
|
||||
},
|
||||
"resolutions": {
|
||||
"strip-ansi": "^7.0.1"
|
||||
},
|
||||
"prettier": "@excalidraw/prettier-config",
|
||||
"engines": {
|
||||
|
||||
+35
-9
@@ -1,4 +1,6 @@
|
||||
import { nodeResolve } from '@rollup/plugin-node-resolve';
|
||||
import zlib from 'node:zlib';
|
||||
import visualizer from 'rollup-plugin-visualizer';
|
||||
import commonjs from '@rollup/plugin-commonjs';
|
||||
import replace from "@rollup/plugin-replace";
|
||||
import terser from "@rollup/plugin-terser";
|
||||
@@ -6,7 +8,6 @@ import copy from "rollup-plugin-copy";
|
||||
import typescript from "@rollup/plugin-typescript";
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import LZString from 'lz-string';
|
||||
import postprocess from '@zsviczian/rollup-plugin-postprocess';
|
||||
import cssnano from 'cssnano';
|
||||
import jsesc from 'jsesc';
|
||||
@@ -14,6 +15,12 @@ import { minify } from 'uglify-js';
|
||||
import json from '@rollup/plugin-json';
|
||||
import { parseEnv } from 'node:util';
|
||||
|
||||
function compressDeflateBase64(code) {
|
||||
// Compress using Node's native zlib at maximum compression
|
||||
const compressed = zlib.deflateSync(Buffer.from(code, "utf-8"), { level: 9 });
|
||||
return compressed.toString("base64");
|
||||
}
|
||||
|
||||
try {
|
||||
const envContent = fs.readFileSync(path.resolve('.env'), 'utf8');
|
||||
Object.assign(process.env, parseEnv(envContent));
|
||||
@@ -48,8 +55,6 @@ const jsxRuntimeShim = `
|
||||
window['react/jsx-dev-runtime'] = { jsx, jsxs, Fragment, jsxDEV: jsx };
|
||||
`;
|
||||
|
||||
const mathjaxtosvg_pkg = isLib ? "" : fs.readFileSync("./MathjaxToSVG/dist/index.js", "utf8");
|
||||
|
||||
// Add non-English locales here to embed them as compressed payloads in main.js.
|
||||
// When adding a locale file:
|
||||
// 1) add its code to this list, 2) build once, 3) if build fails because the locale
|
||||
@@ -86,7 +91,7 @@ function compressLanguageFile(lang) {
|
||||
const filePath = `${inputDir}/${lang}.ts`;
|
||||
let content = fs.readFileSync(filePath, "utf-8");
|
||||
content = trimLastSemicolon(content.split("export default")[1].trim());
|
||||
return LZString.compressToBase64(minifyCode(`x = ${content};`));
|
||||
return compressDeflateBase64(minifyCode(`x = ${content};`));
|
||||
}
|
||||
|
||||
const excalidraw_pkg = isLib ? "" : minifyCode(isProd
|
||||
@@ -99,7 +104,8 @@ const reactdom_pkg = isLib ? "" : minifyCode(isProd
|
||||
? fs.readFileSync("./node_modules/react-dom/umd/react-dom.production.min.js", "utf8")
|
||||
: fs.readFileSync("./node_modules/react-dom/umd/react-dom.development.js", "utf8"));
|
||||
|
||||
const lzstring_pkg = isLib ? "" : fs.readFileSync("./node_modules/lz-string/libs/lz-string.min.js", "utf8");
|
||||
const pako_pkg = isLib ? "" : fs.readFileSync("./node_modules/pako/dist/pako.min.js", "utf8");
|
||||
|
||||
if (!isLib) {
|
||||
const excalidraw_styles = isProd
|
||||
? fs.readFileSync("./node_modules/@zsviczian/excalidraw/dist/styles.production.css", "utf8")
|
||||
@@ -126,15 +132,29 @@ if (!isLib) {
|
||||
}
|
||||
|
||||
const packageString = isLib
|
||||
? ""
|
||||
: ';const INITIAL_TIMESTAMP=Date.now();' + lzstring_pkg +
|
||||
? ""
|
||||
: ';const INITIAL_TIMESTAMP=Date.now();\n' +
|
||||
'const pako = (function() {\n' +
|
||||
' const module = { exports: {} };\n' +
|
||||
' const exports = module.exports;\n' +
|
||||
' ' + pako_pkg + '\n' +
|
||||
' return module.exports;\n' +
|
||||
'})();\n' +
|
||||
'\nlet REACT_PACKAGES = `' +
|
||||
jsesc(react_pkg + reactdom_pkg + jsxRuntimeShim, { quotes: 'backtick' }) +
|
||||
'`;\n' +
|
||||
'const unpackExcalidraw = () => LZString.decompressFromBase64("' + LZString.compressToBase64(excalidraw_pkg) + '");\n' +
|
||||
// NEW: Fast, mobile-compatible runtime decompression
|
||||
'const unpackBase64Deflate = (b64) => {\n' +
|
||||
' const binStr = atob(b64);\n' +
|
||||
' const len = binStr.length;\n' +
|
||||
' const bytes = new Uint8Array(len);\n' +
|
||||
' for (let i = 0; i < len; i++) bytes[i] = binStr.charCodeAt(i);\n' +
|
||||
' return new TextDecoder().decode(pako.inflate(bytes));\n' +
|
||||
'};\n' +
|
||||
'window.unpackBase64Deflate = unpackBase64Deflate;\n' +
|
||||
'const unpackExcalidraw = () => unpackBase64Deflate("' + compressDeflateBase64(excalidraw_pkg) + '");\n' +
|
||||
'let {react, reactDOM } = new Function(`${REACT_PACKAGES}; return {react: React, reactDOM: ReactDOM};`)();\n' +
|
||||
'let excalidrawLib = {};\n' +
|
||||
'const loadMathjaxToSVG = () => new Function(`${LZString.decompressFromBase64("' + LZString.compressToBase64(mathjaxtosvg_pkg) + '")}; return MathjaxToSVG;`)();\n' +
|
||||
`const PLUGIN_LANGUAGES = {${LANGUAGES.map(lang => `"${lang}": "${compressLanguageFile(lang)}"`).join(",")}};\n` +
|
||||
'const PLUGIN_VERSION="' + manifest.version + '";';
|
||||
|
||||
@@ -198,6 +218,12 @@ const BUILD_CONFIG = {
|
||||
(_, g1, g2) => `${g1}${g2}${packageString}`
|
||||
],
|
||||
]),
|
||||
/*visualizer({
|
||||
filename: 'bundle-analysis.html',
|
||||
open: true, // Automatically opens in your browser when the build finishes
|
||||
gzipSize: true,
|
||||
brotliSize: true,
|
||||
}),*/
|
||||
] : [
|
||||
postprocess([ [/var React = require\('react'\);/, packageString] ]),
|
||||
]),
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import { execSync } from 'node:child_process';
|
||||
|
||||
const mathjaxDir = path.resolve('MathjaxToSVG');
|
||||
const distDir = path.join(mathjaxDir, 'dist');
|
||||
const distFile = path.join(distDir, 'index.js');
|
||||
const hashFile = path.join(distDir, '.build-hash');
|
||||
const nodeModulesDir = path.join(mathjaxDir, 'node_modules');
|
||||
|
||||
// Recursively generates an MD5 hash of all source files in a directory
|
||||
function hashDirectory(dir) {
|
||||
const files = fs.readdirSync(dir, { withFileTypes: true });
|
||||
const hash = crypto.createHash('md5');
|
||||
|
||||
// Sort to ensure consistent hashing across different operating systems
|
||||
for (const file of files.sort((a, b) => a.name.localeCompare(b.name))) {
|
||||
// Ignore build outputs, dependencies, and hidden files (like .git, .DS_Store)
|
||||
if (file.name === 'node_modules' || file.name === 'dist' || file.name.startsWith('.')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const fullPath = path.join(dir, file.name);
|
||||
if (file.isDirectory()) {
|
||||
hash.update(hashDirectory(fullPath));
|
||||
} else {
|
||||
hash.update(fs.readFileSync(fullPath));
|
||||
}
|
||||
}
|
||||
return hash.digest('hex');
|
||||
}
|
||||
|
||||
const currentHash = hashDirectory(mathjaxDir);
|
||||
let previousHash = '';
|
||||
|
||||
if (fs.existsSync(hashFile)) {
|
||||
previousHash = fs.readFileSync(hashFile, 'utf8');
|
||||
}
|
||||
|
||||
// Rebuild if the output file is missing, or if the source files have changed
|
||||
if (!fs.existsSync(distFile) || currentHash !== previousHash) {
|
||||
console.log('🔄 MathjaxToSVG changes detected (or missing build). Rebuilding...');
|
||||
|
||||
// Run npm install if node_modules is missing or if we know things changed
|
||||
if (!fs.existsSync(nodeModulesDir) || currentHash !== previousHash) {
|
||||
console.log('📦 Installing MathjaxToSVG dependencies...');
|
||||
execSync('npm install', { stdio: 'inherit', cwd: mathjaxDir });
|
||||
}
|
||||
|
||||
console.log('🔨 Building MathjaxToSVG...');
|
||||
execSync('npm run build', { stdio: 'inherit', cwd: mathjaxDir });
|
||||
|
||||
// Save the new hash for next time
|
||||
if (!fs.existsSync(distDir)) {
|
||||
fs.mkdirSync(distDir, { recursive: true });
|
||||
}
|
||||
fs.writeFileSync(hashFile, currentHash);
|
||||
|
||||
console.log('✅ MathjaxToSVG build complete.\n');
|
||||
} else {
|
||||
console.log('⚡ MathjaxToSVG is up to date. Skipping build.\n');
|
||||
}
|
||||
@@ -1,7 +1,12 @@
|
||||
const path = require("path");
|
||||
const fs = require("fs/promises");
|
||||
const { minify } = require("terser");
|
||||
const LZString = require("lz-string");
|
||||
import path from "path";
|
||||
import fs from "fs/promises";
|
||||
import { minify } from "terser";
|
||||
import LZString from "lz-string";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
// Construct __dirname for ES Modules
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const CHUNK_SIZE = 256;
|
||||
const NEEDLE = "const removeKeydownHandlers";
|
||||
@@ -1,5 +1,5 @@
|
||||
const fs = require('fs');
|
||||
const { execSync } = require('child_process');
|
||||
import fs from 'fs';
|
||||
import { execSync } from 'child_process';
|
||||
|
||||
const content = fs.readFileSync('src/lang/locale/en.ts', 'utf8');
|
||||
const lines = content.split('\n');
|
||||
@@ -29,4 +29,4 @@ for (const key of keys) {
|
||||
}
|
||||
|
||||
unusedKeys.sort().forEach(k => console.log(k));
|
||||
console.log('Total: ' + unusedKeys.length);
|
||||
console.log('Total: ' + unusedKeys.length);
|
||||
@@ -1,7 +1,12 @@
|
||||
/* eslint-disable no-console */
|
||||
// to run: npm run doc
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
// to run: node generate-script-library.mjs
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
// Reconstruct __dirname for ES Modules
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const ROOT = path.resolve(__dirname, '..');
|
||||
const EA_SCRIPTS_DIR = path.join(ROOT, 'ea-scripts');
|
||||
@@ -617,17 +622,17 @@ function main() {
|
||||
|
||||
const combined =
|
||||
(AI_TRAINING_INTRO +
|
||||
'\n---\n\n' +
|
||||
typeDefContent.trim() +
|
||||
'\n\n---\n\n' +
|
||||
excalidrawLibFunctionsSection +
|
||||
'\n---\n\n' +
|
||||
scriptLibContent.trim() +
|
||||
startupSection +
|
||||
'\n')
|
||||
.replaceAll("https://youtu.be/", "YouTube: ")
|
||||
.replaceAll("https://www.youtube.com/watch?v=", "YouTube: ")
|
||||
.replaceAll("https://www.youtube.com/", "YouTube: "); // prevent accidental link triggering
|
||||
'\n---\n\n' +
|
||||
typeDefContent.trim() +
|
||||
'\n\n---\n\n' +
|
||||
excalidrawLibFunctionsSection +
|
||||
'\n---\n\n' +
|
||||
scriptLibContent.trim() +
|
||||
startupSection +
|
||||
'\n')
|
||||
.replaceAll("https://youtu.be/", "YouTube: ")
|
||||
.replaceAll("https://www.youtube.com/watch?v=", "YouTube: ")
|
||||
.replaceAll("https://www.youtube.com/", "YouTube: "); // prevent accidental link triggering
|
||||
|
||||
fs.writeFileSync(AI_TRAINING_OUT, combined, 'utf8');
|
||||
console.log('[script-library] Wrote:', AI_TRAINING_OUT);
|
||||
@@ -638,11 +643,12 @@ function main() {
|
||||
console.log('[script-library] Done.');
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
// ESM equivalent of `if (require.main === module)`
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||
try {
|
||||
main();
|
||||
} catch (e) {
|
||||
console.error('[script-library] Failed:', e);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { getIcon, sanitizeHTMLToDom } from "obsidian";
|
||||
import { PenStyle } from "src/types/penTypes";
|
||||
import React from "react";
|
||||
import { mainDocument } from "./constants";
|
||||
import { isInstanceOfSVGSVGElement } from "src/utils/typechecks";
|
||||
|
||||
const BLOCKED_SVG_TAGS = new Set([
|
||||
"script",
|
||||
@@ -45,7 +47,7 @@ const isUnsafeAttribute = (name: string, value: string): boolean => {
|
||||
|
||||
const sanitizeSvgTree = (svg: SVGSVGElement) => {
|
||||
const nodesToRemove: Element[] = [];
|
||||
const walker = document.createTreeWalker(svg, NodeFilter.SHOW_ELEMENT);
|
||||
const walker = mainDocument.createTreeWalker(svg, NodeFilter.SHOW_ELEMENT);
|
||||
|
||||
let current = walker.currentNode as Element;
|
||||
while (current) {
|
||||
@@ -67,7 +69,7 @@ const sanitizeSvgTree = (svg: SVGSVGElement) => {
|
||||
const sanitizeSvgFromString = (svgMarkup: string): SVGSVGElement | null => {
|
||||
const fragment = sanitizeHTMLToDom(svgMarkup ?? "");
|
||||
const svg = fragment.querySelector("svg");
|
||||
if (!(svg instanceof SVGSVGElement)) {
|
||||
if (!isInstanceOfSVGSVGElement(svg)) {
|
||||
return null;
|
||||
}
|
||||
const clone = svg.cloneNode(true) as SVGSVGElement;
|
||||
@@ -82,7 +84,7 @@ const sanitizeSvgElement = (svg: SVGSVGElement): SVGSVGElement => {
|
||||
};
|
||||
|
||||
const applyDefaultSvgTheme = (svg: SVGSVGElement) => {
|
||||
const walker = document.createTreeWalker(svg, NodeFilter.SHOW_ELEMENT);
|
||||
const walker = mainDocument.createTreeWalker(svg, NodeFilter.SHOW_ELEMENT);
|
||||
let current = walker.currentNode as Element;
|
||||
while (current) {
|
||||
current.removeAttribute("stroke");
|
||||
@@ -118,7 +120,7 @@ const cssTextToReactStyle = (
|
||||
style[toReactAttributeName(key)] = value;
|
||||
});
|
||||
|
||||
return Object.keys(style).length ? (style as React.CSSProperties) : undefined;
|
||||
return Object.keys(style).length ? style : undefined;
|
||||
};
|
||||
|
||||
const domNodeToReact = (
|
||||
@@ -211,6 +213,8 @@ export const ICONS = {
|
||||
</text>
|
||||
</svg>
|
||||
),
|
||||
Edit: getIconAsJSX("pen-line"),
|
||||
Read: getIconAsJSX("book-open"),
|
||||
Learn: getIconAsJSX("graduation-cap"),
|
||||
Github: getIconAsJSX("github"),
|
||||
YouTube: getIconAsJSX("youtube"),
|
||||
|
||||
@@ -5,9 +5,11 @@ import { DeviceType } from "src/types/types";
|
||||
import { errorHandler } from "../utils/ErrorHandler";
|
||||
import { getLanguage } from "obsidian";
|
||||
import { URLs } from "./safeUrls";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
//This is only for backward compatibility because an early version of obsidian included an encoding to avoid fantom links from littering Obsidian graph view
|
||||
declare const PLUGIN_VERSION: string;
|
||||
export let EXCALIDRAW_PLUGIN: ExcalidrawPlugin = null;
|
||||
// eslint-disable-next-line obsidianmd/prefer-active-doc
|
||||
export const mainDocument = document; //signals deliberate use of main document instead of activeDocument
|
||||
export const setExcalidrawPlugin = (plugin: ExcalidrawPlugin) => {
|
||||
EXCALIDRAW_PLUGIN = plugin;
|
||||
@@ -174,7 +176,9 @@ export function updateExcalidrawLib() {
|
||||
getDefaultColorPalette,
|
||||
} = excalidrawLib);
|
||||
} catch (error) {
|
||||
errorHandler.handleError(error, "updateExcalidrawLib", true);
|
||||
if (error instanceof Error || typeof error === "string") {
|
||||
errorHandler.handleError(error, "updateExcalidrawLib", true);
|
||||
}
|
||||
// Don't throw here - we'll try to continue with potentially stale functions
|
||||
// but at least we won't crash
|
||||
}
|
||||
@@ -212,7 +216,7 @@ export function setRootElementSize(size?: number) {
|
||||
return;
|
||||
}
|
||||
const tempElement = mainDocument.createElement("div");
|
||||
tempElement.style.fontSize = "1rem";
|
||||
setStyle(tempElement, { fontSize: "1rem" });
|
||||
tempElement.hidden = true;
|
||||
mainDocument.body.appendChild(tempElement);
|
||||
const computedStyle = getComputedStyle(tempElement);
|
||||
|
||||
@@ -219,10 +219,7 @@ export const URL_REGISTRY = {
|
||||
"https://community.obsidian.md/plugins/obsidian-excalidraw-plugin",
|
||||
UrlPurpose.RELEASE_LOG,
|
||||
),
|
||||
GITHUB_COM_HEINRICH26: defineUrl(
|
||||
"https://github.com/heinrich26",
|
||||
UrlPurpose.RELEASE_LOG,
|
||||
),
|
||||
GITHUB_COM: defineUrl("https://github.com/", UrlPurpose.RELEASE_LOG),
|
||||
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES: defineUrl(
|
||||
"https://github.com/excalidraw/excalidraw/issues",
|
||||
UrlPurpose.RELEASE_LOG,
|
||||
|
||||
+7
-2
@@ -1,5 +1,6 @@
|
||||
import "obsidian";
|
||||
import type { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { errorlog } from "src/utils/coreUtils";
|
||||
import type ExcalidrawView from "src/view/ExcalidrawView";
|
||||
//import { ExcalidrawAutomate } from "./ExcalidrawAutomate";
|
||||
//export ExcalidrawAutomate from "./ExcalidrawAutomate";
|
||||
@@ -16,8 +17,12 @@ export type { Point } from "src/types/types";
|
||||
export const getEA = (view?: ExcalidrawView): ExcalidrawAutomate | null => {
|
||||
try {
|
||||
return window.ExcalidrawAutomate.getAPI(view);
|
||||
} catch (_) {
|
||||
console.log({ message: "Excalidraw not available", fn: getEA });
|
||||
} catch (error) {
|
||||
errorlog({
|
||||
message: "Excalidraw not available",
|
||||
fn: getEA,
|
||||
error: error as unknown,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
};
|
||||
+73
-363
@@ -1,3 +1,4 @@
|
||||
import { ExcalidrawExtrasGateway } from "../utils/ExcalidrawExtrasGateway";
|
||||
import {
|
||||
TFile,
|
||||
Plugin,
|
||||
@@ -10,9 +11,7 @@ import {
|
||||
ViewState,
|
||||
ViewStateResult,
|
||||
Notice,
|
||||
request,
|
||||
MetadataCache,
|
||||
Workspace,
|
||||
TAbstractFile,
|
||||
FrontMatterCache,
|
||||
} from "obsidian";
|
||||
@@ -28,7 +27,6 @@ import {
|
||||
FRONTMATTER,
|
||||
JSON_parse,
|
||||
SCRIPT_INSTALL_CODEBLOCK,
|
||||
SCRIPT_INSTALL_FOLDER,
|
||||
EXPORT_TYPES,
|
||||
EXPORT_IMG_ICON_NAME,
|
||||
EXPORT_IMG_ICON,
|
||||
@@ -37,7 +35,6 @@ import {
|
||||
DEVICE,
|
||||
FONTS_STYLE_ID,
|
||||
CJK_STYLE_ID,
|
||||
loadMermaid,
|
||||
setRootElementSize,
|
||||
mainDocument,
|
||||
} from "../constants/constants";
|
||||
@@ -51,25 +48,18 @@ import {
|
||||
KNOWN_AI_IMAGE_MODEL_CONFIGS,
|
||||
} from "./settings";
|
||||
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
|
||||
import {
|
||||
initExcalidrawAutomate,
|
||||
insertLaTeXToView,
|
||||
} from "src/utils/excalidrawAutomateUtils";
|
||||
import { around, dedupe } from "monkey-around";
|
||||
import { initExcalidrawAutomate } from "src/utils/excalidrawAutomateUtils";
|
||||
import { t } from "../lang/helpers";
|
||||
import {
|
||||
createOrOverwriteFile,
|
||||
fileShouldDefaultAsExcalidraw,
|
||||
getDrawingFilename,
|
||||
getIMGFilename,
|
||||
getNewUniqueFilepath,
|
||||
} from "../utils/fileUtils";
|
||||
import {
|
||||
getFontDataURL,
|
||||
errorlog,
|
||||
sleep,
|
||||
isVersionNewerThanOther,
|
||||
isCallerFromTemplaterPlugin,
|
||||
versionUpdateCheckTimer,
|
||||
getFontMetrics,
|
||||
calculateUIModeValue,
|
||||
@@ -90,18 +80,16 @@ import {
|
||||
import { FieldSuggester } from "../shared/Suggesters/FieldSuggester";
|
||||
import { ReleaseNotes } from "../shared/Dialogs/ReleaseNotes";
|
||||
import { DeviceType, Packages } from "../types/types";
|
||||
import { RemoteDirectoryInfo } from "../types/githubTypes";
|
||||
import { PaneTarget, PreviewImageType } from "../types/utilTypes";
|
||||
import {
|
||||
emulateCTRLClickForLinks,
|
||||
linkClickModifierType,
|
||||
} from "../utils/modifierkeyHelper";
|
||||
import { imageCache } from "../shared/ImageCache";
|
||||
import { getImageCache } from "../shared/ImageCache";
|
||||
import { StylesManager } from "./managers/StylesManager";
|
||||
import { CustomMutationObserver, log } from "../utils/debugHelper";
|
||||
import { ExcalidrawConfig } from "../shared/ExcalidrawConfig";
|
||||
import { EditorHandler } from "./editor/EditorHandler";
|
||||
import { ExcalidrawLib } from "../types/excalidrawLib";
|
||||
import { Rank, SwordColors } from "../constants/actionIcons";
|
||||
import { RankMessage } from "../shared/Dialogs/RankMessage";
|
||||
import {
|
||||
@@ -114,10 +102,10 @@ import {
|
||||
ExcalidrawLoading,
|
||||
switchToExcalidraw,
|
||||
} from "../view/ExcalidrawLoading";
|
||||
import { clearMathJaxVariables } from "../shared/LaTeX";
|
||||
import { PluginFileManager } from "./managers/FileManager";
|
||||
import { ObserverManager } from "./managers/ObserverManager";
|
||||
import { PackageManager } from "./managers/PackageManager";
|
||||
import { MonkeyPatchManager } from "./managers/MonkeyPatchManager";
|
||||
import ExcalidrawView from "../view/ExcalidrawView";
|
||||
import { ExcalidrawSidepanelView } from "../view/sidepanel/Sidepanel";
|
||||
import { CommandManager } from "./managers/CommandManager";
|
||||
@@ -132,7 +120,10 @@ import {
|
||||
decryptPersistedAPIKeys,
|
||||
encryptPersistedAPIKeys,
|
||||
} from "src/utils/settingsKeyObfuscation";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { hideElement, setButtonBgColor } from "src/utils/styleUtils";
|
||||
import { installButton } from "src/utils/scriptLibraryUtils";
|
||||
import { isInstanceOfHTMLStyleElement } from "src/utils/typechecks";
|
||||
import { insertLaTeXToView } from "src/utils/excalidrawViewHelpers";
|
||||
|
||||
declare const PLUGIN_VERSION: string;
|
||||
declare const INITIAL_TIMESTAMP: number;
|
||||
@@ -585,9 +576,11 @@ const migrateLegacyAISettings = (
|
||||
};
|
||||
|
||||
export default class ExcalidrawPlugin extends Plugin {
|
||||
public extrasGateway: ExcalidrawExtrasGateway;
|
||||
private fileManager: PluginFileManager;
|
||||
private observerManager: ObserverManager;
|
||||
private packageManager: PackageManager;
|
||||
private monkeyPatchManager: MonkeyPatchManager;
|
||||
private commandManager: CommandManager;
|
||||
private eventManager: EventManager;
|
||||
public eaInstances = new WeakArray<ExcalidrawAutomate>();
|
||||
@@ -621,6 +614,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
public loadTimestamp: number;
|
||||
private isLocalCJKFontAvailabe: boolean = undefined;
|
||||
public isReady = false;
|
||||
private fontsReady = true; //setting this to true allows for a race condition during startup loading fonts and rendering Excalidraw
|
||||
private startupAnalytics: string[] = [];
|
||||
private lastLogTimestamp: number;
|
||||
private settingsReady: boolean = false;
|
||||
@@ -665,7 +659,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
}
|
||||
|
||||
public printStarupBreakdown() {
|
||||
console.log(
|
||||
log(
|
||||
`Excalidraw ${PLUGIN_VERSION} startup breakdown:\n${this.startupAnalytics.join(
|
||||
"\n",
|
||||
)}`,
|
||||
@@ -725,7 +719,25 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
* @returns shared mermaid instance
|
||||
*/
|
||||
public async getMermaid() {
|
||||
return await loadMermaid();
|
||||
const mermaidApi = await this.extrasGateway.getMermaid();
|
||||
|
||||
if (mermaidApi) {
|
||||
return {
|
||||
loaded: true,
|
||||
// Forwarding the raw module dynamically fetched by the Extras plugin.
|
||||
// This makes your setup completely immune to upstream Mermaid signature changes.
|
||||
api: mermaidApi.getModule(),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
loaded: false,
|
||||
api: Promise.reject(
|
||||
new Error(
|
||||
"Mermaid to Excalidraw requires the Excalidraw Extras companion plugin.",
|
||||
),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
public isPenMode() {
|
||||
@@ -788,15 +800,13 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
addIcon(ICON_NAME, EXCALIDRAW_ICON);
|
||||
addIcon(SCRIPTENGINE_ICON_NAME, SCRIPTENGINE_ICON);
|
||||
addIcon(EXPORT_IMG_ICON_NAME, EXPORT_IMG_ICON);
|
||||
this.addRibbonIcon(
|
||||
ICON_NAME,
|
||||
t("CREATE_NEW"),
|
||||
this.actionRibbonClick.bind(this),
|
||||
this.addRibbonIcon(ICON_NAME, t("CREATE_NEW"), (e) =>
|
||||
this.actionRibbonClick(e),
|
||||
);
|
||||
|
||||
try {
|
||||
void this.loadSettings({ reEnableAutosave: true }).then(
|
||||
this.onloadCheckForOnceOffSettingsUpdates.bind(this),
|
||||
void this.loadSettings({ reEnableAutosave: true }).then(() =>
|
||||
this.onloadCheckForOnceOffSettingsUpdates(),
|
||||
);
|
||||
} catch (e) {
|
||||
new Notice("Error loading plugin settings", 6000);
|
||||
@@ -808,7 +818,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
// need it her for ExcaliBrain
|
||||
this.ea = initExcalidrawAutomate(this);
|
||||
} catch (e) {
|
||||
new Notice("Error initializing Excalidraw Automate", 6000);
|
||||
new Notice(t("ERROR_INITIALIZING_EA"), 6000);
|
||||
console.error("Error initializing Excalidraw Automate", e);
|
||||
}
|
||||
this.logStartupEvent("Excalidraw Automate initialized");
|
||||
@@ -817,12 +827,12 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
//Licat: Are you registering your post processors in onLayoutReady? You should register them in onload instead
|
||||
this.addMarkdownPostProcessor();
|
||||
} catch (e) {
|
||||
new Notice("Error adding markdown post processor", 6000);
|
||||
console.error("Error adding markdown post processor", e);
|
||||
new Notice("Error adding Markdown post processor", 6000);
|
||||
console.error("Error adding Markdown post processor", e);
|
||||
}
|
||||
this.logStartupEvent("Markdown post processor added");
|
||||
|
||||
this.app.workspace.onLayoutReady(this.onloadOnLayoutReady.bind(this));
|
||||
this.app.workspace.onLayoutReady(() => this.onloadOnLayoutReady());
|
||||
this.logStartupEvent("Workspace ready event handler added");
|
||||
}
|
||||
|
||||
@@ -855,6 +865,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
);
|
||||
await this.awaitSettings();
|
||||
this.logStartupEvent("Settings awaited");
|
||||
this.extrasGateway = new ExcalidrawExtrasGateway(this.app, this);
|
||||
if (!this.settings.overrideObsidianFontSize) {
|
||||
setRootElementSize();
|
||||
}
|
||||
@@ -862,6 +873,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.packageManager = new PackageManager(this);
|
||||
this.eventManager = new EventManager(this);
|
||||
this.observerManager = new ObserverManager(this);
|
||||
this.monkeyPatchManager = new MonkeyPatchManager(this);
|
||||
this.commandManager = new CommandManager(this);
|
||||
|
||||
try {
|
||||
@@ -885,7 +897,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
try {
|
||||
//inspiration taken from kanban:
|
||||
//https://github.com/mgmeyers/obsidian-kanban/blob/44118e25661bff9ebfe54f71ae33805dc88ffa53/src/main.ts#L267
|
||||
this.registerMonkeyPatches();
|
||||
this.monkeyPatchManager.initialize();
|
||||
} catch (e) {
|
||||
new Notice("Error registering monkey patches", 6000);
|
||||
console.error("Error registering monkey patches", e);
|
||||
@@ -910,16 +922,10 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
}
|
||||
this.logStartupEvent("Script engine initialized");
|
||||
|
||||
try {
|
||||
await this.initializeFonts();
|
||||
} catch (e) {
|
||||
new Notice("Error initializing fonts", 6000);
|
||||
console.error("Error initializing fonts", e);
|
||||
}
|
||||
this.logStartupEvent("Fonts initialized");
|
||||
void this.initializeFonts();
|
||||
|
||||
try {
|
||||
void imageCache.initializeDB(this);
|
||||
void getImageCache().initializeDB(this);
|
||||
} catch (e) {
|
||||
new Notice("Error initializing image cache", 6000);
|
||||
console.error("Error initializing image cache", e);
|
||||
@@ -1023,7 +1029,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
|
||||
public async awaitInit() {
|
||||
let counter = 0;
|
||||
while (!this.isReady && counter < 150) {
|
||||
while ((!this.isReady || !this.fontsReady) && counter < 200) {
|
||||
await sleep(50);
|
||||
counter++;
|
||||
}
|
||||
@@ -1123,6 +1129,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.fourthFontLoaded = true;
|
||||
}, 100);
|
||||
}
|
||||
this.fontsReady = true;
|
||||
}
|
||||
|
||||
public async addFonts(
|
||||
@@ -1174,8 +1181,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (existingStylesheet instanceof HTMLStyleElement) {
|
||||
if (isInstanceOfHTMLStyleElement(existingStylesheet)) {
|
||||
existingStylesheet.textContent = PHONE_FOOTER_SAFE_AREA_CSS;
|
||||
return;
|
||||
}
|
||||
@@ -1265,205 +1271,36 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
"data-heading",
|
||||
)}"]`,
|
||||
);
|
||||
link.style.paddingRight = "10px";
|
||||
link.addClass("excalidraw-installCodeBlock-link");
|
||||
button2 = link.parentElement.createEl("button", null, (b) => {
|
||||
b.setText(t("UPDATE_SCRIPT"));
|
||||
b.addClass("mod-muted");
|
||||
b.style.backgroundColor = "var(--interactive-success)";
|
||||
b.style.display = "none";
|
||||
setButtonBgColor(b, "success");
|
||||
hideElement(b);
|
||||
});
|
||||
} catch (e) {
|
||||
errorlog({
|
||||
where: "this.registerInstallCodeblockProcessor",
|
||||
source,
|
||||
error: e,
|
||||
error: e as unknown,
|
||||
});
|
||||
}
|
||||
|
||||
source = source.trim();
|
||||
el.createEl("button", null, async (button) => {
|
||||
const setButtonText = (
|
||||
text: "CHECKING" | "INSTALL" | "UPTODATE" | "UPDATE" | "ERROR",
|
||||
) => {
|
||||
if (button2) {
|
||||
button2.style.display = "none";
|
||||
}
|
||||
switch (text) {
|
||||
case "CHECKING":
|
||||
button.setText(t("CHECKING_SCRIPT"));
|
||||
button.style.backgroundColor = "var(--interactive-normal)";
|
||||
break;
|
||||
case "INSTALL":
|
||||
button.setText(t("INSTALL_SCRIPT"));
|
||||
button.style.backgroundColor = "var(--interactive-accent)";
|
||||
break;
|
||||
case "UPTODATE":
|
||||
button.setText(t("UPTODATE_SCRIPT"));
|
||||
button.style.backgroundColor = "var(--interactive-normal)";
|
||||
break;
|
||||
case "UPDATE":
|
||||
button.setText(t("UPDATE_SCRIPT"));
|
||||
button.style.backgroundColor = "var(--interactive-success)";
|
||||
if (button2) {
|
||||
button2.style.display = null;
|
||||
}
|
||||
break;
|
||||
case "ERROR":
|
||||
button.setText(t("UNABLETOCHECK_SCRIPT"));
|
||||
button.style.backgroundColor = "var(--interactive-normal)";
|
||||
break;
|
||||
}
|
||||
};
|
||||
button.addClass("mod-muted");
|
||||
let decodedURI = source;
|
||||
try {
|
||||
decodedURI = decodeURI(source);
|
||||
} catch (e) {
|
||||
errorlog({
|
||||
where:
|
||||
"ExcalidrawPlugin.registerInstallCodeblockProcessor.codeblockProcessor.onClick",
|
||||
source,
|
||||
error: e,
|
||||
});
|
||||
}
|
||||
const fname = decodedURI.substring(decodedURI.lastIndexOf("/") + 1);
|
||||
const folder = `${this.settings.scriptFolderPath}/${SCRIPT_INSTALL_FOLDER}`;
|
||||
const downloaded = this.app.vault
|
||||
.getFiles()
|
||||
.filter((f) => f.path.startsWith(folder) && f.name === fname)
|
||||
.sort((a, b) => (a.path > b.path ? 1 : -1));
|
||||
let scriptFile = downloaded[0];
|
||||
const scriptPath = scriptFile?.path ?? `${folder}/${fname}`;
|
||||
const svgPath = getIMGFilename(scriptPath, "svg");
|
||||
let svgFile = this.app.vault.getFileByPath(svgPath);
|
||||
setButtonText(scriptFile ? "CHECKING" : "INSTALL");
|
||||
button.onclick = async () => {
|
||||
const download = async (
|
||||
url: string,
|
||||
file: TFile,
|
||||
localPath: string,
|
||||
): Promise<TFile> => {
|
||||
const data = await request({ url });
|
||||
if (!data || data.startsWith("404: Not Found")) {
|
||||
return null;
|
||||
}
|
||||
return await createOrOverwriteFile(
|
||||
this.app,
|
||||
file?.path ?? localPath,
|
||||
data,
|
||||
);
|
||||
};
|
||||
|
||||
try {
|
||||
scriptFile = await download(source, scriptFile, scriptPath);
|
||||
if (!scriptFile) {
|
||||
setButtonText("ERROR");
|
||||
throw "File not found";
|
||||
}
|
||||
svgFile = await download(
|
||||
getIMGFilename(source, "svg"),
|
||||
svgFile,
|
||||
svgPath,
|
||||
);
|
||||
setButtonText("UPTODATE");
|
||||
if (Object.keys(this.scriptEngine.scriptIconMap).length === 0) {
|
||||
this.scriptEngine.loadScripts();
|
||||
}
|
||||
const restartSidepanelTabIfActive = async () => {
|
||||
if (!this.scriptEngine || !(scriptFile instanceof TFile)) {
|
||||
return;
|
||||
}
|
||||
const scriptName = this.scriptEngine.getScriptName(scriptFile);
|
||||
const spView = ExcalidrawSidepanelView.getExisting(false);
|
||||
if (
|
||||
!spView ||
|
||||
!scriptName ||
|
||||
!spView.getTabByScript(scriptName)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await spView.restartTabForScript(scriptName);
|
||||
} catch (error) {
|
||||
errorlog({
|
||||
where:
|
||||
"ExcalidrawPlugin.registerInstallCodeblockProcessor.restartSidepanelTab",
|
||||
error,
|
||||
scriptName,
|
||||
});
|
||||
}
|
||||
};
|
||||
await restartSidepanelTabIfActive();
|
||||
new Notice(`Installed: ${scriptFile.basename}`);
|
||||
} catch (e) {
|
||||
new Notice(`Error installing script: ${fname}`);
|
||||
errorlog({
|
||||
where:
|
||||
"ExcalidrawPlugin.registerInstallCodeblockProcessor.codeblockProcessor.onClick",
|
||||
error: e,
|
||||
});
|
||||
}
|
||||
};
|
||||
if (button2) {
|
||||
button2.onclick = button.onclick;
|
||||
}
|
||||
|
||||
//check modified date on github
|
||||
//https://superuser.com/questions/1406875/how-to-get-the-latest-commit-date-of-a-file-from-a-given-github-reposotiry
|
||||
if (!scriptFile || !(scriptFile instanceof TFile)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const files = new Map<string, number>();
|
||||
JSON.parse(
|
||||
await request({
|
||||
url: URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_DIRECTORY_INFO_JSON,
|
||||
}),
|
||||
).forEach((f: RemoteDirectoryInfo) => files.set(f.fname, f.mtime));
|
||||
|
||||
const checkModifyDate = (
|
||||
gitFilename: string,
|
||||
file: TFile,
|
||||
): "ERROR" | "UPDATE" | "UPTODATE" => {
|
||||
if (files.size === 0 || !files.has(gitFilename)) {
|
||||
//setButtonText("ERROR");
|
||||
return "ERROR";
|
||||
}
|
||||
const mtime = files.get(gitFilename);
|
||||
if (!file || mtime > file.stat.mtime) {
|
||||
//setButtonText("UPDATE");
|
||||
return "UPDATE";
|
||||
}
|
||||
return "UPTODATE";
|
||||
};
|
||||
|
||||
const scriptButtonText = checkModifyDate(fname, scriptFile);
|
||||
const svgButtonText = checkModifyDate(
|
||||
getIMGFilename(fname, "svg"),
|
||||
!svgFile || !(svgFile instanceof TFile) ? null : svgFile,
|
||||
);
|
||||
|
||||
setButtonText(
|
||||
scriptButtonText === "UPTODATE" && svgButtonText === "UPTODATE"
|
||||
? "UPTODATE"
|
||||
: scriptButtonText === "UPTODATE" && svgButtonText === "ERROR"
|
||||
? "UPTODATE"
|
||||
: scriptButtonText === "ERROR"
|
||||
? "ERROR"
|
||||
: scriptButtonText === "UPDATE" || svgButtonText === "UPDATE"
|
||||
? "UPDATE"
|
||||
: "UPTODATE",
|
||||
);
|
||||
el.createEl("button", null, (button) => {
|
||||
void installButton(this, button, button2, source);
|
||||
});
|
||||
};
|
||||
|
||||
this.registerMarkdownCodeBlockProcessor(
|
||||
SCRIPT_INSTALL_CODEBLOCK,
|
||||
async (source, el) => {
|
||||
el.addEventListener(RERENDER_EVENT, async (e) => {
|
||||
e.stopPropagation();
|
||||
el.empty();
|
||||
await codeblockProcessor(source, el);
|
||||
el.addEventListener(RERENDER_EVENT, (e) => {
|
||||
void (async () => {
|
||||
e.stopPropagation();
|
||||
el.empty();
|
||||
await codeblockProcessor(source, el);
|
||||
})();
|
||||
});
|
||||
await codeblockProcessor(source, el);
|
||||
},
|
||||
@@ -1540,7 +1377,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
});
|
||||
}
|
||||
if (!keepOriginal) {
|
||||
void this.app.vault.delete(file);
|
||||
void this.app.fileManager.trashFile(file);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -1562,124 +1399,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
new Notice(`Converted ${files.length} files.`);
|
||||
}
|
||||
|
||||
private registerMonkeyPatches() {
|
||||
const key = URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES;
|
||||
|
||||
this.register(
|
||||
around(Workspace.prototype, {
|
||||
getActiveViewOfType(old) {
|
||||
return dedupe(key, old, function (...args) {
|
||||
const result = old && old.apply(this, args);
|
||||
const maybeEAView = self.app?.workspace?.activeLeaf?.view;
|
||||
if (!maybeEAView || !(maybeEAView instanceof ExcalidrawView)) {
|
||||
return result;
|
||||
}
|
||||
const error = new Error();
|
||||
const stackTrace = error.stack;
|
||||
if (!isCallerFromTemplaterPlugin(stackTrace)) {
|
||||
return result;
|
||||
}
|
||||
const leafOrNode = maybeEAView.getActiveEmbeddable();
|
||||
if (leafOrNode) {
|
||||
if (leafOrNode.node && leafOrNode.node.isEditing) {
|
||||
return {
|
||||
file: leafOrNode.node.file,
|
||||
editor: leafOrNode.node.child.editor,
|
||||
};
|
||||
}
|
||||
}
|
||||
return result;
|
||||
});
|
||||
},
|
||||
}),
|
||||
);
|
||||
if (!this.app.plugins.plugins?.["obsidian-hover-editor"]) {
|
||||
this.register(
|
||||
//stolen from hover editor
|
||||
around(WorkspaceLeaf.prototype, {
|
||||
getRoot(old) {
|
||||
return function () {
|
||||
const top = old.call(this);
|
||||
return top.getRoot === this.getRoot ? top : top.getRoot();
|
||||
};
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const self = this;
|
||||
// Monkey patch WorkspaceLeaf to open Excalidraw drawings with ExcalidrawView by default
|
||||
this.register(
|
||||
around(WorkspaceLeaf.prototype, {
|
||||
// Drawings can be viewed as markdown or Excalidraw, and we keep track of the mode
|
||||
// while the file is open. When the file closes, we no longer need to keep track of it.
|
||||
detach(next) {
|
||||
return function () {
|
||||
const state = this.view?.getState();
|
||||
|
||||
if (
|
||||
state?.file &&
|
||||
self.excalidrawFileModes[this.id || state.file]
|
||||
) {
|
||||
delete self.excalidrawFileModes[this.id || state.file];
|
||||
}
|
||||
|
||||
return next.apply(this);
|
||||
};
|
||||
},
|
||||
|
||||
setViewState(next) {
|
||||
return function (state: ViewState, ...rest: [ViewStateResult?]) {
|
||||
const markdownViewLoaded =
|
||||
self._loaded && // Don't force excalidraw mode during shutdown
|
||||
state.type === "markdown" && // If we have a markdown file
|
||||
state.state?.file;
|
||||
if (
|
||||
markdownViewLoaded &&
|
||||
self.excalidrawFileModes[this.id || state.state.file] !==
|
||||
"markdown"
|
||||
) {
|
||||
const filepath: string = state.state.file as string;
|
||||
if (
|
||||
self.forceToOpenInMarkdownFilepath !== filepath &&
|
||||
fileShouldDefaultAsExcalidraw(filepath, this.app)
|
||||
) {
|
||||
// If we have it, force the view type to excalidraw
|
||||
const newState = {
|
||||
...state,
|
||||
type: VIEW_TYPE_EXCALIDRAW,
|
||||
};
|
||||
|
||||
self.excalidrawFileModes[filepath] = VIEW_TYPE_EXCALIDRAW;
|
||||
|
||||
return next.apply(this, [newState, ...rest]);
|
||||
}
|
||||
self.forceToOpenInMarkdownFilepath = null;
|
||||
}
|
||||
|
||||
if (markdownViewLoaded) {
|
||||
const leaf = this;
|
||||
window.setTimeout(async () => {
|
||||
if (
|
||||
!leaf ||
|
||||
!leaf.view ||
|
||||
!(leaf.view instanceof MarkdownView) ||
|
||||
!leaf.view.file ||
|
||||
!self.isExcalidrawFile(leaf.view.file)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
foldExcalidrawSection(leaf.view);
|
||||
}, 500);
|
||||
}
|
||||
|
||||
return next.apply(this, [state, ...rest]);
|
||||
};
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the startup script that will add event hooks to ExcalidrawAutomate (if provided by the user)
|
||||
* Because of file operations, this must be run after the Obsidian Layout is ready
|
||||
@@ -1747,15 +1466,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.eventManager.setDebounceActiveLeafChangeHandler();
|
||||
}
|
||||
|
||||
private getPathForFile(file: File) {
|
||||
let path = "";
|
||||
const { webUtils } = require("electron");
|
||||
if (webUtils && webUtils.getPathForFile) {
|
||||
path = webUtils.getPathForFile(file);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
public registerHotkeyOverrides() {
|
||||
//this is repeated here because the same function is called when settings is closed after hotkeys have changed
|
||||
if (this.popScope) {
|
||||
@@ -1838,8 +1548,8 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.scriptEngine = null;
|
||||
}
|
||||
|
||||
if (imageCache) {
|
||||
imageCache.destroy();
|
||||
if (getImageCache()) {
|
||||
getImageCache().destroy();
|
||||
}
|
||||
|
||||
this.stylesManager.destroy();
|
||||
@@ -1887,7 +1597,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
this.lastActiveExcalidrawFilePath = null;
|
||||
|
||||
this.settings = null;
|
||||
clearMathJaxVariables();
|
||||
//pluginPackages = null;
|
||||
//PLUGIN_VERSION = null;
|
||||
delete window.PolyBool;
|
||||
@@ -1954,6 +1663,10 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
await this.saveData(encryptPersistedAPIKeys(persistedSettings));
|
||||
}
|
||||
|
||||
async onExternalSettingsChange() {
|
||||
await this.loadSettings();
|
||||
}
|
||||
|
||||
public async openSidepanel(
|
||||
reveal: boolean = true,
|
||||
): Promise<ExcalidrawSidepanelView | null> {
|
||||
@@ -1993,8 +1706,10 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
return;
|
||||
}
|
||||
visitedDocs.add(ownerDocument);
|
||||
const e = ownerDocument.createEvent("Event");
|
||||
e.initEvent(RERENDER_EVENT, true, false);
|
||||
const e = new CustomEvent(RERENDER_EVENT, {
|
||||
bubbles: true,
|
||||
cancelable: false,
|
||||
});
|
||||
ownerDocument
|
||||
.querySelectorAll(
|
||||
`.excalidraw-embedded-img${
|
||||
@@ -2043,7 +1758,6 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
await this.saveSettings();
|
||||
new RankMessage(
|
||||
this.app,
|
||||
this,
|
||||
filecount,
|
||||
rank,
|
||||
decoration,
|
||||
@@ -2132,11 +1846,11 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
await this.fileManager.renameEventHandler(file, oldPath);
|
||||
}
|
||||
|
||||
public async modifyEventHandler(file: TFile) {
|
||||
public async modifyEventHandler(file: TAbstractFile) {
|
||||
await this.fileManager.modifyEventHandler(file);
|
||||
}
|
||||
|
||||
public async deleteEventHandler(file: TFile) {
|
||||
public async deleteEventHandler(file: TAbstractFile) {
|
||||
await this.fileManager.deleteEventHandler(file);
|
||||
}
|
||||
|
||||
@@ -2213,11 +1927,7 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
switch (action) {
|
||||
case "anyFile":
|
||||
this.activeExcalidrawView.setCurrentPositionToCenter();
|
||||
const insertFileModal = new UniversalInsertFileModal(
|
||||
this,
|
||||
this.activeExcalidrawView,
|
||||
);
|
||||
insertFileModal.open();
|
||||
new UniversalInsertFileModal(this, this.activeExcalidrawView).open();
|
||||
break;
|
||||
case "LaTeX":
|
||||
insertLaTeXToView(this.activeExcalidrawView, true);
|
||||
|
||||
@@ -34,7 +34,7 @@ import { InsertImageDialog } from "../../shared/Dialogs/InsertImageDialog";
|
||||
import { ImportSVGDialog } from "../../shared/Dialogs/ImportSVGDialog";
|
||||
import { InsertMDDialog } from "../../shared/Dialogs/InsertMDDialog";
|
||||
import { ExcalidrawAutomate } from "../../shared/ExcalidrawAutomate";
|
||||
import { insertLaTeXToView, search } from "src/utils/excalidrawAutomateUtils";
|
||||
import { search } from "src/utils/excalidrawAutomateUtils";
|
||||
import { templatePromt } from "../../shared/Dialogs/Prompt";
|
||||
import { t } from "../../lang/helpers";
|
||||
import {
|
||||
@@ -49,12 +49,7 @@ import {
|
||||
getListOfTemplateFiles,
|
||||
getURLImageExtension,
|
||||
} from "../../utils/fileUtils";
|
||||
import {
|
||||
setLeftHandedMode,
|
||||
sleep,
|
||||
decompress,
|
||||
getImageSize,
|
||||
} from "../../utils/utils";
|
||||
import { setLeftHandedMode, getImageSize } from "../../utils/utils";
|
||||
import {
|
||||
extractSVGPNGFileName,
|
||||
getActivePDFPageNumberFromPDFView,
|
||||
@@ -68,7 +63,6 @@ import {
|
||||
ExcalidrawElement,
|
||||
ExcalidrawEmbeddableElement,
|
||||
ExcalidrawImageElement,
|
||||
ExcalidrawTextElement,
|
||||
FileId,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ReleaseNotes } from "../../shared/Dialogs/ReleaseNotes";
|
||||
@@ -96,6 +90,8 @@ import { insertImageToView } from "../../utils/excalidrawViewUtils";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { UIModeSettings } from "src/shared/Dialogs/UIModeSettings";
|
||||
import { PaneTarget } from "src/types/utilTypes";
|
||||
import { decompress } from "src/utils/sceneDataUtils";
|
||||
import { insertLaTeXToView } from "src/utils/excalidrawViewHelpers";
|
||||
|
||||
declare const PLUGIN_VERSION: string;
|
||||
|
||||
@@ -194,7 +190,7 @@ export class CommandManager {
|
||||
let folderpath = file.path;
|
||||
if (file instanceof TFile) {
|
||||
folderpath = normalizePath(
|
||||
file.path.substr(0, file.path.lastIndexOf(file.name)),
|
||||
file.path.substring(0, file.path.lastIndexOf(file.name)),
|
||||
);
|
||||
}
|
||||
void this.plugin.createAndOpenDrawing(
|
||||
@@ -423,7 +419,7 @@ export class CommandManager {
|
||||
if (!view) {
|
||||
return false;
|
||||
}
|
||||
if (view.leaf !== this.app.workspace.activeLeaf) {
|
||||
if (view.leaf !== this.app.workspace.getMostRecentLeaf()) {
|
||||
return false;
|
||||
}
|
||||
const editor = view.editor;
|
||||
@@ -724,10 +720,7 @@ export class CommandManager {
|
||||
}
|
||||
if (view) {
|
||||
if (!this.settings.taskboneEnabled) {
|
||||
new Notice(
|
||||
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
|
||||
4000,
|
||||
);
|
||||
new Notice(t("TASKBONE_NOT_ENABLED"), 4000);
|
||||
return true;
|
||||
}
|
||||
void this.taskbone.getTextForView(view, { forceReScan: false });
|
||||
@@ -747,10 +740,7 @@ export class CommandManager {
|
||||
}
|
||||
if (view) {
|
||||
if (!this.settings.taskboneEnabled) {
|
||||
new Notice(
|
||||
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
|
||||
4000,
|
||||
);
|
||||
new Notice(t("TASKBONE_NOT_ENABLED"), 4000);
|
||||
return true;
|
||||
}
|
||||
void this.taskbone.getTextForView(view, { forceReScan: true });
|
||||
@@ -770,10 +760,7 @@ export class CommandManager {
|
||||
}
|
||||
if (view) {
|
||||
if (!this.settings.taskboneEnabled) {
|
||||
new Notice(
|
||||
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
|
||||
4000,
|
||||
);
|
||||
new Notice(t("TASKBONE_NOT_ENABLED"), 4000);
|
||||
return true;
|
||||
}
|
||||
void this.taskbone.getTextForView(view, {
|
||||
@@ -940,6 +927,7 @@ export class CommandManager {
|
||||
|
||||
this.forceSaveCommand = this.addCommand({
|
||||
id: "save",
|
||||
//eslint-disable-next-line obsidianmd/commands/no-default-hotkeys
|
||||
hotkeys: [{ modifiers: ["Ctrl"], key: "s" }], //See also Poposcope
|
||||
name: t("FORCE_SAVE"),
|
||||
checkCallback: (checking: boolean) =>
|
||||
@@ -998,21 +986,15 @@ export class CommandManager {
|
||||
this.ea.setView(view);
|
||||
const el = this.ea.getViewSelectedElement();
|
||||
if (el.type !== "image") {
|
||||
new Notice(
|
||||
"Please select an image or embedded markdown document",
|
||||
4000,
|
||||
);
|
||||
new Notice(t("DELETE_IMAGE_NOTICE"), 4000);
|
||||
return true;
|
||||
}
|
||||
const file = this.ea.getViewFileForImageElement(el);
|
||||
if (!file) {
|
||||
new Notice(
|
||||
"Please select an image or embedded markdown document",
|
||||
4000,
|
||||
);
|
||||
new Notice(t("DELETE_IMAGE_NOTICE"), 4000);
|
||||
return true;
|
||||
}
|
||||
void this.app.vault.delete(file);
|
||||
void this.app.fileManager.trashFile(file);
|
||||
this.ea.deleteViewElements([el]);
|
||||
return true;
|
||||
}
|
||||
@@ -1053,7 +1035,6 @@ export class CommandManager {
|
||||
|
||||
this.addCommand({
|
||||
id: "insert-link",
|
||||
hotkeys: [{ modifiers: ["Mod", "Shift"], key: "k" }],
|
||||
name: t("INSERT_LINK"),
|
||||
checkCallback: (checking: boolean) => {
|
||||
if (checking) {
|
||||
@@ -1065,8 +1046,9 @@ export class CommandManager {
|
||||
if (view) {
|
||||
this.insertLinkDialog.start(
|
||||
view.file.path,
|
||||
(markdownlink: string, path: string, alias: string) =>
|
||||
view.addLink(markdownlink, path, alias),
|
||||
(markdownlink: string, path: string, alias: string) => {
|
||||
void view.addLink(markdownlink, path, alias);
|
||||
},
|
||||
);
|
||||
return true;
|
||||
}
|
||||
@@ -1075,6 +1057,7 @@ export class CommandManager {
|
||||
});
|
||||
|
||||
this.addCommand({
|
||||
// eslint-disable-next-line obsidianmd/commands/no-command-in-command-id -- this is actually the command to insert a "command" into the drawing.
|
||||
id: "insert-command",
|
||||
name: t("INSERT_COMMAND"),
|
||||
checkCallback: (checking: boolean) => {
|
||||
@@ -1086,8 +1069,9 @@ export class CommandManager {
|
||||
const view = this.app.workspace.getActiveViewOfType(ExcalidrawView);
|
||||
if (view) {
|
||||
this.insertCommandDialog.start(
|
||||
(text: string, fontFamily?: 1 | 2 | 3 | 4, save?: boolean) =>
|
||||
view.addText(text, fontFamily, save),
|
||||
(text: string, fontFamily?: 1 | 2 | 3 | 4, save?: boolean) => {
|
||||
void view.addText(text, fontFamily, save);
|
||||
},
|
||||
);
|
||||
return true;
|
||||
}
|
||||
@@ -1632,7 +1616,7 @@ export class CommandManager {
|
||||
nodes: CanvasNodeLike[];
|
||||
};
|
||||
};
|
||||
const activeView = this.app.workspace.activeLeaf?.view;
|
||||
const activeView = this.app.workspace.getMostRecentLeaf()?.view;
|
||||
const isCanvasViewLike = (
|
||||
view: typeof activeView,
|
||||
): view is CanvasViewLike =>
|
||||
@@ -1822,12 +1806,14 @@ export class CommandManager {
|
||||
|
||||
const replacer = (link: string, file: TFile) => {
|
||||
if (node.file) {
|
||||
node.file.extension === "pdf"
|
||||
? node.canvas.createFileNode({
|
||||
pos: { x: node.x + node.width + 10, y: node.y },
|
||||
file,
|
||||
})
|
||||
: node.setFile(file);
|
||||
if (node.file.extension === "pdf") {
|
||||
node.canvas.createFileNode({
|
||||
pos: { x: node.x + node.width + 10, y: node.y },
|
||||
file,
|
||||
});
|
||||
} else {
|
||||
node.setFile(file);
|
||||
}
|
||||
}
|
||||
if (node.url) {
|
||||
node.canvas.createFileNode({
|
||||
@@ -1962,7 +1948,7 @@ export class CommandManager {
|
||||
nodes: CanvasNodeLike[];
|
||||
};
|
||||
};
|
||||
const activeView = this.app.workspace.activeLeaf?.view;
|
||||
const activeView = this.app.workspace.getMostRecentLeaf()?.view;
|
||||
const isCanvasViewLike = (
|
||||
view: typeof activeView,
|
||||
): view is CanvasViewLike =>
|
||||
@@ -2060,9 +2046,7 @@ export class CommandManager {
|
||||
}
|
||||
//console.log({counter, file});
|
||||
if (!newFile || !(newFile instanceof TFile)) {
|
||||
new Notice(
|
||||
"File not found. NewExcalidraw Drawing is taking too long to create. Please try again.",
|
||||
);
|
||||
new Notice(t("ANNOTATE_IMAGE_ERROR"));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2110,12 +2094,14 @@ export class CommandManager {
|
||||
|
||||
const replacer = (link: string, file: TFile) => {
|
||||
if (node.file) {
|
||||
node.file.extension === "pdf"
|
||||
? node.canvas.createFileNode({
|
||||
pos: { x: node.x + node.width + 10, y: node.y },
|
||||
file,
|
||||
})
|
||||
: node.setFile(file);
|
||||
if (node.file.extension === "pdf") {
|
||||
node.canvas.createFileNode({
|
||||
pos: { x: node.x + node.width + 10, y: node.y },
|
||||
file,
|
||||
});
|
||||
} else {
|
||||
node.setFile(file);
|
||||
}
|
||||
}
|
||||
if (node.url) {
|
||||
node.canvas.createFileNode({
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
EventRef,
|
||||
Menu,
|
||||
FileView,
|
||||
TAbstractFile,
|
||||
} from "obsidian";
|
||||
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { getLink } from "../../utils/fileUtils";
|
||||
@@ -29,7 +30,11 @@ import {
|
||||
} from "src/constants/constants";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { setMobileNavbarPosition } from "src/utils/excalidrawViewUtils";
|
||||
import {
|
||||
getChangedTopLevelDependencyFileIDs,
|
||||
setMobileNavbarPosition,
|
||||
} from "src/utils/excalidrawViewUtils";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
|
||||
/**
|
||||
* Registers event listeners for the plugin
|
||||
@@ -101,37 +106,39 @@ export class EventManager {
|
||||
public async registerEvents() {
|
||||
await this.plugin.awaitInit();
|
||||
this.registerEvent(
|
||||
this.app.workspace.on("editor-paste", this.onPasteHandler.bind(this)),
|
||||
this.app.workspace.on("editor-paste", (evt, editor, info) =>
|
||||
this.onPasteHandler(evt, editor, info),
|
||||
),
|
||||
);
|
||||
this.registerEvent(
|
||||
this.app.vault.on("rename", this.onRenameHandler.bind(this)),
|
||||
this.app.vault.on("rename", (file, oldPath) =>
|
||||
this.onRenameHandler(file, oldPath),
|
||||
),
|
||||
);
|
||||
this.registerEvent(
|
||||
this.app.vault.on("modify", this.onModifyHandler.bind(this)),
|
||||
this.app.vault.on("modify", (file) => this.onModifyHandler(file)),
|
||||
);
|
||||
this.registerEvent(
|
||||
this.app.vault.on("delete", this.onDeleteHandler.bind(this)),
|
||||
this.app.vault.on("delete", (file) => this.onDeleteHandler(file)),
|
||||
);
|
||||
|
||||
//save Excalidraw leaf and update embeds when switching to another leaf
|
||||
this.registerEvent(
|
||||
this.plugin.app.workspace.on(
|
||||
"active-leaf-change",
|
||||
this.onActiveLeafChangeHandler.bind(this),
|
||||
this.plugin.app.workspace.on("active-leaf-change", (leaf) =>
|
||||
this.onActiveLeafChangeHandler(leaf),
|
||||
),
|
||||
);
|
||||
|
||||
this.registerEvent(
|
||||
this.app.workspace.on(
|
||||
"layout-change",
|
||||
this.onLayoutChangeHandler.bind(this),
|
||||
this.app.workspace.on("layout-change", () =>
|
||||
this.onLayoutChangeHandler(),
|
||||
),
|
||||
);
|
||||
|
||||
//File Save Trigger Handlers
|
||||
//Save the drawing if the user clicks outside the Excalidraw Canvas
|
||||
const onClickEventSaveActiveDrawing =
|
||||
this.onClickSaveActiveDrawing.bind(this);
|
||||
const onClickEventSaveActiveDrawing = (e: PointerEvent) =>
|
||||
this.onClickSaveActiveDrawing(e);
|
||||
this.app.workspace.containerEl.addEventListener(
|
||||
"click",
|
||||
onClickEventSaveActiveDrawing,
|
||||
@@ -143,9 +150,8 @@ export class EventManager {
|
||||
);
|
||||
});
|
||||
this.registerEvent(
|
||||
this.app.workspace.on(
|
||||
"file-menu",
|
||||
this.onFileMenuSaveActiveDrawing.bind(this),
|
||||
this.app.workspace.on("file-menu", () =>
|
||||
this.onFileMenuSaveActiveDrawing(),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -157,13 +163,20 @@ export class EventManager {
|
||||
);
|
||||
|
||||
this.registerEvent(
|
||||
this.app.workspace.on("file-menu", this.onFileMenuHandler.bind(this)),
|
||||
this.app.workspace.on("file-menu", (menu, file, source, leaf) => {
|
||||
if (!(file instanceof TFile)) {
|
||||
return;
|
||||
}
|
||||
this.onFileMenuHandler(menu, file, source, leaf);
|
||||
}),
|
||||
);
|
||||
this.plugin.registerEvent(
|
||||
this.plugin.app.workspace.on(
|
||||
"editor-menu",
|
||||
this.onEditorMenuHandler.bind(this),
|
||||
),
|
||||
this.plugin.app.workspace.on("editor-menu", (menu, editor, view) => {
|
||||
if (!(view instanceof MarkdownView)) {
|
||||
return;
|
||||
}
|
||||
this.onEditorMenuHandler(menu, editor, view);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -200,7 +213,11 @@ export class EventManager {
|
||||
if (data.startsWith(`{"type":"excalidraw/clipboard"`)) {
|
||||
evt.preventDefault();
|
||||
try {
|
||||
const drawing = JSON.parse(data);
|
||||
const drawing = JSON.parse(data) as {
|
||||
type: string;
|
||||
elements: ExcalidrawElement[];
|
||||
};
|
||||
|
||||
const hasOneTextElement =
|
||||
drawing.elements.filter((el: ExcalidrawElement) => el.type === "text")
|
||||
.length === 1;
|
||||
@@ -238,19 +255,25 @@ export class EventManager {
|
||||
if (element.link) {
|
||||
editorInsertText(editor, `${element.link}`);
|
||||
}
|
||||
} catch (_) {}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"Error parsing pasted Excalidraw element",
|
||||
this.onPasteHandler.bind(this),
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private onRenameHandler(file: TFile, oldPath: string) {
|
||||
private onRenameHandler(file: TAbstractFile, oldPath: string) {
|
||||
void this.plugin.renameEventHandler(file, oldPath);
|
||||
}
|
||||
|
||||
private onModifyHandler(file: TFile) {
|
||||
private onModifyHandler(file: TAbstractFile) {
|
||||
void this.plugin.modifyEventHandler(file);
|
||||
}
|
||||
|
||||
private onDeleteHandler(file: TFile) {
|
||||
private onDeleteHandler(file: TAbstractFile) {
|
||||
void this.plugin.deleteEventHandler(file);
|
||||
}
|
||||
|
||||
@@ -263,7 +286,10 @@ export class EventManager {
|
||||
|
||||
//In Obsidian 1.8.x the active excalidraw leaf is obscured by an empty leaf without a parent
|
||||
//This hack resolves it
|
||||
if (this.app.workspace.activeLeaf === leaf && isUnwantedLeaf(leaf)) {
|
||||
if (
|
||||
//this.app.workspace.getMostRecentLeaf() === leaf &&
|
||||
isUnwantedLeaf(leaf)
|
||||
) {
|
||||
leaf.detach();
|
||||
return;
|
||||
}
|
||||
@@ -292,7 +318,9 @@ export class EventManager {
|
||||
|
||||
if (this.settings.overrideObsidianFontSize) {
|
||||
if (leaf.view && leaf.view.getViewType() === VIEW_TYPE_EXCALIDRAW) {
|
||||
mainDocument.documentElement.style.fontSize = "";
|
||||
setStyle(mainDocument.documentElement, {
|
||||
fontSize: "",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,7 +386,17 @@ export class EventManager {
|
||||
if (newActiveviewEV.activeLoader) {
|
||||
return;
|
||||
}
|
||||
void newActiveviewEV.loadSceneFiles();
|
||||
const changedDependencyFileIDs =
|
||||
getChangedTopLevelDependencyFileIDs(newActiveviewEV);
|
||||
if (changedDependencyFileIDs.size > 0) {
|
||||
// Reload only top-level embeds whose own file changed or whose
|
||||
// dependency tree contains a newer nested Excalidraw file.
|
||||
newActiveviewEV.scheduleSceneFileDeferredValidation(
|
||||
changedDependencyFileIDs,
|
||||
false,
|
||||
true,
|
||||
);
|
||||
}
|
||||
}, 2000);
|
||||
} //refresh embedded files
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ import {
|
||||
openLeaf,
|
||||
} from "src/utils/obsidianUtils";
|
||||
import { errorlog, getExportTheme } from "src/utils/utils";
|
||||
import { imageCache } from "src/shared/ImageCache";
|
||||
import { getImageCache } from "src/shared/ImageCache";
|
||||
import { PaneTarget } from "src/types/utilTypes";
|
||||
|
||||
export class PluginFileManager {
|
||||
@@ -148,7 +148,7 @@ export class PluginFileManager {
|
||||
errorlog({
|
||||
file,
|
||||
error: "new drawing not recognized as an excalidraw file",
|
||||
fn: this.createDrawing,
|
||||
fn: "createDrawing",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -238,7 +238,7 @@ export class PluginFileManager {
|
||||
} catch (e) {
|
||||
errorlog({
|
||||
where: "FileManager.embedDrawing",
|
||||
fn: this.plugin.ea.onImageExportPathHook,
|
||||
fn: "plugin.ea.onImageExportPathHook",
|
||||
error: e,
|
||||
});
|
||||
}
|
||||
@@ -390,20 +390,22 @@ export class PluginFileManager {
|
||||
"my-library",
|
||||
"filename, leave blank to cancel action",
|
||||
);
|
||||
void prompt.openAndGetValue(async (filename: string) => {
|
||||
if (!filename) {
|
||||
return;
|
||||
}
|
||||
filename = `${filename}.excalidrawlib`;
|
||||
const folderpath = normalizePath(this.settings.folder);
|
||||
await checkAndCreateFolder(folderpath); //create folder if it does not exist
|
||||
const fname = getNewUniqueFilepath(
|
||||
this.app.vault,
|
||||
filename,
|
||||
folderpath,
|
||||
);
|
||||
await this.app.vault.create(fname, this.settings.library);
|
||||
new Notice(`Exported library to ${fname}`, 6000);
|
||||
void prompt.openAndGetValue((filename: string) => {
|
||||
void (async () => {
|
||||
if (!filename) {
|
||||
return;
|
||||
}
|
||||
filename = `${filename}.excalidrawlib`;
|
||||
const folderpath = normalizePath(this.settings.folder);
|
||||
await checkAndCreateFolder(folderpath); //create folder if it does not exist
|
||||
const fname = getNewUniqueFilepath(
|
||||
this.app.vault,
|
||||
filename,
|
||||
folderpath,
|
||||
);
|
||||
await this.app.vault.create(fname, this.settings.library);
|
||||
new Notice(`Exported library to ${fname}`, 6000);
|
||||
})();
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -551,8 +553,8 @@ export class PluginFileManager {
|
||||
}
|
||||
|
||||
if (
|
||||
this.app.workspace.activeLeaf?.view instanceof ExcalidrawView &&
|
||||
this.app.workspace.activeLeaf.view.file === file
|
||||
this.app.workspace.getMostRecentLeaf()?.view instanceof ExcalidrawView &&
|
||||
this.app.workspace.getMostRecentLeaf()?.view.file === file
|
||||
) {
|
||||
this.plugin.lastActiveExcalidrawFilePath = file.path;
|
||||
}
|
||||
@@ -586,10 +588,10 @@ export class PluginFileManager {
|
||||
excalidrawFile: file,
|
||||
action: "export",
|
||||
}) ?? newImgPath;
|
||||
} catch (e) {
|
||||
} catch (e: unknown) {
|
||||
errorlog({
|
||||
where: "FileManager.renameEventHandler",
|
||||
fn: this.plugin.ea.onImageExportPathHook,
|
||||
fn: "plugin.ea.onImageExportPathHook",
|
||||
error: e,
|
||||
});
|
||||
}
|
||||
@@ -610,83 +612,91 @@ export class PluginFileManager {
|
||||
});
|
||||
}
|
||||
|
||||
public async modifyEventHandler(file: TFile) {
|
||||
public async modifyEventHandler(file: TAbstractFile) {
|
||||
if (!(file instanceof TFile)) {
|
||||
return;
|
||||
}
|
||||
const excalidrawViews = getExcalidrawViews(this.app);
|
||||
excalidrawViews.forEach(async (excalidrawView) => {
|
||||
if (excalidrawView.semaphores?.viewunload) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
excalidrawView.file &&
|
||||
(excalidrawView.file.path === file.path ||
|
||||
(file.extension === "excalidraw" &&
|
||||
`${file.path.substring(
|
||||
0,
|
||||
file.path.lastIndexOf(".excalidraw"),
|
||||
)}.md` === excalidrawView.file.path))
|
||||
) {
|
||||
if (excalidrawView.semaphores?.preventReload) {
|
||||
excalidrawView.semaphores.preventReload = false;
|
||||
excalidrawViews.forEach((excalidrawView) => {
|
||||
void (async () => {
|
||||
if (excalidrawView.semaphores?.viewunload) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Avoid synchronizing or reloading if the user hasn't interacted with the file for 5 minutes.
|
||||
// This prevents complex sync issues when multiple remote changes occur outside an active collaboration session.
|
||||
|
||||
// The following logic handles a rare edge case where:
|
||||
// 1. The user opens an Excalidraw file.
|
||||
// 2. Immediately splits the view without saving Excalidraw (since no changes were made).
|
||||
// 3. Switches the new split view to Markdown, edits the file, and quickly returns to Excalidraw.
|
||||
// 4. The "modify" event may fire while Excalidraw is active, triggering an unwanted reload and zoom reset.
|
||||
|
||||
// To address this:
|
||||
// - We check if the user is currently editing the Markdown version of the Excalidraw file in a split view.
|
||||
// - As a heuristic, we also check for recent leaf switches.
|
||||
// This is not perfectly accurate (e.g., rapid switching between views within a few seconds),
|
||||
// but it is sufficient to avoid most edge cases without introducing complexity.
|
||||
|
||||
// Edge case impact:
|
||||
// - In extremely rare situations, an update arriving within the "recent switch" timeframe (e.g., from Obsidian Sync)
|
||||
// might not trigger a reload. This is unlikely and an acceptable trade-off for better user experience.
|
||||
const activeView = this.app.workspace.activeLeaf.view;
|
||||
const isEditingMarkdownSideInSplitView =
|
||||
(activeView !== excalidrawView &&
|
||||
activeView instanceof MarkdownView &&
|
||||
activeView.file === excalidrawView.file) ||
|
||||
(activeView === excalidrawView &&
|
||||
this.plugin.isRecentSplitViewSwitch());
|
||||
|
||||
if (
|
||||
!isEditingMarkdownSideInSplitView &&
|
||||
excalidrawView.lastSaveTimestamp + 300000 < Date.now()
|
||||
excalidrawView.file &&
|
||||
(excalidrawView.file.path === file.path ||
|
||||
(file.extension === "excalidraw" &&
|
||||
`${file.path.substring(
|
||||
0,
|
||||
file.path.lastIndexOf(".excalidraw"),
|
||||
)}.md` === excalidrawView.file.path))
|
||||
) {
|
||||
await excalidrawView.reload(true, excalidrawView.file);
|
||||
return;
|
||||
}
|
||||
if (file.extension === "md") {
|
||||
if (excalidrawView.semaphores?.embeddableIsEditingSelf) {
|
||||
if (excalidrawView.semaphores?.preventReload) {
|
||||
excalidrawView.semaphores.preventReload = false;
|
||||
return;
|
||||
}
|
||||
const inData = new ExcalidrawData(this.plugin);
|
||||
const data = await this.app.vault.read(file);
|
||||
await inData.loadData(data, file, getTextMode(data));
|
||||
await excalidrawView.synchronizeWithData(inData);
|
||||
inData.destroy();
|
||||
if (excalidrawView?.isDirty()) {
|
||||
if (
|
||||
excalidrawView.autosaveTimer &&
|
||||
excalidrawView.autosaveFunction
|
||||
) {
|
||||
window.clearTimeout(excalidrawView.autosaveTimer);
|
||||
|
||||
// Avoid synchronizing or reloading if the user hasn't interacted with the file for 5 minutes.
|
||||
// This prevents complex sync issues when multiple remote changes occur outside an active collaboration session.
|
||||
|
||||
// The following logic handles a rare edge case where:
|
||||
// 1. The user opens an Excalidraw file.
|
||||
// 2. Immediately splits the view without saving Excalidraw (since no changes were made).
|
||||
// 3. Switches the new split view to Markdown, edits the file, and quickly returns to Excalidraw.
|
||||
// 4. The "modify" event may fire while Excalidraw is active, triggering an unwanted reload and zoom reset.
|
||||
|
||||
// To address this:
|
||||
// - We check if the user is currently editing the Markdown version of the Excalidraw file in a split view.
|
||||
// - As a heuristic, we also check for recent leaf switches.
|
||||
// This is not perfectly accurate (e.g., rapid switching between views within a few seconds),
|
||||
// but it is sufficient to avoid most edge cases without introducing complexity.
|
||||
|
||||
// Edge case impact:
|
||||
// - In extremely rare situations, an update arriving within the "recent switch" timeframe (e.g., from Obsidian Sync)
|
||||
// might not trigger a reload. This is unlikely and an acceptable trade-off for better user experience.
|
||||
const activeView = this.app.workspace.getMostRecentLeaf()?.view;
|
||||
if (!activeView) {
|
||||
return;
|
||||
}
|
||||
const isEditingMarkdownSideInSplitView =
|
||||
(activeView !== excalidrawView &&
|
||||
activeView instanceof MarkdownView &&
|
||||
activeView.file === excalidrawView.file) ||
|
||||
(activeView === excalidrawView &&
|
||||
this.plugin.isRecentSplitViewSwitch());
|
||||
|
||||
if (
|
||||
!isEditingMarkdownSideInSplitView &&
|
||||
excalidrawView.lastSaveTimestamp + 300000 < Date.now()
|
||||
) {
|
||||
await excalidrawView.reload(true, excalidrawView.file);
|
||||
return;
|
||||
}
|
||||
if (file.extension === "md") {
|
||||
if (excalidrawView.semaphores?.embeddableIsEditingSelf) {
|
||||
return;
|
||||
}
|
||||
if (excalidrawView.autosaveFunction) {
|
||||
await excalidrawView.autosaveFunction();
|
||||
const inData = new ExcalidrawData(this.plugin);
|
||||
const data = await this.app.vault.read(file);
|
||||
await inData.loadData(data, file, getTextMode(data));
|
||||
await excalidrawView.synchronizeWithData(inData);
|
||||
inData.destroy();
|
||||
if (excalidrawView?.isDirty()) {
|
||||
if (
|
||||
excalidrawView.autosaveTimer &&
|
||||
excalidrawView.autosaveFunction
|
||||
) {
|
||||
window.clearTimeout(excalidrawView.autosaveTimer);
|
||||
}
|
||||
if (excalidrawView.autosaveFunction) {
|
||||
excalidrawView.autosaveFunction();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
await excalidrawView.reload(true, excalidrawView.file);
|
||||
}
|
||||
} else {
|
||||
await excalidrawView.reload(true, excalidrawView.file);
|
||||
}
|
||||
}
|
||||
})();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -694,10 +704,10 @@ export class PluginFileManager {
|
||||
//this will not work in a short period when Obsidian is starting up, however
|
||||
//because there is housekeeping in ImageCache at each startup to delete
|
||||
//BAK files, this is not a major issue.
|
||||
if (!imageCache.isReady() || !path) {
|
||||
if (!getImageCache().isReady() || !path) {
|
||||
return;
|
||||
}
|
||||
await imageCache.removeBAKFromCache(path);
|
||||
await getImageCache().removeBAKFromCache(path);
|
||||
}
|
||||
|
||||
private async moveBAKFile(oldPath: string, newPath: string) {
|
||||
@@ -708,12 +718,12 @@ export class PluginFileManager {
|
||||
//this will only effect a very few files, statistically unlikely to cause
|
||||
//much/any real user impact.
|
||||
//a proper queuing feels overkill for this.
|
||||
if (!imageCache.isReady()) {
|
||||
if (!getImageCache().isReady()) {
|
||||
return;
|
||||
}
|
||||
const backup = await imageCache.getBAKFromCache(oldPath);
|
||||
const backup = await getImageCache().getBAKFromCache(oldPath);
|
||||
if (backup) {
|
||||
await imageCache.addBAKToCache(newPath, `${backup}`);
|
||||
await getImageCache().addBAKToCache(newPath, `${backup}`);
|
||||
await this.removeBAKFromCache(oldPath);
|
||||
}
|
||||
}
|
||||
@@ -723,7 +733,7 @@ export class PluginFileManager {
|
||||
* @param file
|
||||
* @returns
|
||||
*/
|
||||
public async deleteEventHandler(file: TFile) {
|
||||
public async deleteEventHandler(file: TAbstractFile) {
|
||||
if (!(file instanceof TFile)) {
|
||||
return;
|
||||
}
|
||||
@@ -764,7 +774,7 @@ export class PluginFileManager {
|
||||
} catch (e) {
|
||||
errorlog({
|
||||
where: "FileManager.deleteEventHandler",
|
||||
fn: this.plugin.ea.onImageExportPathHook,
|
||||
fn: "plugin.ea.onImageExportPathHook",
|
||||
error: e,
|
||||
});
|
||||
}
|
||||
@@ -776,7 +786,7 @@ export class PluginFileManager {
|
||||
imgMap.forEach((imgPath: string) => {
|
||||
const imgFile = this.app.vault.getFileByPath(normalizePath(imgPath));
|
||||
if (imgFile) {
|
||||
void this.app.vault.delete(imgFile);
|
||||
void this.app.fileManager.trashFile(imgFile);
|
||||
}
|
||||
});
|
||||
}, 500);
|
||||
|
||||
@@ -31,21 +31,25 @@ import {
|
||||
getFileCSSClasses,
|
||||
} from "../../utils/obsidianUtils";
|
||||
import { linkClickModifierType } from "../../utils/modifierkeyHelper";
|
||||
import { ImageKey, imageCache } from "../../shared/ImageCache";
|
||||
import { ImageKey, getImageCache } from "../../shared/ImageCache";
|
||||
import { FILENAMEPARTS, PreviewImageType } from "../../types/utilTypes";
|
||||
import { CustomMutationObserver, DEBUGGING } from "../../utils/debugHelper";
|
||||
import { getExcalidrawFileForwardLinks } from "../../utils/excalidrawViewUtils";
|
||||
import { linkPrompt } from "../../shared/Dialogs/Prompt";
|
||||
import { isHTMLElement } from "../../utils/typechecks";
|
||||
import {
|
||||
isInstanceOfHTMLElement,
|
||||
isInstanceOfHTMLImageElement,
|
||||
} from "../../utils/typechecks";
|
||||
import { ExportSettings } from "src/types/exportUtilTypes";
|
||||
import { setElementDisplay } from "src/utils/htmlUtils";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
|
||||
interface imgElementAttributes {
|
||||
file?: TFile;
|
||||
fname: string; //Excalidraw filename
|
||||
fwidth: string; //Display width of image
|
||||
fheight: string; //Display height of image
|
||||
style: string[]; //css style to apply to IMG element
|
||||
imgstyle: string[]; //css style to apply to IMG element
|
||||
}
|
||||
|
||||
let plugin: ExcalidrawPlugin;
|
||||
@@ -120,7 +124,7 @@ const _getPNG = async ({
|
||||
};
|
||||
|
||||
if (cacheReady) {
|
||||
const src = await imageCache.getImageFromCache(cacheKey);
|
||||
const src = await getImageCache().getImageFromCache(cacheKey);
|
||||
//In case of PNG I cannot change the viewBox to select the area of the element
|
||||
//being referenced. For PNG only the group reference works
|
||||
if (src && typeof src === "string") {
|
||||
@@ -174,11 +178,14 @@ const _getPNG = async ({
|
||||
img.addEventListener("error", cleanup, { once: true });
|
||||
}
|
||||
|
||||
cacheReady && imageCache.addImageToCache(cacheKey, blobUrl, png);
|
||||
if (cacheReady) {
|
||||
getImageCache().addImageToCache(cacheKey, blobUrl, png);
|
||||
}
|
||||
|
||||
return img;
|
||||
};
|
||||
|
||||
const setStyle = ({
|
||||
const setImgStyle = ({
|
||||
element,
|
||||
imgAttributes,
|
||||
onCanvas,
|
||||
@@ -189,19 +196,36 @@ const setStyle = ({
|
||||
onCanvas: boolean;
|
||||
isNativeSVG: boolean;
|
||||
}) => {
|
||||
let style = "";
|
||||
if (imgAttributes.fwidth) {
|
||||
style = `${isNativeSVG ? "max-width:" : "max-width:100%; width:"}${imgAttributes.fwidth}${imgAttributes.fwidth.match(/\d$/) ? "px" : ""}; `; //width:100%;`; //removed !important https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/886
|
||||
} else {
|
||||
style = "width: fit-content;";
|
||||
}
|
||||
if (imgAttributes.fheight) {
|
||||
style += `${imgAttributes.fwidth ? "min-" : "max-"}height:${imgAttributes.fheight}px;`;
|
||||
}
|
||||
if (!onCanvas) {
|
||||
element.setAttribute("style", style);
|
||||
const styles: Partial<CSSStyleDeclaration> = {};
|
||||
|
||||
// 1. Resolve Width & Max-Width
|
||||
if (imgAttributes.fwidth) {
|
||||
const unit = imgAttributes.fwidth.match(/\d$/) ? "px" : "";
|
||||
const finalWidth = `${imgAttributes.fwidth}${unit}`;
|
||||
|
||||
if (isNativeSVG) {
|
||||
styles.maxWidth = finalWidth;
|
||||
} else {
|
||||
styles.maxWidth = "100%";
|
||||
styles.width = finalWidth;
|
||||
}
|
||||
} else {
|
||||
styles.width = "fit-content";
|
||||
}
|
||||
|
||||
// 2. Resolve Height (Min vs Max)
|
||||
if (imgAttributes.fheight) {
|
||||
const targetHeightProperty = imgAttributes.fwidth
|
||||
? "minHeight"
|
||||
: "maxHeight";
|
||||
styles[targetHeightProperty] = `${imgAttributes.fheight}px`;
|
||||
}
|
||||
|
||||
// Apply styles uniformly using the generic function
|
||||
setStyle(element, styles);
|
||||
}
|
||||
element.classList.add(...Array.from(imgAttributes.style));
|
||||
element.classList.add(...Array.from(imgAttributes.imgstyle));
|
||||
if (!element.hasClass("excalidraw-embedded-img")) {
|
||||
element.addClass("excalidraw-embedded-img");
|
||||
}
|
||||
@@ -241,7 +265,7 @@ const _getSVGIMG = async ({
|
||||
};
|
||||
|
||||
if (cacheReady) {
|
||||
const src = await imageCache.getImageFromCache(cacheKey);
|
||||
const src = await getImageCache().getImageFromCache(cacheKey);
|
||||
if (src && typeof src === "string") {
|
||||
img.setAttribute("src", src);
|
||||
return img;
|
||||
@@ -333,7 +357,7 @@ const _getSVGNative = async ({
|
||||
};
|
||||
let maybeSVG;
|
||||
if (cacheReady) {
|
||||
maybeSVG = await imageCache.getImageFromCache(cacheKey);
|
||||
maybeSVG = await getImageCache().getImageFromCache(cacheKey);
|
||||
}
|
||||
|
||||
const svg =
|
||||
@@ -380,8 +404,8 @@ const _getSVGNative = async ({
|
||||
}
|
||||
|
||||
//cache SVG should have the width and height parameters and not the embedded font
|
||||
if (!maybeSVG) {
|
||||
cacheReady && imageCache.addImageToCache(cacheKey, "", svg);
|
||||
if (!maybeSVG && cacheReady) {
|
||||
getImageCache().addImageToCache(cacheKey, "", svg);
|
||||
}
|
||||
|
||||
if (width && !isNaN(width)) {
|
||||
@@ -417,7 +441,9 @@ const getIMG = async (
|
||||
const filenameParts = getEmbeddedFilenameParts(imgAttributes.fname);
|
||||
|
||||
// https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/387
|
||||
imgAttributes.style = imgAttributes.style.map((s) => s.replaceAll(" ", "-"));
|
||||
imgAttributes.imgstyle = imgAttributes.imgstyle.map((s) =>
|
||||
s.replaceAll(" ", "-"),
|
||||
);
|
||||
|
||||
const forceTheme = hasExportTheme(plugin, file)
|
||||
? getExportTheme(plugin, file, "light")
|
||||
@@ -446,13 +472,18 @@ const getIMG = async (
|
||||
theme ? theme === "dark" : undefined,
|
||||
);
|
||||
|
||||
const cacheReady = imageCache.isReady();
|
||||
const cacheReady = getImageCache().isReady();
|
||||
|
||||
await plugin.awaitInit();
|
||||
switch (plugin.settings.previewImageType) {
|
||||
case PreviewImageType.PNG: {
|
||||
const img = createEl("img");
|
||||
setStyle({ element: img, imgAttributes, onCanvas, isNativeSVG: false });
|
||||
setImgStyle({
|
||||
element: img,
|
||||
imgAttributes,
|
||||
onCanvas,
|
||||
isNativeSVG: false,
|
||||
});
|
||||
return await _getPNG({
|
||||
imgAttributes,
|
||||
filenameParts,
|
||||
@@ -466,7 +497,12 @@ const getIMG = async (
|
||||
}
|
||||
case PreviewImageType.SVGIMG: {
|
||||
const img = createEl("img");
|
||||
setStyle({ element: img, imgAttributes, onCanvas, isNativeSVG: false });
|
||||
setImgStyle({
|
||||
element: img,
|
||||
imgAttributes,
|
||||
onCanvas,
|
||||
isNativeSVG: false,
|
||||
});
|
||||
return await _getSVGIMG({
|
||||
filenameParts,
|
||||
theme,
|
||||
@@ -479,7 +515,7 @@ const getIMG = async (
|
||||
}
|
||||
case PreviewImageType.SVG: {
|
||||
const img = createEl("div");
|
||||
setStyle({ element: img, imgAttributes, onCanvas, isNativeSVG: true });
|
||||
setImgStyle({ element: img, imgAttributes, onCanvas, isNativeSVG: true });
|
||||
return await _getSVGNative({
|
||||
filenameParts,
|
||||
theme,
|
||||
@@ -518,7 +554,9 @@ const addSVGToImgSrc = (
|
||||
img.addEventListener("error", cleanup, { once: true });
|
||||
}
|
||||
|
||||
cacheReady && imageCache.addImageToCache(cacheKey, blobUrl, blob);
|
||||
if (cacheReady) {
|
||||
getImageCache().addImageToCache(cacheKey, blobUrl, blob);
|
||||
}
|
||||
return img;
|
||||
};
|
||||
|
||||
@@ -542,7 +580,7 @@ const createImgElement = async (
|
||||
|
||||
let timer: number;
|
||||
const clickEvent = (ev: PointerEvent) => {
|
||||
if (!isHTMLElement(ev.target)) {
|
||||
if (!isInstanceOfHTMLElement(ev.target)) {
|
||||
return;
|
||||
}
|
||||
const targetElement = ev.target;
|
||||
@@ -642,32 +680,36 @@ const createImgElement = async (
|
||||
timer = null;
|
||||
});
|
||||
eventElement.addEventListener("dblclick", clickEvent);
|
||||
eventElement.addEventListener(RERENDER_EVENT, async (e) => {
|
||||
eventElement.addEventListener(RERENDER_EVENT, (e) => {
|
||||
e.stopPropagation();
|
||||
const parent = imgOrDiv.parentElement;
|
||||
const imgMaxWidth = imgOrDiv.style.maxWidth;
|
||||
const imgMaxHeigth = imgOrDiv.style.maxHeight;
|
||||
const fileSource = imgOrDiv.getAttribute("fileSource");
|
||||
const onCanvas = imgOrDiv.getAttribute("onCanvas") === "true";
|
||||
const newImg = await createImgElement(
|
||||
{
|
||||
fname: fileSource,
|
||||
fwidth: imgOrDiv.getAttribute("w"),
|
||||
fheight: imgOrDiv.getAttribute("h"),
|
||||
style: [...Array.from(imgOrDiv.classList)],
|
||||
},
|
||||
onCanvas,
|
||||
);
|
||||
if (!newImg) {
|
||||
return;
|
||||
}
|
||||
parent.empty();
|
||||
if (!onCanvas) {
|
||||
newImg.style.maxHeight = imgMaxHeigth;
|
||||
newImg.style.maxWidth = imgMaxWidth;
|
||||
}
|
||||
newImg.setAttribute("fileSource", fileSource);
|
||||
parent.append(newImg);
|
||||
void (async () => {
|
||||
const parent = imgOrDiv.parentElement;
|
||||
const imgMaxWidth = imgOrDiv.style.maxWidth;
|
||||
const imgMaxHeigth = imgOrDiv.style.maxHeight;
|
||||
const fileSource = imgOrDiv.getAttribute("fileSource");
|
||||
const onCanvas = imgOrDiv.getAttribute("onCanvas") === "true";
|
||||
const newImg = await createImgElement(
|
||||
{
|
||||
fname: fileSource,
|
||||
fwidth: imgOrDiv.getAttribute("w"),
|
||||
fheight: imgOrDiv.getAttribute("h"),
|
||||
imgstyle: [...Array.from(imgOrDiv.classList)],
|
||||
},
|
||||
onCanvas,
|
||||
);
|
||||
if (!newImg) {
|
||||
return;
|
||||
}
|
||||
parent.empty();
|
||||
if (!onCanvas) {
|
||||
setStyle(newImg, {
|
||||
maxHeight: imgMaxHeigth,
|
||||
maxWidth: imgMaxWidth,
|
||||
});
|
||||
}
|
||||
newImg.setAttribute("fileSource", fileSource);
|
||||
parent.append(newImg);
|
||||
})();
|
||||
});
|
||||
const cssClasses = getFileCSSClasses(attr.file);
|
||||
cssClasses.forEach((cssClass) => {
|
||||
@@ -691,7 +733,7 @@ const createImageDiv = async (
|
||||
onCanvas: boolean = false,
|
||||
): Promise<HTMLDivElement> => {
|
||||
const img = await createImgElement(attr, onCanvas);
|
||||
return createDiv(attr.style.join(" "), (el) => el.append(img));
|
||||
return createDiv(attr.imgstyle.join(" "), (el) => el.append(img));
|
||||
};
|
||||
|
||||
const processReadingMode = async (
|
||||
@@ -738,7 +780,7 @@ const processInternalEmbed = async (
|
||||
fname: "",
|
||||
fheight: "",
|
||||
fwidth: "",
|
||||
style: [],
|
||||
imgstyle: [],
|
||||
};
|
||||
|
||||
const src = internalEmbedEl.getAttribute("src");
|
||||
@@ -759,7 +801,7 @@ const processInternalEmbed = async (
|
||||
? internalEmbedEl.getAttribute("height")
|
||||
: getDefaultHeight(plugin);
|
||||
const alt = internalEmbedEl.getAttribute("alt");
|
||||
attr.style = ["excalidraw-svg"];
|
||||
attr.imgstyle = ["excalidraw-svg"];
|
||||
processAltText(src.split("#")[0], alt, attr);
|
||||
const fnameParts = getEmbeddedFilenameParts(src);
|
||||
attr.fname =
|
||||
@@ -811,15 +853,16 @@ function parseAlias(input: string): AliasParts {
|
||||
const parts = input.split("|").map((part) => part.trim());
|
||||
|
||||
switch (parts.length) {
|
||||
case 1:
|
||||
case 1: {
|
||||
const singleMatch = getDimensionsFromAliasString(parts[0]);
|
||||
if (singleMatch) {
|
||||
return singleMatch; // Return dimensions if valid
|
||||
}
|
||||
result.style = parts[0]; // Otherwise, return as style
|
||||
break;
|
||||
}
|
||||
|
||||
case 2:
|
||||
case 2: {
|
||||
const firstDim = getDimensionsFromAliasString(parts[0]);
|
||||
const secondDim = getDimensionsFromAliasString(parts[1]);
|
||||
|
||||
@@ -836,8 +879,9 @@ function parseAlias(input: string): AliasParts {
|
||||
result.style = parts[1]; // Assuming second part is style
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 3:
|
||||
case 3: {
|
||||
const middleMatch = getDimensionsFromAliasString(parts[1]);
|
||||
if (middleMatch) {
|
||||
result.alias = parts[0];
|
||||
@@ -849,8 +893,9 @@ function parseAlias(input: string): AliasParts {
|
||||
result.style = parts[2]; // Last part is style
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
default: {
|
||||
const secondValue = getDimensionsFromAliasString(parts[1]);
|
||||
if (secondValue) {
|
||||
result.alias = parts[0];
|
||||
@@ -862,6 +907,7 @@ function parseAlias(input: string): AliasParts {
|
||||
result.style = parts[parts.length - 1]; // Last part is style
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up the result to remove undefined properties
|
||||
@@ -884,7 +930,7 @@ const processAltText = (
|
||||
attr.fwidth = aliasParts.width ?? attr.fwidth;
|
||||
attr.fheight = aliasParts.height ?? attr.fheight;
|
||||
if (aliasParts.style && !aliasParts.style.startsWith(fname)) {
|
||||
attr.style = [`excalidraw-svg${`-${aliasParts.style}`}`];
|
||||
attr.imgstyle = [`excalidraw-svg${`-${aliasParts.style}`}`];
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -983,7 +1029,7 @@ const tmpObsidianWYSIWYG = async (
|
||||
fname: ctx.sourcePath,
|
||||
fheight: isPrinting ? "100%" : getDefaultHeight(plugin),
|
||||
fwidth: isPrinting ? "100%" : getDefaultWidth(plugin),
|
||||
style: ["excalidraw-svg"],
|
||||
imgstyle: ["excalidraw-svg"],
|
||||
};
|
||||
|
||||
attr.file = file;
|
||||
@@ -1042,15 +1088,17 @@ const tmpObsidianWYSIWYG = async (
|
||||
internalEmbedDiv.removeClass("inline-embed");
|
||||
internalEmbedDiv.addClass("media-embed");
|
||||
internalEmbedDiv.addClass("image-embed");
|
||||
if (!onCanvas && imgDiv.firstChild instanceof HTMLElement) {
|
||||
imgDiv.firstChild.style.maxHeight = "100%";
|
||||
imgDiv.firstChild.style.maxWidth = null;
|
||||
if (!onCanvas && isInstanceOfHTMLElement(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 &&
|
||||
imgDiv.firstChild instanceof HTMLImageElement
|
||||
isInstanceOfHTMLImageElement(imgDiv.firstChild)
|
||||
) {
|
||||
internalEmbedDiv.style.setProperty(
|
||||
"--popover-width",
|
||||
@@ -1060,8 +1108,10 @@ const tmpObsidianWYSIWYG = async (
|
||||
"--popover-height",
|
||||
`${attr.fheight}px`,
|
||||
);
|
||||
internalEmbedDiv.style.width = "var(--popover-width)";
|
||||
internalEmbedDiv.style.height = "var(--popover-height)";
|
||||
setStyle(internalEmbedDiv, {
|
||||
width: "var(--popover-width)",
|
||||
height: "var(--popover-height)",
|
||||
});
|
||||
}
|
||||
internalEmbedDiv.appendChild(imgDiv.firstChild);
|
||||
return;
|
||||
@@ -1096,11 +1146,13 @@ const tmpObsidianWYSIWYG = async (
|
||||
if (timer) {
|
||||
window.clearTimeout(timer);
|
||||
}
|
||||
timer = window.setTimeout(async () => {
|
||||
timer = window.setTimeout(() => {
|
||||
timer = null;
|
||||
internalEmbedDiv.empty();
|
||||
const imgDiv = await processInternalEmbed(internalEmbedDiv, file);
|
||||
internalEmbedDiv.appendChild(imgDiv);
|
||||
void (async () => {
|
||||
const imgDiv = await processInternalEmbed(internalEmbedDiv, file);
|
||||
internalEmbedDiv.appendChild(imgDiv);
|
||||
})();
|
||||
}, 500);
|
||||
};
|
||||
const observer = DEBUGGING
|
||||
@@ -1197,7 +1249,7 @@ export const markdownPostProcessor = async (
|
||||
//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?.hasOwnProperty("excalidraw-plugin"),
|
||||
ctx.frontmatter && "excalidraw-plugin" in ctx.frontmatter,
|
||||
);
|
||||
if (!(isPreview || isMarkdownReadingMode || isPrinting) && excalidrawFile) {
|
||||
setElementDisplay(el, "none");
|
||||
@@ -1224,7 +1276,7 @@ export const hoverEvent = (
|
||||
};
|
||||
|
||||
//monitoring for div.popover.hover-popover.file-embed.is-loaded to be added to the DOM tree
|
||||
const legacyExcalidrawPopoverObserverFn: MutationCallback = async (m) => {
|
||||
const legacyExcalidrawPopoverObserverFn: MutationCallback = (m) => {
|
||||
if (m.length === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -1279,25 +1331,30 @@ const legacyExcalidrawPopoverObserverFn: MutationCallback = async (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
|
||||
const img = await getIMG({
|
||||
file,
|
||||
fname: file.path,
|
||||
fwidth: "300",
|
||||
fheight: null,
|
||||
style: ["excalidraw-svg"],
|
||||
});
|
||||
const div = createDiv("", async (el) => {
|
||||
el.appendChild(img);
|
||||
el.setAttribute("src", file.path);
|
||||
el.onClickEvent((ev) => {
|
||||
ev.stopImmediatePropagation();
|
||||
const src = el.getAttribute("src");
|
||||
if (src) {
|
||||
plugin.openDrawing(vault.getFileByPath(src), linkClickModifierType(ev));
|
||||
} //.ctrlKey||ev.metaKey);
|
||||
void (async () => {
|
||||
const img = await getIMG({
|
||||
file,
|
||||
fname: file.path,
|
||||
fwidth: "300",
|
||||
fheight: null,
|
||||
imgstyle: ["excalidraw-svg"],
|
||||
});
|
||||
});
|
||||
node.appendChild(div);
|
||||
const div = createDiv("", (el) => {
|
||||
el.appendChild(img);
|
||||
el.setAttribute("src", file.path);
|
||||
el.onClickEvent((ev) => {
|
||||
ev.stopImmediatePropagation();
|
||||
const src = el.getAttribute("src");
|
||||
if (src) {
|
||||
plugin.openDrawing(
|
||||
vault.getFileByPath(src),
|
||||
linkClickModifierType(ev),
|
||||
);
|
||||
} //.ctrlKey||ev.metaKey);
|
||||
});
|
||||
});
|
||||
node.appendChild(div);
|
||||
})();
|
||||
};
|
||||
|
||||
export const legacyExcalidrawPopoverObserver = DEBUGGING
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
import {
|
||||
MarkdownView,
|
||||
View,
|
||||
ViewState,
|
||||
ViewStateResult,
|
||||
Workspace,
|
||||
WorkspaceLeaf,
|
||||
} from "obsidian";
|
||||
import { around, dedupe } from "monkey-around";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import { VIEW_TYPE_EXCALIDRAW } from "src/constants/constants";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { fileShouldDefaultAsExcalidraw } from "src/utils/fileUtils";
|
||||
import { foldExcalidrawSection } from "src/utils/obsidianUtils";
|
||||
import type ExcalidrawView from "src/view/ExcalidrawView";
|
||||
|
||||
type ViewConstructor<T extends View = View> = new (...args: unknown[]) => T;
|
||||
|
||||
/**
|
||||
* Registers workspace monkey patches that adapt Obsidian behavior
|
||||
* for Excalidraw and known plugin integrations.
|
||||
*/
|
||||
export class MonkeyPatchManager {
|
||||
private readonly plugin: ExcalidrawPlugin;
|
||||
|
||||
constructor(plugin: ExcalidrawPlugin) {
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
public initialize(): void {
|
||||
this.patchTemplaterGetActiveViewOfType();
|
||||
this.patchHoverEditorGetRoot();
|
||||
this.patchWorkspaceLeafExcalidrawDefault();
|
||||
}
|
||||
|
||||
private patchTemplaterGetActiveViewOfType(): void {
|
||||
const key = URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES;
|
||||
|
||||
this.plugin.register(
|
||||
around(Workspace.prototype, {
|
||||
getActiveViewOfType(old: Workspace["getActiveViewOfType"]) {
|
||||
return dedupe(key, old, function <
|
||||
T extends View,
|
||||
>(this: Workspace, type: ViewConstructor<T>): T | null {
|
||||
const result = old.call(this, type) as T | null;
|
||||
const maybeEAView = this.getMostRecentLeaf()?.view;
|
||||
if (
|
||||
!maybeEAView ||
|
||||
maybeEAView.getViewType() !== VIEW_TYPE_EXCALIDRAW
|
||||
) {
|
||||
return result;
|
||||
}
|
||||
const stackTrace = new Error().stack ?? "";
|
||||
if (!MonkeyPatchManager.isCallerFromTemplaterPlugin(stackTrace)) {
|
||||
return result;
|
||||
}
|
||||
const leafOrNode = (
|
||||
maybeEAView as ExcalidrawView
|
||||
).getActiveEmbeddable();
|
||||
if (leafOrNode?.node?.isEditing) {
|
||||
return {
|
||||
file: leafOrNode.node.file,
|
||||
editor: leafOrNode.node.child.editor,
|
||||
} as unknown as T;
|
||||
}
|
||||
return result;
|
||||
});
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private patchHoverEditorGetRoot(): void {
|
||||
if (this.plugin.app.plugins.plugins?.["obsidian-hover-editor"]) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.plugin.register(
|
||||
// Stolen from hover editor.
|
||||
around(WorkspaceLeaf.prototype, {
|
||||
getRoot(old: WorkspaceLeaf["getRoot"]) {
|
||||
return function (
|
||||
this: WorkspaceLeaf,
|
||||
): ReturnType<WorkspaceLeaf["getRoot"]> {
|
||||
const top = old.call(this) as WorkspaceLeaf;
|
||||
return top.getRoot === this.getRoot ? top : top.getRoot();
|
||||
};
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private patchWorkspaceLeafExcalidrawDefault(): void {
|
||||
const plugin = this.plugin;
|
||||
|
||||
this.plugin.register(
|
||||
around(WorkspaceLeaf.prototype, {
|
||||
// Drawings can be viewed as markdown or Excalidraw, and we keep track of the mode
|
||||
// while the file is open. When the file closes, we no longer need to keep track of it.
|
||||
detach(next: WorkspaceLeaf["detach"]) {
|
||||
return function (
|
||||
this: WorkspaceLeaf,
|
||||
): ReturnType<WorkspaceLeaf["detach"]> {
|
||||
const state = this.view?.getState();
|
||||
const stateFile =
|
||||
typeof state?.file === "string" ? state.file : null;
|
||||
const leafKey = this.id || stateFile;
|
||||
|
||||
if (leafKey && plugin.excalidrawFileModes[leafKey]) {
|
||||
delete plugin.excalidrawFileModes[leafKey];
|
||||
}
|
||||
|
||||
return next.apply(this) as ReturnType<WorkspaceLeaf["detach"]>;
|
||||
};
|
||||
},
|
||||
|
||||
setViewState(next: WorkspaceLeaf["setViewState"]) {
|
||||
return function (
|
||||
this: WorkspaceLeaf,
|
||||
state: ViewState,
|
||||
...rest: [ViewStateResult?]
|
||||
): ReturnType<WorkspaceLeaf["setViewState"]> {
|
||||
const filePath = state.state?.file;
|
||||
const markdownViewLoaded =
|
||||
plugin._loaded && // Do not force Excalidraw mode during shutdown.
|
||||
state.type === "markdown" &&
|
||||
typeof filePath === "string";
|
||||
|
||||
if (
|
||||
markdownViewLoaded &&
|
||||
plugin.excalidrawFileModes[this.id || filePath] !== "markdown"
|
||||
) {
|
||||
if (
|
||||
plugin.forceToOpenInMarkdownFilepath !== filePath &&
|
||||
fileShouldDefaultAsExcalidraw(filePath, plugin.app)
|
||||
) {
|
||||
const newState: ViewState = {
|
||||
...state,
|
||||
type: VIEW_TYPE_EXCALIDRAW,
|
||||
};
|
||||
|
||||
plugin.excalidrawFileModes[filePath] = VIEW_TYPE_EXCALIDRAW;
|
||||
|
||||
return next.apply(this, [newState, ...rest]) as ReturnType<
|
||||
WorkspaceLeaf["setViewState"]
|
||||
>;
|
||||
}
|
||||
plugin.forceToOpenInMarkdownFilepath = null;
|
||||
}
|
||||
|
||||
if (markdownViewLoaded) {
|
||||
window.setTimeout(() => {
|
||||
if (
|
||||
!(this.view instanceof MarkdownView) ||
|
||||
!this.view.file ||
|
||||
!plugin.isExcalidrawFile(this.view.file)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
foldExcalidrawSection(this.view);
|
||||
}, 500);
|
||||
}
|
||||
|
||||
return next.apply(this, [state, ...rest]) as ReturnType<
|
||||
WorkspaceLeaf["setViewState"]
|
||||
>;
|
||||
};
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private static isCallerFromTemplaterPlugin(stackTrace: string): boolean {
|
||||
const lines = stackTrace.split("\n");
|
||||
for (const line of lines) {
|
||||
if (line.trim().startsWith("at Templater.")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,10 @@ import {
|
||||
isObsidianThemeDark,
|
||||
} from "src/utils/obsidianUtils";
|
||||
import { App, Notice, TFile } from "obsidian";
|
||||
import {
|
||||
isInstanceOfDocumentFragment,
|
||||
isInstanceOfElement,
|
||||
} from "src/utils/typechecks";
|
||||
|
||||
export class ObserverManager {
|
||||
private plugin: ExcalidrawPlugin;
|
||||
@@ -80,9 +84,7 @@ export class ObserverManager {
|
||||
return;
|
||||
}
|
||||
|
||||
const themeObserverFn: MutationCallback = async (
|
||||
mutations: MutationRecord[],
|
||||
) => {
|
||||
const themeObserverFn: MutationCallback = (mutations: MutationRecord[]) => {
|
||||
const { matchThemeTrigger } = this.settings;
|
||||
if (!matchThemeTrigger) {
|
||||
return;
|
||||
@@ -178,11 +180,14 @@ export class ObserverManager {
|
||||
mutationsList.forEach((mutation) => {
|
||||
if (mutation.type === "childList") {
|
||||
mutation.addedNodes.forEach((node) => {
|
||||
if (node instanceof Element || node instanceof DocumentFragment) {
|
||||
if (
|
||||
isInstanceOfElement(node) ||
|
||||
isInstanceOfDocumentFragment(node)
|
||||
) {
|
||||
ensureFiletypes(node);
|
||||
}
|
||||
});
|
||||
if (mutation.target instanceof Element) {
|
||||
if (isInstanceOfElement(mutation.target)) {
|
||||
// Handles folders that were collapsed/expanded without adding nodes
|
||||
ensureFiletypes(mutation.target);
|
||||
}
|
||||
@@ -191,7 +196,7 @@ export class ObserverManager {
|
||||
|
||||
if (
|
||||
mutation.type === "attributes" &&
|
||||
mutation.target instanceof Element
|
||||
isInstanceOfElement(mutation.target)
|
||||
) {
|
||||
ensureFiletypes(mutation.target);
|
||||
}
|
||||
@@ -237,7 +242,7 @@ export class ObserverManager {
|
||||
const added = Array.from(mutation.addedNodes ?? []);
|
||||
const hasContainer = added.some(
|
||||
(node) =>
|
||||
node instanceof Element &&
|
||||
isInstanceOfElement(node) &&
|
||||
(node.matches?.(".nav-files-container") ||
|
||||
node.querySelector?.(".nav-files-container")),
|
||||
);
|
||||
@@ -276,7 +281,7 @@ export class ObserverManager {
|
||||
this.removeModalContainerObserver();
|
||||
}
|
||||
//The user clicks settings, or "open another vault", or the command palette
|
||||
const modalContainerObserverFn: MutationCallback = async (
|
||||
const modalContainerObserverFn: MutationCallback = (
|
||||
m: MutationRecord[],
|
||||
) => {
|
||||
const view = this.plugin.activeExcalidrawView;
|
||||
@@ -293,7 +298,7 @@ export class ObserverManager {
|
||||
|
||||
const { errorMessage } = view.excalidrawAPI.getAppState();
|
||||
if (!errorMessage) {
|
||||
await this.plugin.activeExcalidrawView.save();
|
||||
void this.plugin.activeExcalidrawView.save();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -112,13 +112,18 @@ export class StylesManager {
|
||||
|
||||
const iframeDoc = iframe.contentWindow.document;
|
||||
const iframeWin = iframe.contentWindow;
|
||||
|
||||
iframeDoc.open();
|
||||
iframeDoc.write(`<head>${mainDocument.head.innerHTML}</head>`);
|
||||
iframeDoc.close();
|
||||
iframeDoc.close(); // Closes the stream to clear out the default page skeleton
|
||||
const newHead = iframeDoc.createElement("head");
|
||||
Array.from(mainDocument.head.children).forEach((child) => {
|
||||
newHead.appendChild(child.cloneNode(true));
|
||||
});
|
||||
iframeDoc.documentElement.replaceChild(newHead, iframeDoc.head);
|
||||
|
||||
await iframeLoadedPromise;
|
||||
|
||||
const iframeBody = iframe.contentWindow.document.body;
|
||||
const iframeBody = iframeDoc.body;
|
||||
iframeBody.setAttribute("style", body.getAttribute("style"));
|
||||
iframeBody.setAttribute("class", body.getAttribute("class"));
|
||||
|
||||
@@ -164,7 +169,6 @@ export class StylesManager {
|
||||
);
|
||||
} else {
|
||||
const lightStyleTag = doc.createElement("style");
|
||||
lightStyleTag.type = "text/css";
|
||||
lightStyleTag.setAttribute("id", "excalidraw-embedded-light");
|
||||
setStyleText(
|
||||
lightStyleTag,
|
||||
@@ -173,7 +177,6 @@ export class StylesManager {
|
||||
doc.head.appendChild(lightStyleTag);
|
||||
|
||||
const darkStyleTag = doc.createElement("style");
|
||||
darkStyleTag.type = "text/css";
|
||||
darkStyleTag.setAttribute("id", "excalidraw-embedded-dark");
|
||||
setStyleText(
|
||||
darkStyleTag,
|
||||
|
||||
+132
-81
@@ -29,7 +29,7 @@ import {
|
||||
import { PENS } from "src/utils/pens";
|
||||
import { addYouTubeThumbnail, fragWithHTML } from "src/utils/utils";
|
||||
import { setElementIconAndText, setSanitizedHtml } from "src/utils/htmlUtils";
|
||||
import { imageCache } from "src/shared/ImageCache";
|
||||
import { getImageCache } from "src/shared/ImageCache";
|
||||
import { MultiOptionConfirmationPrompt } from "src/shared/Dialogs/Prompt";
|
||||
import { EmbeddableMDCustomProps } from "src/shared/Dialogs/EmbeddableSettings";
|
||||
import { EmbeddalbeMDFileCustomDataSettingsComponent } from "src/shared/Dialogs/EmbeddableMDFileCustomDataSettingsComponent";
|
||||
@@ -70,8 +70,10 @@ import { getAIUsage, formatAIUsageLabel } from "src/utils/AIUtils";
|
||||
import { decryptProviderProfiles } from "src/utils/settingsKeyObfuscation";
|
||||
import { getGeminiSupportedSizes } from "src/utils/geminiImageModelUtils";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { hideElement, setStyle, showElement } from "src/utils/styleUtils";
|
||||
|
||||
export interface ExcalidrawSettings {
|
||||
showTabTitlebarButtons: boolean;
|
||||
copyLinkToElemenetAnchorTo100: boolean;
|
||||
copyFrameLinkByName: boolean;
|
||||
disableDoubleClickTextEditing: boolean;
|
||||
@@ -555,6 +557,7 @@ export const cloneModelConfigs = <TConfig extends AIModelConfig>(
|
||||
) as Record<string, TConfig>;
|
||||
|
||||
export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
showTabTitlebarButtons: true,
|
||||
copyLinkToElemenetAnchorTo100: false,
|
||||
copyFrameLinkByName: false,
|
||||
disableDoubleClickTextEditing: false,
|
||||
@@ -745,6 +748,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
borderColor: "#fff",
|
||||
borderOpacity: 0,
|
||||
filenameVisible: false,
|
||||
lockedReadingMode: false,
|
||||
},
|
||||
markdownNodeOneClickEditing: false,
|
||||
canvasImmersiveEmbed: true,
|
||||
@@ -1230,34 +1234,38 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}
|
||||
}
|
||||
|
||||
async hide() {
|
||||
hide() {
|
||||
this.detachSettingsFocusoutHandler();
|
||||
if (this.plugin.settings.overrideObsidianFontSize) {
|
||||
mainDocument.documentElement.style.fontSize = "";
|
||||
setStyle(mainDocument.documentElement, { fontSize: "" });
|
||||
setRootElementSize(16);
|
||||
} else if (!mainDocument.documentElement.style.fontSize) {
|
||||
mainDocument.documentElement.style.fontSize = getComputedStyle(
|
||||
mainDocument.body,
|
||||
).getPropertyValue("--font-text-size");
|
||||
setStyle(mainDocument.documentElement, {
|
||||
fontSize: getComputedStyle(mainDocument.body).getPropertyValue(
|
||||
"--font-text-size",
|
||||
),
|
||||
});
|
||||
setRootElementSize();
|
||||
}
|
||||
|
||||
await this.persistDirtySettings();
|
||||
await this.applyPendingActions();
|
||||
this.hotkeyEditor.unload();
|
||||
if (this.hotkeyEditor.isDirty) {
|
||||
this.plugin.registerHotkeyOverrides();
|
||||
}
|
||||
this.plugin.scriptEngine.updateScriptPath();
|
||||
void (async () => {
|
||||
void (await this.persistDirtySettings());
|
||||
void (await this.applyPendingActions());
|
||||
this.hotkeyEditor.unload();
|
||||
if (this.hotkeyEditor.isDirty) {
|
||||
this.plugin.registerHotkeyOverrides();
|
||||
}
|
||||
this.plugin.scriptEngine.updateScriptPath();
|
||||
})();
|
||||
/* if(this.reloadMathJax) {
|
||||
this.plugin.loadMathJax();
|
||||
}*/
|
||||
}
|
||||
|
||||
async display() {
|
||||
display() {
|
||||
let detailsEl: HTMLElement;
|
||||
|
||||
await this.plugin.loadSettings(); //in case sync loaded changed settings in the background
|
||||
//await this.plugin.loadSettings(); //in case sync loaded changed settings in the background
|
||||
this.settingsDirty = false;
|
||||
this.requestEmbedUpdate = false;
|
||||
this.requestReloadDrawings = false;
|
||||
@@ -1312,7 +1320,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
"span",
|
||||
{
|
||||
cls: "excalidraw-mastery-promo__summary-title",
|
||||
text: "Excalidraw Mastery",
|
||||
text: t("EXCALIDRAW_MASTERY"),
|
||||
},
|
||||
);
|
||||
const excalidrawMasterySummaryState = excalidrawMasterySummary.createEl(
|
||||
@@ -1504,7 +1512,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("FOLDER_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: Excalidraw")
|
||||
.setPlaceholder(t("FOLDER_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.folder)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.folder = value;
|
||||
@@ -1529,7 +1537,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("CROP_FOLDER_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: Excalidraw/Cropped")
|
||||
.setPlaceholder(t("CROP_FOLDER_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.cropFolder)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.cropFolder = value;
|
||||
@@ -1542,7 +1550,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("ANNOTATE_FOLDER_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: Excalidraw/Annotations")
|
||||
.setPlaceholder(t("ANNOTATE_FOLDER_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.annotateFolder)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.annotateFolder = value;
|
||||
@@ -1555,7 +1563,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("TEMPLATE_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: Excalidraw/Template")
|
||||
.setPlaceholder(t("TEMPLATE_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.templateFilePath)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.templateFilePath = value;
|
||||
@@ -1569,7 +1577,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("SCRIPT_FOLDER_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: Excalidraw/Scripts")
|
||||
.setPlaceholder(t("SCRIPT_FOLDER_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.scriptFolderPath)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.scriptFolderPath = value;
|
||||
@@ -1681,7 +1689,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("FILENAME_PREFIX_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: Drawing ")
|
||||
.setPlaceholder(t("FILENAME_PREFIX_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.drawingFilenamePrefix)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.drawingFilenamePrefix = value.replaceAll(
|
||||
@@ -1761,7 +1769,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("CROP_PREFIX_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: cropped_")
|
||||
.setPlaceholder(t("CROP_PREFIX_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.cropPrefix)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.cropPrefix = value.replaceAll(
|
||||
@@ -1778,7 +1786,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("CROP_SUFFIX_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: _cropped")
|
||||
.setPlaceholder(t("CROP_SUFFIX_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.cropSuffix)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.cropSuffix = value.replaceAll(
|
||||
@@ -1795,7 +1803,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("ANNOTATE_PREFIX_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: annotated_")
|
||||
.setPlaceholder(t("ANNOTATE_PREFIX_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.annotatePrefix)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.annotatePrefix = value.replaceAll(
|
||||
@@ -1812,7 +1820,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("ANNOTATE_SUFFIX_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: _annotated")
|
||||
.setPlaceholder(t("ANNOTATE_SUFFIX_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.annotateSuffix)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.annotateSuffix = value.replaceAll(
|
||||
@@ -1857,12 +1865,22 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
toggle
|
||||
.setValue(this.plugin.settings.aiEnabled ?? true)
|
||||
.onChange(async (value) => {
|
||||
aiEl.style.display = value ? "block" : "none";
|
||||
if (value) {
|
||||
showElement(aiEl);
|
||||
} else {
|
||||
hideElement(aiEl);
|
||||
}
|
||||
this.plugin.settings.aiEnabled = value;
|
||||
this.applySettingsUpdate();
|
||||
}),
|
||||
);
|
||||
|
||||
detailsEl = detailsEl.createDiv();
|
||||
const aiEl = detailsEl;
|
||||
if (!(this.plugin.settings.aiEnabled ?? true)) {
|
||||
hideElement(detailsEl);
|
||||
}
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("AI_USAGE_SETTINGS_BUTTON_NAME"))
|
||||
.setDesc(t("AI_USAGE_SETTINGS_BUTTON_DESC"))
|
||||
@@ -1889,12 +1907,6 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}),
|
||||
);
|
||||
|
||||
detailsEl = detailsEl.createDiv();
|
||||
const aiEl = detailsEl;
|
||||
if (!(this.plugin.settings.aiEnabled ?? true)) {
|
||||
detailsEl.style.display = "none";
|
||||
}
|
||||
|
||||
let selectedProviderProfile =
|
||||
Object.keys(this.plugin.settings.aiProviderProfiles ?? {})[0] || "OpenAI";
|
||||
let selectedTextModelConfig =
|
||||
@@ -2281,8 +2293,10 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
)
|
||||
.setDesc(fragWithHTML(description))
|
||||
.addDropdown((dropdown) => {
|
||||
optionValues.forEach((value) => dropdown.addOption(value, value));
|
||||
return dropdown.setValue(selectedValue).onChange(async (value) => {
|
||||
optionValues.forEach((value) => {
|
||||
void dropdown.addOption(value, value);
|
||||
});
|
||||
return dropdown.setValue(selectedValue).onChange((value) => {
|
||||
if (kind === "text") {
|
||||
selectedTextModelConfig = value;
|
||||
this.plugin.settings.aiDefaultTextModel = value;
|
||||
@@ -2387,7 +2401,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
text
|
||||
.setPlaceholder(placeholder)
|
||||
.setValue(getter().toString())
|
||||
.onChange(async (value) => {
|
||||
.onChange((value) => {
|
||||
const intVal = parseInt(value, 10);
|
||||
if (isNaN(intVal) && value !== "") {
|
||||
text.setValue(getter().toString());
|
||||
@@ -2503,6 +2517,24 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
cls: "excalidraw-setting-h3",
|
||||
});
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("SHOW_TAB_TITLEBAR_BUTTONS"))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(this.plugin.settings.showTabTitlebarButtons)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.showTabTitlebarButtons = value;
|
||||
this.applySettingsUpdate();
|
||||
getExcalidrawViews(this.app, true).forEach((excalidrawView) => {
|
||||
if (value) {
|
||||
excalidrawView.addTabTitlebarButtons();
|
||||
} else {
|
||||
excalidrawView.removeTabTitlebarButtons();
|
||||
}
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
new UIModeSettingsComponent(detailsEl, this.plugin.settings, this.app, () =>
|
||||
this.applySettingsUpdate(),
|
||||
).render();
|
||||
@@ -2520,7 +2552,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
this.hotkeyEditor = new HotkeyEditor(
|
||||
detailsEl,
|
||||
this.plugin.settings,
|
||||
this.applySettingsUpdate,
|
||||
(x: boolean = false) => this.applySettingsUpdate(x),
|
||||
);
|
||||
this.hotkeyEditor.onload();
|
||||
|
||||
@@ -2547,9 +2579,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("DYNAMICSTYLE_DESC")))
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOption("none", "Dynamic Styling OFF")
|
||||
.addOption("colorful", "Match color")
|
||||
.addOption("gray", "Gray, match tone")
|
||||
.addOption("none", t("DYNAMICSTYLE_OPTION_NONE"))
|
||||
.addOption("colorful", t("DYNAMICSTYLE_OPTION_COLORFUL"))
|
||||
.addOption("gray", t("DYNAMICSTYLE_OPTION_GRAY"))
|
||||
.setValue(this.plugin.settings.dynamicStyling)
|
||||
.onChange(async (value) => {
|
||||
this.requestUpdateDynamicStyling = true;
|
||||
@@ -2618,10 +2650,10 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("DEFAULT_OPEN_MODE_DESC")))
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOption("normal", "Always in normal-mode")
|
||||
.addOption("zen", "Always in zen-mode")
|
||||
.addOption("view", "Always in view-mode")
|
||||
.addOption("view-mobile", "Usually normal, but view-mode on Phone")
|
||||
.addOption("normal", t("DEFAULT_OPEN_MODE_OPTION_NORMAL"))
|
||||
.addOption("zen", t("DEFAULT_OPEN_MODE_OPTION_ZEN"))
|
||||
.addOption("view", t("DEFAULT_OPEN_MODE_OPTION_VIEW"))
|
||||
.addOption("view-mobile", t("DEFAULT_OPEN_MODE_OPTION_VIEW_MOBILE"))
|
||||
.setValue(this.plugin.settings.defaultMode)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.defaultMode = value;
|
||||
@@ -2782,9 +2814,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("DEFAULT_PEN_MODE_DESC")))
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOption("never", "Never")
|
||||
.addOption("mobile", "On Obsidian Mobile")
|
||||
.addOption("always", "Always")
|
||||
.addOption("never", t("DEFAULT_PEN_MODE_OPTION_NEVER"))
|
||||
.addOption("mobile", t("DEFAULT_PEN_MODE_OPTION_MOBILE"))
|
||||
.addOption("always", t("DEFAULT_PEN_MODE_OPTION_ALWAYS"))
|
||||
.setValue(this.plugin.settings.defaultPenMode)
|
||||
.onChange(async (value: "never" | "always" | "mobile") => {
|
||||
this.plugin.settings.defaultPenMode = value;
|
||||
@@ -2899,7 +2931,11 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setValue(this.plugin.settings.gridSettings.DYNAMIC_COLOR)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.gridSettings.DYNAMIC_COLOR = value;
|
||||
gridColorSection.style.display = value ? "none" : "block";
|
||||
if (value) {
|
||||
hideElement(gridColorSection);
|
||||
} else {
|
||||
showElement(gridColorSection);
|
||||
}
|
||||
this.applySettingsUpdate();
|
||||
updateGridColor();
|
||||
}),
|
||||
@@ -2907,10 +2943,11 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
|
||||
// Create a div to contain color and opacity settings
|
||||
const gridColorSection = detailsEl.createDiv();
|
||||
gridColorSection.style.display = this.plugin.settings.gridSettings
|
||||
.DYNAMIC_COLOR
|
||||
? "none"
|
||||
: "block";
|
||||
if (this.plugin.settings.gridSettings.DYNAMIC_COLOR) {
|
||||
hideElement(gridColorSection);
|
||||
} else {
|
||||
showElement(gridColorSection);
|
||||
}
|
||||
|
||||
// Grid color picker
|
||||
new Setting(gridColorSection)
|
||||
@@ -3038,7 +3075,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
new ModifierKeySettingsComponent(
|
||||
detailsEl,
|
||||
this.plugin.settings.modifierKeyConfig,
|
||||
this.applySettingsUpdate.bind(this),
|
||||
() => this.applySettingsUpdate(),
|
||||
).render();
|
||||
|
||||
// ------------------------------------------------
|
||||
@@ -3357,9 +3394,18 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("EMBED_PREVIEW_IMAGETYPE_DESC")))
|
||||
.addDropdown((dropdown) =>
|
||||
dropdown
|
||||
.addOption(PreviewImageType.PNG, "PNG Image")
|
||||
.addOption(PreviewImageType.SVG, "Native SVG")
|
||||
.addOption(PreviewImageType.SVGIMG, "SVG Image")
|
||||
.addOption(
|
||||
PreviewImageType.PNG,
|
||||
t("EMBED_PREVIEW_IMAGETYPE_OPTION_PNG"),
|
||||
)
|
||||
.addOption(
|
||||
PreviewImageType.SVG,
|
||||
t("EMBED_PREVIEW_IMAGETYPE_OPTION_SVG"),
|
||||
)
|
||||
.addOption(
|
||||
PreviewImageType.SVGIMG,
|
||||
t("EMBED_PREVIEW_IMAGETYPE_OPTION_SVGIMG"),
|
||||
)
|
||||
.setValue(this.plugin.settings.previewImageType)
|
||||
.onChange((value) => {
|
||||
this.plugin.settings.previewImageType = value as PreviewImageType;
|
||||
@@ -3376,7 +3422,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("EMBED_TYPE_DESC")))
|
||||
.addDropdown(async (d: DropdownComponent) => {
|
||||
dropdown = d;
|
||||
dropdown.addOption("excalidraw", "excalidraw");
|
||||
dropdown.addOption("excalidraw", "Excalidraw");
|
||||
if (this.plugin.settings.autoexportPNG) {
|
||||
dropdown.addOption("PNG", "PNG");
|
||||
} else if (this.plugin.settings.embedType === "PNG") {
|
||||
@@ -3394,8 +3440,11 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.embedType =
|
||||
value as typeof this.plugin.settings.embedType;
|
||||
embedComment.settingEl.style.display =
|
||||
value === "excalidraw" ? "none" : "";
|
||||
if (value === "excalidraw") {
|
||||
hideElement(embedComment.settingEl);
|
||||
} else {
|
||||
showElement(embedComment.settingEl);
|
||||
}
|
||||
this.applySettingsUpdate();
|
||||
});
|
||||
});
|
||||
@@ -3412,8 +3461,11 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}),
|
||||
);
|
||||
|
||||
embedComment.settingEl.style.display =
|
||||
this.plugin.settings.embedType === "excalidraw" ? "none" : "";
|
||||
if (this.plugin.settings.embedType === "excalidraw") {
|
||||
hideElement(embedComment.settingEl);
|
||||
} else {
|
||||
showElement(embedComment.settingEl);
|
||||
}
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("EMBED_WIKILINK_NAME"))
|
||||
@@ -3516,7 +3568,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setName(t("EMBED_IMAGE_CACHE_CLEAR"))
|
||||
.addButton((button) =>
|
||||
button.setButtonText(t("EMBED_IMAGE_CACHE_CLEAR")).onClick(() => {
|
||||
void imageCache.clearImageCache();
|
||||
void getImageCache().clearImageCache();
|
||||
}),
|
||||
);
|
||||
new Setting(detailsEl)
|
||||
@@ -3529,7 +3581,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
);
|
||||
void confirmationPrompt.waitForClose.then((confirmed) => {
|
||||
if (confirmed) {
|
||||
void imageCache.clearBackupCache();
|
||||
void getImageCache().clearBackupCache();
|
||||
}
|
||||
});
|
||||
}),
|
||||
@@ -3590,7 +3642,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("EMBED_WIDTH_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: 400")
|
||||
.setPlaceholder("400")
|
||||
.setValue(this.plugin.settings.width)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.width = value;
|
||||
@@ -3604,7 +3656,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("EMBED_HEIGHT_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: 400")
|
||||
.setPlaceholder("400")
|
||||
.setValue(this.plugin.settings.height)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.height = value;
|
||||
@@ -3940,7 +3992,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("MD_DEFAULT_COLOR_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("CSS Color-name|RGB-HEX")
|
||||
.setPlaceholder(t("DEFAULT_COLOR_MD_DESC"))
|
||||
.setValue(this.plugin.settings.mdFontColor)
|
||||
.onChange((value) => {
|
||||
this.requestReloadDrawings = true;
|
||||
@@ -3954,7 +4006,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("MD_DEFAULT_BORDER_COLOR_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("CSS Color-name|RGB-HEX")
|
||||
.setPlaceholder(t("DEFAULT_COLOR_MD_DESC"))
|
||||
.setValue(this.plugin.settings.mdBorderColor)
|
||||
.onChange((value) => {
|
||||
this.requestReloadDrawings = true;
|
||||
@@ -3968,7 +4020,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("MD_CSS_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("filename of css file in vault")
|
||||
.setPlaceholder(t("MD_CSS_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.mdCSS)
|
||||
.onChange((value) => {
|
||||
this.requestReloadDrawings = true;
|
||||
@@ -4118,7 +4170,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setDesc(fragWithHTML(t("CJK_ASSETS_FOLDER_DESC")))
|
||||
.addText((text) =>
|
||||
text
|
||||
.setPlaceholder("e.g.: Excalidraw/FontAssets")
|
||||
.setPlaceholder(t("CJK_ASSETS_FOLDER_PLACEHOLDER"))
|
||||
.setValue(this.plugin.settings.fontAssetsPath)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.fontAssetsPath = value;
|
||||
@@ -4426,7 +4478,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}
|
||||
startupScriptButton.setButtonText(t("STARTUP_SCRIPT_BUTTON_OPEN"));
|
||||
await this.app.workspace.openLinkText(f.path, "", true);
|
||||
await this.hide();
|
||||
this.hide();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4610,9 +4662,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setName(variableName)
|
||||
.setDesc(fragWithHTML(description ?? ""))
|
||||
.addDropdown((dropdown) => {
|
||||
valueset.forEach((val: string) =>
|
||||
dropdown.addOption(val.toString(), val.toString()),
|
||||
);
|
||||
valueset.forEach((val: string) => {
|
||||
void dropdown.addOption(val.toString(), val.toString());
|
||||
});
|
||||
dropdown
|
||||
.setValue(getValue(scriptName, variableName) as string)
|
||||
.onChange(async (value) => {
|
||||
@@ -4625,14 +4677,13 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
.setName(variableName)
|
||||
.setDesc(fragWithHTML(description ?? ""))
|
||||
.addTextArea((text) => {
|
||||
text.inputEl.style.minHeight = textAreaHeight(
|
||||
scriptName,
|
||||
variableName,
|
||||
)
|
||||
? `${textAreaHeight(scriptName, variableName)}px`
|
||||
: "";
|
||||
text.inputEl.style.minWidth = "400px";
|
||||
text.inputEl.style.width = "100%";
|
||||
setStyle(text.inputEl, {
|
||||
minHeight: textAreaHeight(scriptName, variableName)
|
||||
? `${textAreaHeight(scriptName, variableName)}px`
|
||||
: "",
|
||||
minWidth: "400px",
|
||||
width: "100%",
|
||||
});
|
||||
text
|
||||
.setValue(getValue(scriptName, variableName) as string)
|
||||
.onChange(async (value) => {
|
||||
|
||||
+30
-6
@@ -21,10 +21,28 @@ import { errorHandler } from "src/utils/ErrorHandler";
|
||||
|
||||
declare const PLUGIN_LANGUAGES: Record<string, string>;
|
||||
declare const PLUGIN_VERSION: string;
|
||||
declare var LZString: any;
|
||||
|
||||
let locale: Partial<typeof en> | null = null;
|
||||
|
||||
type LocaleFactory = (
|
||||
device: typeof DEVICE,
|
||||
frontmatterKeys: typeof FRONTMATTER_KEYS,
|
||||
cjkFonts: typeof CJK_FONTS,
|
||||
tagAutoexport: typeof TAG_AUTOEXPORT,
|
||||
tagMdReadingMode: typeof TAG_MDREADINGMODE,
|
||||
tagPdfExport: typeof TAG_PDFEXPORT,
|
||||
safeUrls: typeof URLs,
|
||||
altLabel: typeof labelALT,
|
||||
ctrlLabel: typeof labelCTRL,
|
||||
metaLabel: typeof labelMETA,
|
||||
shiftLabel: typeof labelSHIFT,
|
||||
pluginVersion: string,
|
||||
) => Partial<typeof en>;
|
||||
|
||||
type LocaleRuntimeGlobals = {
|
||||
unpackBase64Deflate?: (value: string) => string;
|
||||
};
|
||||
|
||||
function loadLocale(lang: string): Partial<typeof en> {
|
||||
if (lang === "zh") {
|
||||
lang = "zh-cn";
|
||||
@@ -36,7 +54,12 @@ function loadLocale(lang: string): Partial<typeof en> {
|
||||
|
||||
try {
|
||||
const compressed = PLUGIN_LANGUAGES[lang];
|
||||
const decompressed = LZString.decompressFromBase64(compressed);
|
||||
const runtimeGlobals = window as Window & LocaleRuntimeGlobals;
|
||||
const unpack = runtimeGlobals.unpackBase64Deflate;
|
||||
if (typeof unpack !== "function") {
|
||||
return en;
|
||||
}
|
||||
const decompressed = unpack(compressed);
|
||||
|
||||
// Construct a factory function string.
|
||||
// This allows safeEval (which runs in the global scope) to access our imported variables
|
||||
@@ -54,15 +77,15 @@ function loadLocale(lang: string): Partial<typeof en> {
|
||||
})`;
|
||||
|
||||
// Evaluate the function declaration using your ErrorHandler
|
||||
const factory = errorHandler.safeEval<Function>(
|
||||
const factoryResult = errorHandler.safeEval<unknown>(
|
||||
factoryCode,
|
||||
"loadLocale - parsing language pack",
|
||||
window,
|
||||
);
|
||||
|
||||
if (typeof factory !== "function") {
|
||||
if (typeof factoryResult !== "function") {
|
||||
return en;
|
||||
}
|
||||
const factory = factoryResult as LocaleFactory;
|
||||
|
||||
// Execute the evaluated function, injecting the actual imported dependencies
|
||||
const x = factory(
|
||||
@@ -81,7 +104,8 @@ function loadLocale(lang: string): Partial<typeof en> {
|
||||
);
|
||||
|
||||
return x || en;
|
||||
} catch (_) {
|
||||
} catch (error) {
|
||||
console.error("Error loading locale", loadLocale, error);
|
||||
return en;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ export default {
|
||||
// Sugester
|
||||
SELECT_FILE_TO_INSERT: "Select a file to insert",
|
||||
// main.ts
|
||||
ERROR_INITIALIZING_EA: "Error initializing Excalidraw Automate",
|
||||
CONVERT_URL_TO_FILE: "Save image from URL to local file",
|
||||
UNZIP_CURRENT_FILE: "Decompress current Excalidraw file",
|
||||
PUBLISH_SVG_CHECK:
|
||||
@@ -65,6 +66,7 @@ export default {
|
||||
"Create new drawing - IN A POPOUT WINDOW - and embed into active document",
|
||||
TOGGLE_LOCK: "Toggle Text Element between edit RAW and PREVIEW",
|
||||
DELETE_FILE: "Delete selected image or Markdown file from Obsidian Vault",
|
||||
DELETE_IMAGE_NOTICE: "Please select an image or embedded markdown document",
|
||||
MARKER_FRAME_SHOW: "Marker Frames Visible",
|
||||
MARKER_FRAME_TITLE_SHOW: "Marker Frame Titles Visible",
|
||||
COPY_ELEMENT_LINK: "Copy [[link]] for selected element(s)",
|
||||
@@ -116,6 +118,8 @@ export default {
|
||||
ABOUT_EXCALIDRAW: "About Excalidraw",
|
||||
RUN_OCR:
|
||||
"OCR full drawing: Grab text from freedraw + images to clipboard and doc.props",
|
||||
TASKBONE_NOT_ENABLED:
|
||||
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
|
||||
RERUN_OCR:
|
||||
"OCR full drawing re-run: Grab text from freedraw + images to clipboard and doc.props",
|
||||
RUN_OCR_ELEMENTS:
|
||||
@@ -125,6 +129,8 @@ export default {
|
||||
CROP_PAGE: "Crop and mask selected page",
|
||||
CROP_IMAGE: "Crop and mask image",
|
||||
ANNOTATE_IMAGE: "Annotate image in Excalidraw",
|
||||
ANNOTATE_IMAGE_ERROR:
|
||||
"File not found. New Excalidraw drawing is taking too long to create. Please try again.",
|
||||
INSERT_ACTIVE_PDF_PAGE_AS_IMAGE: "Insert active PDF page as image",
|
||||
RESET_IMG_TO_100: "Set selected image element size to 100% of original",
|
||||
RESET_IMG_ASPECT_RATIO: "Reset selected image element aspect ratio",
|
||||
@@ -186,6 +192,7 @@ export default {
|
||||
INSTALL_SCRIPT_BUTTON: "Install or update Excalidraw Scripts",
|
||||
OPEN_AS_MD: "Open as Markdown",
|
||||
EXPORT_IMAGE: `Export Image`,
|
||||
SHOW_TAB_TITLEBAR_BUTTONS: "Show tab titlebar buttons",
|
||||
OPEN_LINK: "Open selected text as link\n(SHIFT+CLICK to open in a new pane)",
|
||||
EXCALIDRAW_SIDEPANEL: "Excalidraw Sidepanel",
|
||||
LINK_BUTTON_CLICK_NO_TEXT:
|
||||
@@ -251,6 +258,33 @@ export default {
|
||||
SEARCH_PREVIOUS: "Previous",
|
||||
|
||||
//settings.ts
|
||||
FOLDER_PLACEHOLDER: "e.g.: Excalidraw",
|
||||
CROP_FOLDER_PLACEHOLDER: "e.g.: Excalidraw/Cropped",
|
||||
ANNOTATE_FOLDER_PLACEHOLDER: "e.g.: Excalidraw/Annotations",
|
||||
TEMPLATE_PLACEHOLDER: "e.g.: Excalidraw/Template",
|
||||
SCRIPT_FOLDER_PLACEHOLDER: "e.g.: Excalidraw/Scripts",
|
||||
FILENAME_PREFIX_PLACEHOLDER: "e.g.: Drawing ",
|
||||
CROP_PREFIX_PLACEHOLDER: "e.g.: cropped_",
|
||||
CROP_SUFFIX_PLACEHOLDER: "e.g.: _cropped",
|
||||
ANNOTATE_PREFIX_PLACEHOLDER: "e.g.: annotated_",
|
||||
ANNOTATE_SUFFIX_PLACEHOLDER: "e.g.: _annotated",
|
||||
DYNAMICSTYLE_OPTION_NONE: "Dynamic Styling OFF",
|
||||
DYNAMICSTYLE_OPTION_COLORFUL: "Match color",
|
||||
DYNAMICSTYLE_OPTION_GRAY: "Gray, match tone",
|
||||
DEFAULT_OPEN_MODE_OPTION_NORMAL: "Always in normal-mode",
|
||||
DEFAULT_OPEN_MODE_OPTION_ZEN: "Always in zen-mode",
|
||||
DEFAULT_OPEN_MODE_OPTION_VIEW: "Always in view-mode",
|
||||
DEFAULT_OPEN_MODE_OPTION_VIEW_MOBILE:
|
||||
"Usually normal, but view-mode on Phone",
|
||||
DEFAULT_PEN_MODE_OPTION_NEVER: "Never",
|
||||
DEFAULT_PEN_MODE_OPTION_MOBILE: "On Obsidian Mobile",
|
||||
DEFAULT_PEN_MODE_OPTION_ALWAYS: "Always",
|
||||
EMBED_PREVIEW_IMAGETYPE_OPTION_PNG: "PNG Image",
|
||||
EMBED_PREVIEW_IMAGETYPE_OPTION_SVG: "Native SVG",
|
||||
EMBED_PREVIEW_IMAGETYPE_OPTION_SVGIMG: "SVG Image",
|
||||
DEFAULT_COLOR_MD_DESC: "CSS Color-name|RGB-HEX",
|
||||
MD_CSS_PLACEHOLDER: "Filename of CSS file in Vault",
|
||||
CJK_ASSETS_FOLDER_PLACEHOLDER: "e.g.: Excalidraw/FontAssets",
|
||||
DISABLE_CONTEXT_MENU_NAME: "Disable Excalidraw context menu",
|
||||
DISABLE_CONTEXT_MENU_DESC:
|
||||
"Disables the Excalidraw context menu. This can be useful on Mobile devices where the context menu pops up in unwanted moments.",
|
||||
@@ -258,6 +292,7 @@ export default {
|
||||
"Ask NotebookLM for help about the plugin. This model is pre-loaded with all my video transcripts, release notes and other helpful content. Chat with NotebookLM to explore my 250+ videos and the Excalidraw documentation.",
|
||||
NOTEBOOKLM_LINK_TEXT:
|
||||
"Learn the Plugin. Access the NotebookLM knowledgebase.",
|
||||
EXCALIDRAW_MASTERY: "Excalidraw Mastery",
|
||||
EXCALIDRAW_MASTERY_PROMO_ARIA: "Open Excalidraw Mastery",
|
||||
EXCALIDRAW_MASTERY_PROMO_HTML: `<p><b>Feeling lost in the toggles and menus?</b></p><p>Excalidraw is a Visual PKM powerhouse built for heavy-duty workflows like <b>Visual-First Daily Notes</b>, deep <b>PDF research</b>, <b>automation</b>, <b>AI integration</b>, and <b>Visual Zettelkasten</b>. But all this power comes with complexity.</p><p>Skip the trial and error. <a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}" target="_blank">👉 Join Excalidraw Mastery</a> to learn these exact setups step-by-step. Overcome tool friction and master your knowledge alongside a supportive community of visual thinkers!</p>`,
|
||||
EXCALIDRAW_MASTERY_PROMO_SHOW: "Show",
|
||||
@@ -1178,6 +1213,13 @@ export default {
|
||||
SCRIPT_EXECUTION_ERROR:
|
||||
"Script execution error. Please find error message on the developer console.",
|
||||
|
||||
//ScriptInstallPrompt.ts
|
||||
SCRIPT_INSTALL_PROMPT_FETCH_ERROR:
|
||||
"Error opening the Excalidraw Script Store page. " +
|
||||
"Please double check that you can access the website. " +
|
||||
"I've logged the link in developer console (press CTRL+SHIFT+i)",
|
||||
SCRIPT_INSTALL_PROMPT_OPEN_ERROR: "Could not open ScriptEngine repository",
|
||||
|
||||
//ExcalidrawViewUtils.ts
|
||||
MARKER_FRAME_RENDERING_DISABLED_NOTICE:
|
||||
"There are hidden marker-frames in the scene.",
|
||||
@@ -1248,6 +1290,11 @@ export default {
|
||||
ES_YOUTUBE_START_INVALID:
|
||||
"The YouTube Start Time is invalid. Please check the format and try again",
|
||||
ES_FILENAME_VISIBLE: "Filename Visible",
|
||||
ES_LOCKED_READING_MODE_HEAD: "Locked Reading Mode",
|
||||
ES_LOCKED_READING_MODE_DESC:
|
||||
"When enabled, interacting with the markdown embeddable will not switch it to edit mode. This is useful for checklists and habit trackers.",
|
||||
LOCK_READING_MODE: "Lock Reading Mode",
|
||||
UNLOCK_READING_MODE: "Unlock Reading Mode",
|
||||
ES_BACKGROUND_HEAD: "Embedded note background color",
|
||||
ES_BACKGROUND_DESC_INFO: "Click here for more info on colors",
|
||||
ES_BACKGROUND_DESC_DETAIL:
|
||||
@@ -1521,4 +1568,41 @@ Thank you & Enjoy!
|
||||
|
||||
//SuggestionModal.ts
|
||||
SUGGESTION_NOMATCH: "No matches found",
|
||||
|
||||
// Excalidraw Extras Gateway Components
|
||||
EXTRAS_GATEWAY_COMP_MATHJAX: "MathJax (LaTeX)",
|
||||
EXTRAS_GATEWAY_COMP_MERMAID: "Mermaid to Excalidraw",
|
||||
EXTRAS_GATEWAY_COMP_PDF: "PDF Export",
|
||||
EXTRAS_GATEWAY_COMP_FILESYSTEM: "Local File System Access",
|
||||
|
||||
// Gateway Modals & Texts
|
||||
EXTRAS_GATEWAY_TITLE: "Excalidraw Extras Required",
|
||||
EXTRAS_GATEWAY_DESC:
|
||||
"The '{component}' feature has been moved to the Excalidraw Extras companion plugin to keep Excalidraw lightweight, stay within Obsidian Sync Basic size restrictions, and give you explicit control over the additional libraries and elevated-permission functionality it requires.",
|
||||
EXTRAS_GATEWAY_INSTALL_BTN: "Install from Community Plugins",
|
||||
EXTRAS_GATEWAY_MANUAL_ENABLE_NOTICE:
|
||||
"I had implemented a smoother workflow that allowed Excalidraw Extras to be enabled and disabled automatically when needed. Unfortunately, I was forced to remove that feature after it was flagged by the Obsidian code scanner as a high-risk issue, accompanied by an automated explanation that I believe does not accurately reflect what the code does. Please enable Excalidraw Extras manually in Community Plugins. If you'd like to see a more convenient experience in the future, please consider contacting Obsidian and asking for plugin-developer-friendly support for safe automation workflows, including companion plugin management.",
|
||||
EXTRAS_GATEWAY_ENABLE_FEATURE_PERM_BTN: "Enable {component} Permanently",
|
||||
EXTRAS_GATEWAY_TEMP_ENABLE_TITLE: "Enable Temporarily",
|
||||
EXTRAS_GATEWAY_TEMP_ENABLE_DESC:
|
||||
"Turn on the feature temporarily. It will automatically turn off when the timer expires.",
|
||||
EXTRAS_GATEWAY_SESSION_ENABLE_DESC:
|
||||
"Enable this feature for the current Obsidian session only.",
|
||||
EXTRAS_GATEWAY_ENABLE_CURRENT_SESSION: "Enable for this session",
|
||||
EXTRAS_GATEWAY_FEATURE_TIMER_EXPIRED:
|
||||
"Excalidraw Extras: {component} timer expired. Feature disabled.",
|
||||
EXTRAS_GATEWAY_API_MISSING:
|
||||
"Excalidraw Extras is enabled, but the API failed to load. Please update the plugin.",
|
||||
EXTRAS_GATEWAY_FEATURE_TITLE: "Feature Disabled",
|
||||
EXTRAS_GATEWAY_FEATURE_DESC:
|
||||
"The '{component}' feature is currently disabled in your Excalidraw Extras settings.",
|
||||
EXTRAS_GATEWAY_IGNORE_SESSION: "Ignore for this session",
|
||||
EXTRAS_GATEWAY_UPDATE_EXACT:
|
||||
"Excalidraw Extras Update Required. {component} requires EXACTLY v{reqVersion} (Found v{currentVersion})",
|
||||
EXTRAS_GATEWAY_UPDATE_MIN:
|
||||
"Excalidraw Extras Update Required. {component} requires >= v{reqVersion} (Found v{currentVersion})",
|
||||
EXTRAS_GATEWAY_COMP_PLUGIN: "Excalidraw Extras Plugin",
|
||||
EXTRAS_GATEWAY_UPDATE_TITLE:
|
||||
"Excalidraw requires a new version of the Extras plugin",
|
||||
EXTRAS_GATEWAY_UPDATE_BTN: "Open Community Plugins",
|
||||
};
|
||||
@@ -3,7 +3,6 @@ import {
|
||||
FileId,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { BinaryFileData } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { Notice } from "obsidian";
|
||||
|
||||
import { getEA } from "src/core";
|
||||
@@ -84,12 +83,14 @@ export class CropImage {
|
||||
|
||||
private setBoundingEl(ea: ExcalidrawAutomate, bgColor: string) {
|
||||
const { topX, topY, width, height } = this.bbox;
|
||||
ea.style.backgroundColor = bgColor;
|
||||
ea.style.strokeColor = "transparent";
|
||||
ea.style.strokeWidth = 0;
|
||||
ea.style.strokeStyle = "solid";
|
||||
ea.style.fillStyle = "solid";
|
||||
ea.style.roughness = 0;
|
||||
ea.setStyle({
|
||||
backgroundColor: bgColor,
|
||||
strokeColor: "transparent",
|
||||
strokeWidth: 0,
|
||||
strokeStyle: "solid",
|
||||
fillStyle: "solid",
|
||||
roughness: 0,
|
||||
});
|
||||
ea.addRect(topX, topY, width, height);
|
||||
}
|
||||
|
||||
@@ -210,7 +211,7 @@ export class CropImage {
|
||||
const context = canvas.getContext("2d");
|
||||
|
||||
if (!context) {
|
||||
reject("Unable to get 2D context");
|
||||
reject(new Error("Unable to get 2D context"));
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
isGeminiImageModel,
|
||||
} from "src/utils/geminiImageModelUtils";
|
||||
import { isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
|
||||
import { showElement } from "src/utils/styleUtils";
|
||||
import { hideElement } from "src/utils/styleUtils";
|
||||
|
||||
type SaveHandler<TConfig extends AIModelConfig> = (
|
||||
modelId: string,
|
||||
@@ -180,8 +182,8 @@ export class AIModelConfigModal<
|
||||
.setName(t("AI_MODEL_CONFIG_MODAL_PROVIDER_NAME"))
|
||||
.setDesc(t("AI_MODEL_CONFIG_MODAL_PROVIDER_DESC"))
|
||||
.addDropdown((dropdown) => {
|
||||
this.options.providerIds.forEach((providerId) =>
|
||||
dropdown.addOption(providerId, providerId),
|
||||
this.options.providerIds.forEach(
|
||||
(providerId) => void dropdown.addOption(providerId, providerId),
|
||||
);
|
||||
return dropdown.setValue(this.config.providerId).onChange((value) => {
|
||||
this.config.providerId = value;
|
||||
@@ -276,9 +278,11 @@ export class AIModelConfigModal<
|
||||
});
|
||||
};
|
||||
updateImageSizeControls = () => {
|
||||
sizesSection.style.display = this.isCurrentGeminiImageModel()
|
||||
? "none"
|
||||
: "";
|
||||
if (this.isCurrentGeminiImageModel()) {
|
||||
hideElement(sizesSection);
|
||||
} else {
|
||||
showElement(sizesSection);
|
||||
}
|
||||
renderSizes();
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { getViewColorPalette } from "src/utils/excalidrawViewUtils";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
|
||||
type PaletteName = "canvasBackground" | "elementBackground" | "elementStroke";
|
||||
|
||||
@@ -51,8 +52,7 @@ const positionPopup = (popup: HTMLElement, anchor: HTMLElement) => {
|
||||
top = Math.max(8, rect.top - popupHeight - 8);
|
||||
}
|
||||
|
||||
popup.style.left = `${left}px`;
|
||||
popup.style.top = `${top}px`;
|
||||
setStyle(popup, { left: `${left}px`, top: `${top}px` });
|
||||
};
|
||||
|
||||
const attachOutsideHandlers = (
|
||||
@@ -107,16 +107,18 @@ export const showColorPicker = async (
|
||||
|
||||
const grid = activeDocument.createElement("div");
|
||||
grid.classList.add("excalidraw-colorpicker-grid");
|
||||
grid.style.gridTemplateColumns = `repeat(${GRID_COLUMNS}, ${CELL_SIZE}px)`;
|
||||
grid.style.gap = `${CELL_GAP}px`;
|
||||
grid.style.maxHeight = `${MAX_HEIGHT}px`;
|
||||
setStyle(grid, {
|
||||
gridTemplateColumns: `repeat(${GRID_COLUMNS}, ${CELL_SIZE}px)`,
|
||||
gap: `${CELL_GAP}px`,
|
||||
maxHeight: `${MAX_HEIGHT}px`,
|
||||
});
|
||||
|
||||
colors.forEach((color) => {
|
||||
const swatch = activeDocument.createElement("button");
|
||||
swatch.type = "button";
|
||||
swatch.ariaLabel = color;
|
||||
swatch.classList.add("excalidraw-colorpicker-swatch");
|
||||
swatch.style.backgroundColor = color;
|
||||
setStyle(swatch, { backgroundColor: color });
|
||||
swatch.addEventListener("click", () => cleanup(color));
|
||||
grid.appendChild(swatch);
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Setting, ToggleComponent } from "obsidian";
|
||||
import { EmbeddableMDCustomProps } from "./EmbeddableSettings";
|
||||
import { fragWithHTML } from "src/utils/utils";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { hideElement, showElement } from "src/utils/styleUtils";
|
||||
|
||||
export class EmbeddalbeMDFileCustomDataSettingsComponent {
|
||||
constructor(
|
||||
@@ -23,7 +24,11 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
|
||||
.setValue(this.mdCustomData.useObsidianDefaults)
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.useObsidianDefaults = value;
|
||||
detailsDIV.style.display = value ? "none" : "block";
|
||||
if (value) {
|
||||
hideElement(detailsDIV);
|
||||
} else {
|
||||
showElement(detailsDIV);
|
||||
}
|
||||
this.update();
|
||||
}),
|
||||
);
|
||||
@@ -31,9 +36,11 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
|
||||
this.contentEl.createEl("hr", { cls: "excalidraw-setting-hr" });
|
||||
|
||||
const detailsDIV = this.contentEl.createDiv();
|
||||
detailsDIV.style.display = this.mdCustomData.useObsidianDefaults
|
||||
? "none"
|
||||
: "block";
|
||||
if (this.mdCustomData.useObsidianDefaults) {
|
||||
hideElement(detailsDIV);
|
||||
} else {
|
||||
showElement(detailsDIV);
|
||||
}
|
||||
|
||||
const contentEl = detailsDIV;
|
||||
if (this.isMDFile) {
|
||||
@@ -46,7 +53,19 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
|
||||
this.mdCustomData.filenameVisible = value;
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(contentEl)
|
||||
.setName(t("ES_LOCKED_READING_MODE_HEAD"))
|
||||
.setDesc(t("ES_LOCKED_READING_MODE_DESC"))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(!!this.mdCustomData.lockedReadingMode)
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.lockedReadingMode = value;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
contentEl.createEl("h4", { text: t("ES_BACKGROUND_HEAD") });
|
||||
const descDiv = contentEl.createDiv({ cls: "excalidraw-setting-desc" });
|
||||
descDiv.textContent = t("ES_BACKGROUND_DESC_INFO");
|
||||
@@ -70,12 +89,12 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.backgroundMatchElement = value;
|
||||
if (value) {
|
||||
bgSetting.settingEl.style.display = "none";
|
||||
hideElement(bgSetting.settingEl);
|
||||
if (this.mdCustomData.backgroundMatchCanvas) {
|
||||
bgMatchCanvasToggle.setValue(false);
|
||||
}
|
||||
} else if (!this.mdCustomData.backgroundMatchCanvas) {
|
||||
bgSetting.settingEl.style.display = "";
|
||||
showElement(bgSetting.settingEl);
|
||||
}
|
||||
this.update();
|
||||
});
|
||||
@@ -90,12 +109,12 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.backgroundMatchCanvas = value;
|
||||
if (value) {
|
||||
bgSetting.settingEl.style.display = "none";
|
||||
hideElement(bgSetting.settingEl);
|
||||
if (this.mdCustomData.backgroundMatchElement) {
|
||||
bgMatchElementToggle.setValue(false);
|
||||
}
|
||||
} else if (!this.mdCustomData.backgroundMatchElement) {
|
||||
bgSetting.settingEl.style.display = "";
|
||||
showElement(bgSetting.settingEl);
|
||||
}
|
||||
this.update();
|
||||
});
|
||||
@@ -119,11 +138,14 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
|
||||
}),
|
||||
);
|
||||
|
||||
bgSetting.settingEl.style.display =
|
||||
if (
|
||||
this.mdCustomData.backgroundMatchElement ||
|
||||
this.mdCustomData.backgroundMatchCanvas
|
||||
? "none"
|
||||
: "";
|
||||
) {
|
||||
hideElement(bgSetting.settingEl);
|
||||
} else {
|
||||
showElement(bgSetting.settingEl);
|
||||
}
|
||||
const opacity = (value: number): DocumentFragment => {
|
||||
return fragWithHTML(`Current opacity is <b>${value}%</b>`);
|
||||
};
|
||||
@@ -153,9 +175,9 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
|
||||
.onChange((value) => {
|
||||
this.mdCustomData.borderMatchElement = value;
|
||||
if (value) {
|
||||
borderSetting.settingEl.style.display = "none";
|
||||
hideElement(borderSetting.settingEl);
|
||||
} else {
|
||||
borderSetting.settingEl.style.display = "";
|
||||
showElement(borderSetting.settingEl);
|
||||
}
|
||||
this.update();
|
||||
}),
|
||||
@@ -172,10 +194,11 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
|
||||
}),
|
||||
);
|
||||
|
||||
borderSetting.settingEl.style.display = this.mdCustomData
|
||||
.borderMatchElement
|
||||
? "none"
|
||||
: "";
|
||||
if (this.mdCustomData?.borderMatchElement) {
|
||||
hideElement(borderSetting.settingEl);
|
||||
} else {
|
||||
showElement(borderSetting.settingEl);
|
||||
}
|
||||
|
||||
const borderOpacitySetting = new Setting(contentEl)
|
||||
.setName(t("ES_BORDER_OPACITY"))
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
updateYouTubeStartTime,
|
||||
} from "src/utils/YoutTubeUtils";
|
||||
import { EmbeddalbeMDFileCustomDataSettingsComponent } from "./EmbeddableMDFileCustomDataSettingsComponent";
|
||||
import { isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
|
||||
import { isWinCTRLorMacCMD, labelCTRL } from "src/utils/modifierkeyHelper";
|
||||
import { CaptureUpdateAction } from "src/constants/constants";
|
||||
|
||||
export type EmbeddableMDCustomProps = {
|
||||
@@ -32,6 +32,7 @@ export type EmbeddableMDCustomProps = {
|
||||
borderColor: string;
|
||||
borderOpacity: number;
|
||||
filenameVisible: boolean;
|
||||
lockedReadingMode?: boolean;
|
||||
};
|
||||
|
||||
export class EmbeddableSettings extends Modal {
|
||||
@@ -66,9 +67,9 @@ export class EmbeddableSettings extends Modal {
|
||||
this.youtubeStart = getYouTubeStartAt(this.element.link);
|
||||
}
|
||||
|
||||
this.mdCustomData =
|
||||
element.customData?.mdProps ??
|
||||
view.plugin.settings.embeddableMarkdownDefaults;
|
||||
this.mdCustomData = (element.customData?.mdProps ??
|
||||
view.plugin.settings
|
||||
.embeddableMarkdownDefaults) as EmbeddableMDCustomProps;
|
||||
if (!element.customData?.mdProps) {
|
||||
const bgCM = this.plugin.ea.getCM(element.backgroundColor);
|
||||
this.mdCustomData.backgroundColor = bgCM.stringHEX({ alpha: false });
|
||||
@@ -164,14 +165,14 @@ export class EmbeddableSettings extends Modal {
|
||||
button
|
||||
.setButtonText(t("PROMPT_BUTTON_CANCEL"))
|
||||
.setTooltip("ESC")
|
||||
.onClick(this.close.bind(this)),
|
||||
.onClick(() => this.close()),
|
||||
)
|
||||
.addButton((button) =>
|
||||
button
|
||||
.setButtonText(t("PROMPT_BUTTON_OK"))
|
||||
.setTooltip("CTRL/Opt+Enter")
|
||||
.setTooltip(labelCTRL() + "Enter")
|
||||
.setCta()
|
||||
.onClick(this.applySettings.bind(this)),
|
||||
.onClick(() => this.applySettings()),
|
||||
);
|
||||
|
||||
const onKeyDown = (ev: KeyboardEvent) => {
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
} from "./PDFExportSettingsComponent";
|
||||
import { captureScreenshot } from "src/utils/screenshot";
|
||||
import { exportImageToFile, getIMGFilename } from "src/utils/fileUtils";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
|
||||
export class ExportDialog extends Modal {
|
||||
private ea: ExcalidrawAutomate;
|
||||
@@ -80,7 +81,7 @@ export class ExportDialog extends Modal {
|
||||
this.theme = getExportTheme(
|
||||
this.plugin,
|
||||
this.file,
|
||||
this.api.getAppState().theme,
|
||||
this.api.getAppState().theme as string,
|
||||
);
|
||||
this.boundingBox = this.ea.getBoundingBox(this.ea.getViewElements());
|
||||
this.embedScene = shouldEmbedScene(this.plugin, this.file);
|
||||
@@ -126,7 +127,7 @@ export class ExportDialog extends Modal {
|
||||
} else {
|
||||
this.boundingBox = this.ea.getBoundingBox(this.ea.getViewElements());
|
||||
}
|
||||
if (this.scaleSetting) {
|
||||
if (this.scaleSetting !== null) {
|
||||
this.scaleSetting.setDesc(this.size());
|
||||
}
|
||||
}
|
||||
@@ -139,7 +140,7 @@ export class ExportDialog extends Modal {
|
||||
this.updateBoundingBox();
|
||||
}
|
||||
|
||||
async onClose() {
|
||||
onClose() {
|
||||
this.dirty = this.saveSettings;
|
||||
}
|
||||
|
||||
@@ -196,7 +197,7 @@ export class ExportDialog extends Modal {
|
||||
this.buttonContainerRow2 = this.contentEl.createDiv({
|
||||
cls: "excalidraw-export-buttons-div",
|
||||
});
|
||||
this.buttonContainerRow2.style.marginTop = "10px";
|
||||
setStyle(this.buttonContainerRow2, { marginTop: "10px" });
|
||||
|
||||
this.renderContent();
|
||||
}
|
||||
@@ -426,16 +427,18 @@ export class ExportDialog extends Modal {
|
||||
bPNG.onclick = () => {
|
||||
if (isScreenshot) {
|
||||
//allow dialog to close before taking screenshot
|
||||
window.setTimeout(async () => {
|
||||
const png = await captureScreenshot(this.view, {
|
||||
zoom: this.scale,
|
||||
margin: this.padding,
|
||||
selectedOnly: this.isSelectedOnly,
|
||||
theme: this.theme,
|
||||
});
|
||||
if (png) {
|
||||
exportPNG(png, this.view.file.basename);
|
||||
}
|
||||
window.setTimeout(() => {
|
||||
void (async () => {
|
||||
const png = await captureScreenshot(this.view, {
|
||||
zoom: this.scale,
|
||||
margin: this.padding,
|
||||
selectedOnly: this.isSelectedOnly,
|
||||
theme: this.theme,
|
||||
});
|
||||
if (png) {
|
||||
exportPNG(png, this.view.file.basename);
|
||||
}
|
||||
})();
|
||||
});
|
||||
} else {
|
||||
void this.view.exportPNG(this.embedScene, this.isSelectedOnly);
|
||||
@@ -451,22 +454,24 @@ export class ExportDialog extends Modal {
|
||||
bPNGVault.onclick = () => {
|
||||
if (isScreenshot) {
|
||||
//allow dialog to close before taking screenshot
|
||||
window.setTimeout(async () => {
|
||||
const png = await captureScreenshot(this.view, {
|
||||
zoom: this.scale,
|
||||
margin: this.padding,
|
||||
selectedOnly: this.isSelectedOnly,
|
||||
theme: this.theme,
|
||||
});
|
||||
if (png) {
|
||||
void exportImageToFile(
|
||||
this.view,
|
||||
getIMGFilename(this.view.file.path, "png"),
|
||||
png,
|
||||
".png",
|
||||
);
|
||||
}
|
||||
});
|
||||
window.setTimeout(() => {
|
||||
void (async () => {
|
||||
const png = await captureScreenshot(this.view, {
|
||||
zoom: this.scale,
|
||||
margin: this.padding,
|
||||
selectedOnly: this.isSelectedOnly,
|
||||
theme: this.theme,
|
||||
});
|
||||
if (png) {
|
||||
void exportImageToFile(
|
||||
this.view,
|
||||
getIMGFilename(this.view.file.path, "png"),
|
||||
png,
|
||||
".png",
|
||||
);
|
||||
}
|
||||
})();
|
||||
}, 0);
|
||||
} else {
|
||||
void this.view.savePNG({
|
||||
scene: this.view.getScene(this.isSelectedOnly),
|
||||
@@ -482,16 +487,18 @@ export class ExportDialog extends Modal {
|
||||
bPNGClipboard.onclick = async () => {
|
||||
if (isScreenshot) {
|
||||
//allow dialog to close before taking screenshot
|
||||
window.setTimeout(async () => {
|
||||
const png = await captureScreenshot(this.view, {
|
||||
zoom: this.scale,
|
||||
margin: this.padding,
|
||||
selectedOnly: this.isSelectedOnly,
|
||||
theme: this.theme,
|
||||
});
|
||||
if (png) {
|
||||
await exportPNGToClipboard(png);
|
||||
}
|
||||
window.setTimeout(() => {
|
||||
void (async () => {
|
||||
const png = await captureScreenshot(this.view, {
|
||||
zoom: this.scale,
|
||||
margin: this.padding,
|
||||
selectedOnly: this.isSelectedOnly,
|
||||
theme: this.theme,
|
||||
});
|
||||
if (png) {
|
||||
await exportPNGToClipboard(png);
|
||||
}
|
||||
})();
|
||||
});
|
||||
} else {
|
||||
await this.view.exportPNGToClipboard(
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import { App, Modal } from "obsidian";
|
||||
import { clamp } from "@radix-ui/number";
|
||||
import { mainDocument } from "src/constants/constants";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
import {
|
||||
isInstanceOfHTMLButtonElement,
|
||||
isInstanceOfHTMLInputElement,
|
||||
isInstanceOfHTMLSelectElement,
|
||||
isInstanceOfHTMLTextAreaElement,
|
||||
} from "src/utils/typechecks";
|
||||
|
||||
function getClientPoint(e: PointerEvent | TouchEvent) {
|
||||
if (e.type.startsWith("touch")) {
|
||||
@@ -98,9 +105,9 @@ export class FloatingModal extends Modal {
|
||||
constructor(app: App) {
|
||||
super(app);
|
||||
// Initialize event handlers with proper binding
|
||||
this.pointerDownHandler = this.handlePointerDown.bind(this);
|
||||
this.pointerMoveHandler = this.handlePointerMove.bind(this);
|
||||
this.pointerUpHandler = this.handlePointerUp.bind(this);
|
||||
this.pointerDownHandler = (e) => this.handlePointerDown(e);
|
||||
this.pointerMoveHandler = (e) => this.handlePointerMove(e);
|
||||
this.pointerUpHandler = () => this.handlePointerUp();
|
||||
this.modalKeydownStopHandler = (ev: KeyboardEvent) => ev.stopPropagation();
|
||||
|
||||
this.setDimBackground(false);
|
||||
@@ -111,10 +118,10 @@ export class FloatingModal extends Modal {
|
||||
event: PointerEvent | TouchEvent,
|
||||
): boolean {
|
||||
return Boolean(
|
||||
target instanceof HTMLInputElement ||
|
||||
target instanceof HTMLTextAreaElement ||
|
||||
target instanceof HTMLSelectElement ||
|
||||
target instanceof HTMLButtonElement ||
|
||||
isInstanceOfHTMLInputElement(target) ||
|
||||
isInstanceOfHTMLTextAreaElement(target) ||
|
||||
isInstanceOfHTMLSelectElement(target) ||
|
||||
isInstanceOfHTMLButtonElement(target) ||
|
||||
isPointOnText(event, this.ownerDocument) ||
|
||||
target.closest(".clickable-icon") ||
|
||||
// ensure close button never starts drag
|
||||
@@ -145,7 +152,9 @@ export class FloatingModal extends Modal {
|
||||
const { modalEl } = this;
|
||||
this.offsetX = touch.clientX - modalEl.getBoundingClientRect().left;
|
||||
this.offsetY = touch.clientY - modalEl.getBoundingClientRect().top;
|
||||
modalEl.style.height = "fit-content";
|
||||
setStyle(modalEl, {
|
||||
height: "fit-content",
|
||||
});
|
||||
|
||||
// Add touch-specific event listeners
|
||||
this.ownerDocument.addEventListener(
|
||||
@@ -207,8 +216,10 @@ export class FloatingModal extends Modal {
|
||||
]);
|
||||
|
||||
// Position the modal element
|
||||
modalEl.style.left = `${x}px`;
|
||||
modalEl.style.top = `${y}px`;
|
||||
setStyle(modalEl, {
|
||||
left: `${x}px`,
|
||||
top: `${y}px`,
|
||||
});
|
||||
}
|
||||
|
||||
private handlePointerUp(): void {
|
||||
@@ -241,7 +252,9 @@ export class FloatingModal extends Modal {
|
||||
try {
|
||||
// Release modal scope so focus and key handling can return to the workspace.
|
||||
this.app.keymap.popScope(this.scope);
|
||||
} catch {}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
// prevent automatic selection / focus restoration
|
||||
this.shouldRestoreSelection = false;
|
||||
}
|
||||
@@ -251,18 +264,22 @@ export class FloatingModal extends Modal {
|
||||
|
||||
// Set initial position and make modal draggable
|
||||
if (modalEl) {
|
||||
modalEl.style.pointerEvents = "auto";
|
||||
// Position absolute is needed for custom positioning
|
||||
modalEl.style.position = "absolute";
|
||||
setStyle(modalEl, {
|
||||
pointerEvents: "auto",
|
||||
// Position absolute is needed for custom positioning
|
||||
position: "absolute",
|
||||
});
|
||||
|
||||
// Center the modal initially
|
||||
const rect = modalEl.getBoundingClientRect();
|
||||
const centerX = this.ownerWindow.innerWidth / 2 - rect.width / 2;
|
||||
const centerY = this.ownerWindow.innerHeight / 2 - rect.height / 2;
|
||||
|
||||
modalEl.style.left = `${centerX}px`;
|
||||
modalEl.style.top = `${centerY}px`;
|
||||
modalEl.style.transform = "none";
|
||||
setStyle(modalEl, {
|
||||
left: `${centerX}px`,
|
||||
top: `${centerY}px`,
|
||||
transform: "none",
|
||||
});
|
||||
|
||||
// Add event listeners for both pointer and touch events
|
||||
modalEl.addEventListener("pointerdown", this.pointerDownHandler);
|
||||
@@ -276,9 +293,13 @@ export class FloatingModal extends Modal {
|
||||
|
||||
// In order to propagate keypresses, modal container and backdrop
|
||||
// need to ignore (and thus propagate) any pointerEvents.
|
||||
containerEl.style.pointerEvents = "none";
|
||||
setStyle(containerEl, {
|
||||
pointerEvents: "none",
|
||||
});
|
||||
if (bgEl) {
|
||||
bgEl.style.pointerEvents = "none";
|
||||
setStyle(bgEl, {
|
||||
pointerEvents: "none",
|
||||
});
|
||||
}
|
||||
|
||||
// Refocus previous element (if still in DOM)
|
||||
@@ -294,7 +315,9 @@ export class FloatingModal extends Modal {
|
||||
// NEW: re-enable pointer events on the close button so it is tappable on mobile
|
||||
const closeBtn = containerEl.querySelector(".modal-close-button");
|
||||
if (closeBtn) {
|
||||
(closeBtn as HTMLElement).style.pointerEvents = "auto";
|
||||
setStyle(closeBtn as HTMLElement, {
|
||||
pointerEvents: "auto",
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -309,7 +332,9 @@ export class FloatingModal extends Modal {
|
||||
) {
|
||||
try {
|
||||
this.previousActive.focus({ preventScroll: true });
|
||||
} catch {}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
const { modalEl } = this;
|
||||
// Clean up event listeners
|
||||
|
||||
@@ -3,6 +3,7 @@ import { CaptureUpdateAction } from "src/constants/constants";
|
||||
import { FloatingModal } from "./FloatingModal";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { Setting } from "obsidian";
|
||||
import { setComponentVisibility } from "src/utils/styleUtils";
|
||||
|
||||
export const showFrameSettings = (view: ExcalidrawView) => {
|
||||
const { enabled, clip, name, outline, markerName, markerEnabled } =
|
||||
@@ -31,9 +32,9 @@ export const showFrameSettings = (view: ExcalidrawView) => {
|
||||
.addToggle((toggle) =>
|
||||
toggle.setValue(settings.enabled).onChange((value) => {
|
||||
settings.enabled = value;
|
||||
hideComponent(displayFrameNameSetting, !value);
|
||||
hideComponent(displayFrameOutlineSetting, !value);
|
||||
hideComponent(enableFrameClippingSetting, !value);
|
||||
setComponentVisibility(displayFrameNameSetting, value);
|
||||
setComponentVisibility(displayFrameOutlineSetting, value);
|
||||
setComponentVisibility(enableFrameClippingSetting, value);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -62,9 +63,9 @@ export const showFrameSettings = (view: ExcalidrawView) => {
|
||||
);
|
||||
|
||||
// Hide or show components based on initial state
|
||||
hideComponent(displayFrameNameSetting, !settings.enabled);
|
||||
hideComponent(displayFrameOutlineSetting, !settings.enabled);
|
||||
hideComponent(enableFrameClippingSetting, !settings.enabled);
|
||||
setComponentVisibility(displayFrameNameSetting, settings.enabled);
|
||||
setComponentVisibility(displayFrameOutlineSetting, settings.enabled);
|
||||
setComponentVisibility(enableFrameClippingSetting, settings.enabled);
|
||||
|
||||
// Add OK button
|
||||
new Setting(contentEl).addButton((button) =>
|
||||
@@ -83,8 +84,3 @@ export const showFrameSettings = (view: ExcalidrawView) => {
|
||||
|
||||
frameSettingsModal.open();
|
||||
};
|
||||
|
||||
// Function to hide or show a component
|
||||
function hideComponent(comp: Setting, value: boolean) {
|
||||
comp.settingEl.style.display = value ? "none" : "";
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { t } from "src/lang/helpers";
|
||||
import { ExcalidrawSettings } from "src/core/settings";
|
||||
import { modifierLabel } from "src/utils/modifierkeyHelper";
|
||||
import { fragWithHTML } from "src/utils/utils";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
|
||||
export class HotkeyEditor extends BaseComponent {
|
||||
private settings: ExcalidrawSettings;
|
||||
@@ -66,10 +67,14 @@ export class HotkeyEditor extends BaseComponent {
|
||||
|
||||
// Render Add New Override or Capture Instruction
|
||||
if (this.capturing) {
|
||||
new Setting(this.containerEl)
|
||||
.setName(t("HOTKEY_PRESS_COMBO_NANE"))
|
||||
.setDesc(t("HOTKEY_PRESS_COMBO_DESC")).controlEl.style.cursor =
|
||||
"pointer";
|
||||
setStyle(
|
||||
new Setting(this.containerEl)
|
||||
.setName(t("HOTKEY_PRESS_COMBO_NANE"))
|
||||
.setDesc(t("HOTKEY_PRESS_COMBO_DESC")).controlEl,
|
||||
{
|
||||
cursor: "pointer",
|
||||
},
|
||||
);
|
||||
} else {
|
||||
new Setting(this.containerEl).addButton((button) =>
|
||||
button
|
||||
|
||||
@@ -4,7 +4,6 @@ import ExcalidrawView from "../../view/ExcalidrawView";
|
||||
import { t } from "../../lang/helpers";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { getEA } from "src/core";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
|
||||
export class ImportSVGDialog extends FuzzySuggestModal<TFile> {
|
||||
public plugin: ExcalidrawPlugin;
|
||||
@@ -44,19 +43,21 @@ export class ImportSVGDialog extends FuzzySuggestModal<TFile> {
|
||||
return item.path;
|
||||
}
|
||||
|
||||
async onChooseItem(item: TFile, _: KeyboardEvent): Promise<void> {
|
||||
onChooseItem(item: TFile, _: KeyboardEvent): void {
|
||||
if (!item) {
|
||||
return;
|
||||
}
|
||||
const ea = getEA(this.view);
|
||||
const svg = await this.app.vault.read(item);
|
||||
if (!svg || svg === "") {
|
||||
return;
|
||||
}
|
||||
ea.importSVG(svg);
|
||||
ea.addToGroup(ea.getElements().map((el) => el.id));
|
||||
await ea.addElementsToView(true, true, true, true);
|
||||
ea.destroy();
|
||||
void (async () => {
|
||||
const ea = getEA(this.view);
|
||||
const svg = await this.app.vault.read(item);
|
||||
if (!svg || svg === "") {
|
||||
return;
|
||||
}
|
||||
ea.importSVG(svg);
|
||||
ea.addToGroup(ea.getElements().map((el) => el.id));
|
||||
await ea.addElementsToView(true, true, true, true);
|
||||
ea.destroy();
|
||||
})();
|
||||
}
|
||||
|
||||
onClose(): void {
|
||||
|
||||
@@ -10,11 +10,11 @@ import { getPDFDoc } from "src/utils/fileUtils";
|
||||
import { Modal, Setting, TextComponent } from "obsidian";
|
||||
import { FileSuggestionModal } from "../Suggesters/FileSuggestionModal";
|
||||
import { getEA } from "src/core";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { NamedExcalidrawFrameElement } from "src/types/excalidrawElementTypes";
|
||||
import type { PdfJsDocumentProxy } from "src/types/pdfJsTypes";
|
||||
import { setSanitizedHtml } from "src/utils/htmlUtils";
|
||||
import { hideElement, setStyle, showElement } from "src/utils/styleUtils";
|
||||
|
||||
export class InsertPDFModal extends Modal {
|
||||
private borderBox: boolean = true;
|
||||
@@ -26,10 +26,6 @@ export class InsertPDFModal extends Modal {
|
||||
private numRows: number = 1;
|
||||
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;
|
||||
@@ -58,7 +54,7 @@ export class InsertPDFModal extends Modal {
|
||||
void this.createForm();
|
||||
}
|
||||
|
||||
async onClose() {
|
||||
onClose() {
|
||||
if (this.dirty) {
|
||||
this.plugin.settings.pdfImportScale = this.importScale;
|
||||
this.plugin.settings.pdfBorderBox = this.borderBox;
|
||||
@@ -69,7 +65,7 @@ export class InsertPDFModal extends Modal {
|
||||
this.plugin.settings.pdfNumRows = this.numRows;
|
||||
this.plugin.settings.pdfDirection = this.direction;
|
||||
this.plugin.settings.pdfLockAfterImport = this.lockAfterImport;
|
||||
await this.plugin.saveSettings();
|
||||
void this.plugin.saveSettings();
|
||||
}
|
||||
if (this.pdfDoc) {
|
||||
this.pdfDoc.destroy();
|
||||
@@ -104,7 +100,6 @@ export class InsertPDFModal extends Modal {
|
||||
console.log(e);
|
||||
}
|
||||
}
|
||||
this.pageDimensions = this.getMaxSelectedPageDimensions();
|
||||
this.setImageSizeMessage();
|
||||
}
|
||||
|
||||
@@ -147,7 +142,9 @@ export class InsertPDFModal extends Modal {
|
||||
const pageRangeArray = pageRange.split("-");
|
||||
if (pageRangeArray.length === 1) {
|
||||
const page = parseInt(cleanNonDigits(pageRangeArray[0]));
|
||||
!isNaN(page) && this.pagesToImport.push(page);
|
||||
if (!isNaN(page)) {
|
||||
this.pagesToImport.push(page);
|
||||
}
|
||||
} else if (pageRangeArray.length === 2) {
|
||||
const start = parseInt(cleanNonDigits(pageRangeArray[0]));
|
||||
const end = parseInt(cleanNonDigits(pageRangeArray[1]));
|
||||
@@ -190,19 +187,19 @@ export class InsertPDFModal extends Modal {
|
||||
const importButtonMessages = () => {
|
||||
if (!this.pdfDoc) {
|
||||
importMessage.innerText = t("IPM_SELECT_PDF");
|
||||
importButton.buttonEl.style.display = "none";
|
||||
hideElement(importButton.buttonEl);
|
||||
return;
|
||||
}
|
||||
if (this.pagesToImport.length === 0) {
|
||||
importButton.buttonEl.style.display = "none";
|
||||
hideElement(importButton.buttonEl);
|
||||
importMessage.innerText = t("IPM_SELECT_PAGES_TO_IMPORT");
|
||||
return;
|
||||
}
|
||||
if (Math.max(...this.pagesToImport) <= this.pdfDoc.numPages) {
|
||||
importButton.buttonEl.style.display = "block";
|
||||
showElement(importButton.buttonEl);
|
||||
importMessage.innerText = "";
|
||||
} else {
|
||||
importButton.buttonEl.style.display = "none";
|
||||
hideElement(importButton.buttonEl);
|
||||
importMessage.innerText = `The selected document has ${this.pdfDoc.numPages} pages. Please select pages between 1 and ${this.pdfDoc.numPages}`;
|
||||
}
|
||||
};
|
||||
@@ -226,7 +223,6 @@ export class InsertPDFModal extends Modal {
|
||||
await this.loadPageDimensions(pages);
|
||||
} else {
|
||||
this.pageDimensionsByPage.clear();
|
||||
this.pageDimensions = { width: 0, height: 0 };
|
||||
this.setImageSizeMessage();
|
||||
}
|
||||
if (pages.length > 15) {
|
||||
@@ -245,11 +241,10 @@ export class InsertPDFModal extends Modal {
|
||||
|
||||
const setFile = async (file: TFile) => {
|
||||
if (this.pdfDoc) {
|
||||
await this.pdfDoc.destroy();
|
||||
this.pdfDoc.destroy();
|
||||
}
|
||||
this.pdfDoc = null;
|
||||
this.pageDimensionsByPage.clear();
|
||||
this.pageDimensions = { width: 0, height: 0 };
|
||||
numPages = 0;
|
||||
this.setImageSizeMessage();
|
||||
|
||||
@@ -272,7 +267,9 @@ export class InsertPDFModal extends Modal {
|
||||
};
|
||||
|
||||
const search = new TextComponent(ce);
|
||||
search.inputEl.style.width = "100%";
|
||||
setStyle(search.inputEl, {
|
||||
width: "100%",
|
||||
});
|
||||
const suggester = new FileSuggestionModal(
|
||||
this.app,
|
||||
search,
|
||||
@@ -296,7 +293,9 @@ export class InsertPDFModal extends Modal {
|
||||
text.setValue("").onChange(async (value) => {
|
||||
await rangeOnChange(value);
|
||||
});
|
||||
text.inputEl.style.width = "100%";
|
||||
setStyle(text.inputEl, {
|
||||
width: "100%",
|
||||
});
|
||||
});
|
||||
const importPagesMessage = ce.createEl("p", { text: "" });
|
||||
|
||||
@@ -362,12 +361,12 @@ export class InsertPDFModal extends Modal {
|
||||
const colRowVisibility = () => {
|
||||
switch (this.direction) {
|
||||
case "down":
|
||||
numColumnsSetting.settingEl.style.display = "none";
|
||||
numRowsSetting.settingEl.style.display = "";
|
||||
hideElement(numColumnsSetting.settingEl);
|
||||
showElement(numRowsSetting.settingEl);
|
||||
break;
|
||||
case "right":
|
||||
numColumnsSetting.settingEl.style.display = "";
|
||||
numRowsSetting.settingEl.style.display = "none";
|
||||
showElement(numColumnsSetting.settingEl);
|
||||
hideElement(numRowsSetting.settingEl);
|
||||
break;
|
||||
}
|
||||
};
|
||||
@@ -402,8 +401,7 @@ export class InsertPDFModal extends Modal {
|
||||
)
|
||||
.settingEl.createDiv("", (el) => {
|
||||
columnsText = el;
|
||||
el.style.minWidth = "2.3em";
|
||||
el.style.textAlign = "right";
|
||||
el.addClass("excalidraw-insertpdf-infolabel");
|
||||
el.innerText = ` ${this.numColumns.toString()}`;
|
||||
});
|
||||
|
||||
@@ -423,8 +421,7 @@ export class InsertPDFModal extends Modal {
|
||||
)
|
||||
.settingEl.createDiv("", (el) => {
|
||||
rowsText = el;
|
||||
el.style.minWidth = "2.3em";
|
||||
el.style.textAlign = "right";
|
||||
el.addClass("excalidraw-insertpdf-infolabel");
|
||||
el.innerText = ` ${this.numRows.toString()}`;
|
||||
});
|
||||
colRowVisibility();
|
||||
@@ -444,8 +441,7 @@ export class InsertPDFModal extends Modal {
|
||||
)
|
||||
.settingEl.createDiv("", (el) => {
|
||||
gapSizeText = el;
|
||||
el.style.minWidth = "2.3em";
|
||||
el.style.textAlign = "right";
|
||||
el.addClass("excalidraw-insertpdf-infolabel");
|
||||
el.innerText = ` ${this.gapSize.toString()}`;
|
||||
});
|
||||
|
||||
@@ -503,7 +499,9 @@ export class InsertPDFModal extends Modal {
|
||||
);
|
||||
const topY = Math.round(cellHeight * row + this.gapSize * row);
|
||||
|
||||
ea.style.strokeColor = this.borderBox ? "#000000" : "transparent";
|
||||
ea.setStyle({
|
||||
strokeColor: this.borderBox ? "#000000" : "transparent",
|
||||
});
|
||||
const boxID = ea.addRect(topX, topY, imgWidth, imgHeight);
|
||||
const boxEl = ea.getElement(boxID) as Mutable<ExcalidrawElement>;
|
||||
if (this.lockAfterImport) {
|
||||
@@ -579,7 +577,7 @@ export class InsertPDFModal extends Modal {
|
||||
this.close();
|
||||
});
|
||||
importButton = button;
|
||||
importButton.buttonEl.style.display = "none";
|
||||
hideElement(importButton.buttonEl);
|
||||
});
|
||||
const importMessage = actionButton.descEl;
|
||||
importMessage.addClass("mod-warning");
|
||||
|
||||
@@ -13,13 +13,94 @@ const getYouTubeDiv = (videoId: string) => `
|
||||
export const RELEASE_NOTES: { [k: string]: string } = {
|
||||
Intro: `After each update, you'll see these release notes (you can turn this off in the plugin settings).
|
||||
|
||||
I build this plugin as a labor of love. Curious about the philosophy behind it? Check out [📕 Sketch Your Mind](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_SYM}). Want to master Excalidraw? Join [Excalidraw Mastery](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}). If you find it valuable, say THANK YOU or…
|
||||
I build this plugin as a labor of love. Curious about the philosophy behind it? Check out [📕 Sketch Your Mind](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_SYM}). Want to master Excalidraw? Join [Excalidraw Mastery](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}). If you find it valuable, say "Thank you", and
|
||||
|
||||
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
|
||||
`,
|
||||
"2.23.9": `
|
||||
"2.24.2": `
|
||||
## Fixed
|
||||
- High impact regression in 2.24.0: Translations were not loading correctly. 🙏[@Lumintian](${URLs.GITHUB_COM}/Lumintian) [#2809](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2809)
|
||||
|
||||
## New
|
||||
- Added lock reading mode to markdown embeddables. If reading mode is locked, clicking the embeddable will not switch to the editor. This is useful for interacting with todo lists, links, and other interactive elements in the embeddables. Based on feedback from the Sketch Your Mind Community. 🙏[@robb3r](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM}/u/robb3r)
|
||||
`,
|
||||
"2.24.1": `
|
||||
To keep Excalidraw lightweight, improve startup performance, reduce plugin size, and address Obsidian's high-risk code scanner findings, several advanced features have been moved to the new **Excalidraw Extras** companion plugin in 2.24.0.
|
||||
|
||||
The first time you use one of these features, Excalidraw will automatically prompt you to install Excalidraw Extras:
|
||||
|
||||
- LaTeX formulas (MathJax)
|
||||
- Mermaid diagrams
|
||||
- PDF printing
|
||||
- Direct file system access (files outside your vault)
|
||||
|
||||
This change reduces Excalidraw's size to under 5 MB, allowing even Obsidian Sync Basic users to sync the plugin across all devices while keeping the core plugin lighter.
|
||||
|
||||
---
|
||||
|
||||
This (2.24.1) is an emergency follow-up release.
|
||||
|
||||
I had to remove a very helpful convenience feature from Excalidraw Extras management: automatic plugin enable/disable.
|
||||
|
||||
The feature was removed because of an unexpected Obsidian code scanner review that VERY negatively impacted Excalidraw's scanner score. The same code passed validation without any issues before the release, then failed when released, with no clear warning or guidance. I cannot continue shipping user-friendly automation when the validation target keeps changing.
|
||||
|
||||
I support security and quality checks. However, the current scanner process is difficult to work with due to inconsistent results, limited transparency, and the lack of a clear review or appeal process.
|
||||
|
||||
If Excalidraw matters to you, please consider contacting Obsidian and advocating for a more transparent, developer-friendly process:
|
||||
|
||||
* Stable and consistent scanner results before release
|
||||
* Clear, actionable error reporting
|
||||
* A real and timely review and appeal path for questionable findings
|
||||
* Support for safe plugin workflows, such as companion-plugin management and asset deployment
|
||||
|
||||
## Changed
|
||||
|
||||
* Removed automatic enable/disable of Excalidraw Extras from the onboarding flow.
|
||||
* Excalidraw Extras must now be enabled manually in Community Plugins after installation.
|
||||
|
||||
`,
|
||||
"2.24.0": `
|
||||
To keep Excalidraw lightweight, improve startup performance, reduce plugin size, and address Obsidian's high-risk code scanner findings, several advanced features have been moved to the new **Excalidraw Extras** companion plugin.
|
||||
|
||||
The first time you use one of these features, Excalidraw will automatically prompt you to install Excalidraw Extras:
|
||||
|
||||
- LaTeX formulas (MathJax)
|
||||
- Mermaid diagrams
|
||||
- PDF printing
|
||||
- Direct file system access (files outside your vault)
|
||||
|
||||
This change reduces Excalidraw's size to under 5 MB, allowing even Obsidian Sync Basic users to sync the plugin across all devices while keeping the core plugin lighter.
|
||||
|
||||
## Fixed
|
||||
- Keep runtime custom pen settings per custom pen index instead of sharing one active pen object. Switching between custom pens restores each pen's last adjusted stroke width, colors, fill style, and roughness. 🙏[@arias007](${URLs.GITHUB_COM}/arias007) [#2801](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2801)
|
||||
- Insert ANY file: Typing “p” in the search field opens the PDF selection [#2791](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2791)
|
||||
- Blurry arrows in PNG export when arrows have a text label [#2793](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2793), [#11492](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11492)
|
||||
`,
|
||||
"2.23.12": `
|
||||
## Fixed
|
||||
- Code scanner error
|
||||
`,
|
||||
"2.23.11": `
|
||||
## Fixed
|
||||
- Print to PDF sometimes displayed a scrollbar on prinouts on MacOS.
|
||||
- Scenes that contain \`![[text#^block]] transclusions\` did not render in markdown nor in image previews.
|
||||
- Addressed further Obsidian code scanner findings
|
||||
`,
|
||||
"2.23.10": `
|
||||
## Fixed
|
||||
- 2.23.9 regression: Toolbar sizing issue in desktop and compact UI modes [#2789](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2789)
|
||||
`,
|
||||
"2.23.9": `
|
||||
## New
|
||||
- Excalidraw now updates nested image embeds in the scene triggered by Obsidian window/tab changes even if those changes affect deep nested images (i.e. excalidraw images nested inside the nested drawings)
|
||||
- Added the Color Scheme Manager script. 🙏[@iwanhoogendoorn](${URLs.GITHUB_COM}/iwanhoogendoorn)
|
||||
- Iwan will demonstrate the script and host a Q&A session for [Sketch Your Mind Community Members](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_SYM}) on Friday, 12 June.
|
||||
|
||||
## Fixed
|
||||
- Clicking Excalidraw links now correctly jumps to the targeted element, group, or frame when the destination is another Excalidraw drawing, including links chosen through the multi-link picker and links triggered from nested embeds.
|
||||
- In some cases the image cache did not update when nested drawings were modified
|
||||
- Horizontal and Vertical arrow lines are not always displayed correctly when exporting to SVG or embedding SVG to a markdown note [#1454](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/1454)
|
||||
- Updated vulnerable package dependency lodash-es and nanoid based on Obsidian code scanner findings.
|
||||
`,
|
||||
"2.23.8": `
|
||||
${getYouTubeDiv("y3sDfH30ApU")}
|
||||
@@ -285,7 +366,7 @@ ${getYouTubeDiv("TnwRlaIdhSU")}
|
||||
`,
|
||||
"2.22.0": `
|
||||
## Fixed
|
||||
- Fixed misaligned panel buttons in tray mode [#2718](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2718) 🙏[@heinrich26](${URLs.GITHUB_COM_HEINRICH26})
|
||||
- Fixed misaligned panel buttons in tray mode [#2718](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2718) 🙏[@heinrich26](${URLs.GITHUB_COM}/heinrich26)
|
||||
- Improved loading of nested Excalidraw files within a scene, with some additional performance gains.
|
||||
- Fixed an issue where the caret color did not match the text color [#11018](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES}/11018)
|
||||
|
||||
@@ -325,11 +406,11 @@ ${getYouTubeDiv("TnwRlaIdhSU")}
|
||||
`,
|
||||
"2.21.0": `
|
||||
## New
|
||||
- LaTeX editor is now floating [#2684](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2684) 🙏[@TravisLEBLANC1](${URLs.GITHUB_COM_TRAVISLEBLANC1}), [#2698](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2698) 🙏[@heinrich26](${URLs.GITHUB_COM_HEINRICH26})
|
||||
- LaTeX editor is now floating [#2684](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2684) 🙏[@TravisLEBLANC1](${URLs.GITHUB_COM_TRAVISLEBLANC1}), [#2698](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2698) 🙏[@heinrich26](${URLs.GITHUB_COM}/heinrich26)
|
||||
- Inline link suggester supports new triggers \`
|
||||
- New Context Menu options to disable arrow binding and midpoint snapping [#10906](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/10906)
|
||||
- Improved UI styling and icons are better aligned with Obsidian [#2703](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2703), [#2687](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2687), [#2697](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2697) 🙏[@heinrich26](${URLs.GITHUB_COM_HEINRICH26})
|
||||
- Improved UI styling and icons are better aligned with Obsidian [#2703](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2703), [#2687](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2687), [#2697](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2697) 🙏[@heinrich26](${URLs.GITHUB_COM}/heinrich26)
|
||||
|
||||
## Fixed
|
||||
- Sizing of embedded images in Markdown when image type is set to SVG [#2685](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2685)
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
ModifierSetType,
|
||||
modifierKeyTooltipMessages,
|
||||
} from "src/utils/modifierkeyHelper";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
|
||||
type ModifierKeyCategories = Partial<{
|
||||
[modifierSetType in ModifierSetType]: string;
|
||||
@@ -113,7 +114,7 @@ export class ModifierKeySettingsComponent {
|
||||
// the click via CMD being held). On macOS, CMD is also reserved for
|
||||
// non-link-click actions.
|
||||
toggle.setDisabled(true);
|
||||
toggle.toggleEl.style.opacity = "0.5";
|
||||
setStyle(toggle.toggleEl, { opacity: "0.5" });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
STANDARD_PAGE_SIZES,
|
||||
} from "src/types/exportUtilTypes";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { hideElement, showElement } from "src/utils/styleUtils";
|
||||
|
||||
export interface PDFExportSettings {
|
||||
pageSize: PageSize;
|
||||
@@ -55,15 +56,21 @@ export class PDFExportSettingsComponent {
|
||||
.setValue(this.settings.pageSize)
|
||||
.onChange((value) => {
|
||||
this.settings.pageSize = value as PageSize;
|
||||
div.style.display = this.isOrientationAndTilingVisible()
|
||||
? "block"
|
||||
: "none";
|
||||
if (this.isOrientationAndTilingVisible()) {
|
||||
showElement(div);
|
||||
} else {
|
||||
hideElement(div);
|
||||
}
|
||||
this.update();
|
||||
}),
|
||||
);
|
||||
|
||||
const div = this.contentEl.createDiv();
|
||||
div.style.display = this.isOrientationAndTilingVisible() ? "block" : "none";
|
||||
if (this.isOrientationAndTilingVisible()) {
|
||||
showElement(div);
|
||||
} else {
|
||||
hideElement(div);
|
||||
}
|
||||
|
||||
new Setting(div)
|
||||
.setName(t("EXPORTDIALOG_PAGE_ORIENTATION"))
|
||||
@@ -140,7 +147,11 @@ export class PDFExportSettingsComponent {
|
||||
.setValue(this.settings.paperColor)
|
||||
.onChange((value) => {
|
||||
this.settings.paperColor = value as typeof this.settings.paperColor;
|
||||
colorInput.style.display = value === "custom" ? "block" : "none";
|
||||
if (value === "custom") {
|
||||
showElement(colorInput);
|
||||
} else {
|
||||
hideElement(colorInput);
|
||||
}
|
||||
this.update();
|
||||
}),
|
||||
);
|
||||
@@ -149,10 +160,12 @@ export class PDFExportSettingsComponent {
|
||||
type: "color",
|
||||
value: this.settings.customPaperColor,
|
||||
});
|
||||
colorInput.style.width = "50px";
|
||||
colorInput.style.marginLeft = "10px";
|
||||
colorInput.style.display =
|
||||
this.settings.paperColor === "custom" ? "block" : "none";
|
||||
colorInput.addClass("excalidraw-pdfexportsettings-colorinput");
|
||||
if (this.settings.paperColor === "custom") {
|
||||
showElement(colorInput);
|
||||
} else {
|
||||
hideElement(colorInput);
|
||||
}
|
||||
colorInput.addEventListener("change", (e) => {
|
||||
this.settings.customPaperColor = (e.target as HTMLInputElement).value;
|
||||
this.update();
|
||||
|
||||
@@ -17,6 +17,7 @@ import { fragWithHTML } from "src/utils/utils";
|
||||
import { setSanitizedHtml } from "src/utils/htmlUtils";
|
||||
import { showColorPicker } from "./ColorPicker";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { hideElement, showElement } from "src/utils/styleUtils";
|
||||
|
||||
const EASINGFUNCTIONS: Record<string, string> = {
|
||||
linear: "linear",
|
||||
@@ -71,9 +72,9 @@ export class PenSettingsModal extends Modal {
|
||||
void this.createForm();
|
||||
}
|
||||
|
||||
async onClose() {
|
||||
onClose() {
|
||||
if (this.dirty) {
|
||||
await this.plugin.saveSettings();
|
||||
void this.plugin.saveSettings();
|
||||
getExcalidrawViews(this.app, true).forEach((excalidrawView) =>
|
||||
excalidrawView.updatePinnedCustomPens(),
|
||||
);
|
||||
@@ -90,10 +91,10 @@ export class PenSettingsModal extends Modal {
|
||||
if (COLOR_NAMES.has(color)) {
|
||||
return [COLOR_NAMES.get(color), opacity];
|
||||
}
|
||||
const style = new Option().style;
|
||||
style.color = color;
|
||||
if (style.color) {
|
||||
const digits = style.color.match(
|
||||
const optionStyle = new Option().style;
|
||||
optionStyle.color = color;
|
||||
if (optionStyle.color) {
|
||||
const digits = optionStyle.color.match(
|
||||
/^[^\d]*(\d*)[^\d]*(\d*)[^\d]*(\d*)[^\d]*([\d.]*)?/,
|
||||
);
|
||||
if (!digits) {
|
||||
@@ -205,7 +206,11 @@ export class PenSettingsModal extends Modal {
|
||||
strokeUseCurrentToggle = toggle;
|
||||
toggle.setValue(!ps.strokeColor).onChange((value) => {
|
||||
this.dirty = true;
|
||||
scSetting.settingEl.style.display = value ? "none" : "";
|
||||
if (value) {
|
||||
hideElement(scSetting.settingEl);
|
||||
} else {
|
||||
showElement(scSetting.settingEl);
|
||||
}
|
||||
strokeSetting.setName(
|
||||
fragWithHTML(
|
||||
value
|
||||
@@ -288,7 +293,11 @@ export class PenSettingsModal extends Modal {
|
||||
});
|
||||
});
|
||||
|
||||
scSetting.settingEl.style.display = !ps.strokeColor ? "none" : "";
|
||||
if (ps.strokeColor) {
|
||||
showElement(scSetting.settingEl);
|
||||
} else {
|
||||
hideElement(scSetting.settingEl);
|
||||
}
|
||||
|
||||
let bgcpComponent: ColorComponent;
|
||||
let bgctComponent: TextComponent;
|
||||
@@ -320,9 +329,18 @@ export class PenSettingsModal extends Modal {
|
||||
: "Background color: <b>Preset color</b>",
|
||||
),
|
||||
);
|
||||
bgctSetting.settingEl.style.display = value ? "none" : "";
|
||||
bgcSetting.settingEl.style.display =
|
||||
value || ps.backgroundColor === "transparent" ? "none" : "";
|
||||
|
||||
if (value) {
|
||||
hideElement(bgctSetting.settingEl);
|
||||
} else {
|
||||
showElement(bgctSetting.settingEl);
|
||||
}
|
||||
|
||||
if (value || ps.backgroundColor === "transparent") {
|
||||
hideElement(bgcSetting.settingEl);
|
||||
} else {
|
||||
showElement(bgcSetting.settingEl);
|
||||
}
|
||||
if (value) {
|
||||
delete ps.backgroundColor;
|
||||
} else {
|
||||
@@ -351,8 +369,13 @@ export class PenSettingsModal extends Modal {
|
||||
.setValue(ps.backgroundColor === "transparent")
|
||||
.onChange((value) => {
|
||||
this.dirty = true;
|
||||
bgcSetting.settingEl.style.display = value ? "none" : "";
|
||||
fsSetting.settingEl.style.display = value ? "none" : "";
|
||||
if (value) {
|
||||
hideElement(bgcSetting.settingEl);
|
||||
hideElement(fsSetting.settingEl);
|
||||
} else {
|
||||
showElement(bgcSetting.settingEl);
|
||||
showElement(fsSetting.settingEl);
|
||||
}
|
||||
bgctSetting.setName(
|
||||
fragWithHTML(
|
||||
value
|
||||
@@ -366,7 +389,11 @@ export class PenSettingsModal extends Modal {
|
||||
});
|
||||
});
|
||||
|
||||
bgctSetting.settingEl.style.display = !ps.backgroundColor ? "none" : "";
|
||||
if (ps.backgroundColor) {
|
||||
showElement(bgctSetting.settingEl);
|
||||
} else {
|
||||
hideElement(bgctSetting.settingEl);
|
||||
}
|
||||
let bgChangeBounce: boolean = false;
|
||||
const bgcSetting = new Setting(ce)
|
||||
.setName("Background color")
|
||||
@@ -431,8 +458,11 @@ export class PenSettingsModal extends Modal {
|
||||
});
|
||||
});
|
||||
|
||||
bgcSetting.settingEl.style.display =
|
||||
!ps.backgroundColor || ps.backgroundColor === "transparent" ? "none" : "";
|
||||
if (!ps.backgroundColor || ps.backgroundColor === "transparent") {
|
||||
hideElement(bgcSetting.settingEl);
|
||||
} else {
|
||||
showElement(bgcSetting.settingEl);
|
||||
}
|
||||
|
||||
const fsSetting = new Setting(ce)
|
||||
.setName("Fill Style")
|
||||
@@ -452,8 +482,11 @@ export class PenSettingsModal extends Modal {
|
||||
ps.fillStyle = value;
|
||||
}),
|
||||
);
|
||||
fsSetting.settingEl.style.display =
|
||||
!ps.backgroundColor || ps.backgroundColor === "transparent" ? "none" : "";
|
||||
if (!ps.backgroundColor || ps.backgroundColor === "transparent") {
|
||||
hideElement(fsSetting.settingEl);
|
||||
} else {
|
||||
showElement(fsSetting.settingEl);
|
||||
}
|
||||
|
||||
const rSetting = new Setting(ce)
|
||||
.setName(
|
||||
@@ -516,9 +549,11 @@ export class PenSettingsModal extends Modal {
|
||||
toggle.setValue(!ps.penOptions.constantPressure).onChange((value) => {
|
||||
this.dirty = true;
|
||||
ps.penOptions.constantPressure = !value;
|
||||
spSetting.settingEl.style.display = ps.penOptions.constantPressure
|
||||
? "none"
|
||||
: "";
|
||||
if (ps.penOptions.constantPressure) {
|
||||
hideElement(spSetting.settingEl);
|
||||
} else {
|
||||
showElement(spSetting.settingEl);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -582,7 +617,7 @@ export class PenSettingsModal extends Modal {
|
||||
.setLimits(-1, 1, 0.05)
|
||||
.setValue(ps.penOptions.options.thinning)
|
||||
.onChange((value) => {
|
||||
this.dirty;
|
||||
this.dirty = true;
|
||||
tSetting.setName(fragWithHTML(`Thinnning <b>${value}</b>`));
|
||||
ps.penOptions.options.thinning = value;
|
||||
}),
|
||||
@@ -598,7 +633,7 @@ export class PenSettingsModal extends Modal {
|
||||
.setLimits(0, 1, 0.05)
|
||||
.setValue(ps.penOptions.options.smoothing)
|
||||
.onChange((value) => {
|
||||
this.dirty;
|
||||
this.dirty = true;
|
||||
sSetting.setName(fragWithHTML(`Smoothing <b>${value}</b>`));
|
||||
ps.penOptions.options.smoothing = value;
|
||||
}),
|
||||
@@ -614,7 +649,7 @@ export class PenSettingsModal extends Modal {
|
||||
.setLimits(0, 1, 0.05)
|
||||
.setValue(ps.penOptions.options.streamline)
|
||||
.onChange((value) => {
|
||||
this.dirty;
|
||||
this.dirty = true;
|
||||
slSetting.setName(fragWithHTML(`Streamline <b>${value}</b>`));
|
||||
ps.penOptions.options.streamline = value;
|
||||
}),
|
||||
@@ -666,9 +701,12 @@ export class PenSettingsModal extends Modal {
|
||||
}
|
||||
}),
|
||||
);
|
||||
spSetting.settingEl.style.display = ps.penOptions.constantPressure
|
||||
? "none"
|
||||
: "";
|
||||
|
||||
if (ps.penOptions.constantPressure) {
|
||||
hideElement(spSetting.settingEl);
|
||||
} else {
|
||||
showElement(spSetting.settingEl);
|
||||
}
|
||||
|
||||
ce.createEl("h3", { text: "Start" });
|
||||
ce.createEl("p", { text: "Tapering options for the start of the line." });
|
||||
@@ -701,7 +739,7 @@ export class PenSettingsModal extends Modal {
|
||||
: ps.penOptions.options.start.taper,
|
||||
)
|
||||
.onChange((value) => {
|
||||
this.dirty;
|
||||
this.dirty = true;
|
||||
ps.penOptions.options.start.taper = value === 151 ? true : value;
|
||||
stSetting.setName(
|
||||
fragWithHTML(
|
||||
@@ -759,7 +797,7 @@ export class PenSettingsModal extends Modal {
|
||||
: ps.penOptions.options.end.taper,
|
||||
)
|
||||
.onChange((value) => {
|
||||
this.dirty;
|
||||
this.dirty = true;
|
||||
ps.penOptions.options.end.taper = value === 151 ? true : value;
|
||||
etSetting.setName(
|
||||
fragWithHTML(
|
||||
|
||||
+116
-85
@@ -11,7 +11,7 @@ import {
|
||||
} from "obsidian";
|
||||
import ExcalidrawView from "../../view/ExcalidrawView";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { escapeRegExp, sleep } from "../../utils/utils";
|
||||
import { escapeRegExp } from "../../utils/utils";
|
||||
import { getLeaf, openLeaf } from "../../utils/obsidianUtils";
|
||||
import { createOrOverwriteFile } from "src/utils/fileUtils";
|
||||
import { KeyEvent, isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
|
||||
@@ -38,6 +38,7 @@ import { editorLivePreviewField } from "obsidian";
|
||||
import { Extension } from "@codemirror/state";
|
||||
import { FloatingModal } from "./FloatingModal";
|
||||
import { setSanitizedHtml } from "src/utils/htmlUtils";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
|
||||
/**
|
||||
* Minimal type for obsidian-latex-suite plugin.
|
||||
@@ -75,7 +76,9 @@ export class Prompt extends Modal {
|
||||
div.addClass("excalidraw-prompt-div");
|
||||
if (this.prompt_desc) {
|
||||
div = div.createDiv();
|
||||
div.style.width = "100%";
|
||||
setStyle(div, {
|
||||
width: "100%",
|
||||
});
|
||||
const p = div.createEl("p");
|
||||
setSanitizedHtml(p, this.prompt_desc);
|
||||
}
|
||||
@@ -104,7 +107,6 @@ export class Prompt extends Modal {
|
||||
|
||||
export class LaTexPrompt extends FloatingModal {
|
||||
public waitForClose: Promise<string>;
|
||||
private promptEl: HTMLInputElement;
|
||||
private resolvePromise: (input: string) => void;
|
||||
private rejectPromise: (reason?: string) => void;
|
||||
private editorView: EditorView;
|
||||
@@ -141,11 +143,20 @@ export class LaTexPrompt extends FloatingModal {
|
||||
);
|
||||
}
|
||||
|
||||
public static Prompt(
|
||||
public static async Prompt(
|
||||
plugin: ExcalidrawPlugin,
|
||||
app: App,
|
||||
prompt_text?: string,
|
||||
default_value?: string,
|
||||
): Promise<string> {
|
||||
const mathjaxAPI = await plugin.extrasGateway.getMathJax();
|
||||
|
||||
if (!mathjaxAPI) {
|
||||
return Promise.reject(
|
||||
new Error("MathJax is not available or activation was cancelled"),
|
||||
);
|
||||
}
|
||||
|
||||
const latexprompt = new this(app, prompt_text, default_value);
|
||||
|
||||
return latexprompt.waitForClose;
|
||||
@@ -203,18 +214,21 @@ export class LaTexPrompt extends FloatingModal {
|
||||
const actionButtonContainer: HTMLDivElement =
|
||||
buttonBarContainer.createDiv();
|
||||
|
||||
setStyle(
|
||||
this.createButton(
|
||||
actionButtonContainer,
|
||||
"",
|
||||
() => this.submitCallback(),
|
||||
t("PROMPT_BUTTON_OK") ?? "",
|
||||
undefined,
|
||||
"check",
|
||||
).setCta().buttonEl,
|
||||
{ marginRight: "0" },
|
||||
);
|
||||
this.createButton(
|
||||
actionButtonContainer,
|
||||
"",
|
||||
this.submitCallback.bind(this),
|
||||
t("PROMPT_BUTTON_OK") ?? "",
|
||||
undefined,
|
||||
"check",
|
||||
).setCta().buttonEl.style.marginRight = "0";
|
||||
this.createButton(
|
||||
actionButtonContainer,
|
||||
"",
|
||||
this.cancelCallback.bind(this),
|
||||
() => this.cancelCallback(),
|
||||
t("PROMPT_BUTTON_CANCEL"),
|
||||
undefined,
|
||||
"x",
|
||||
@@ -231,8 +245,10 @@ export class LaTexPrompt extends FloatingModal {
|
||||
iconId?: string,
|
||||
) {
|
||||
const btn = new ButtonComponent(container);
|
||||
btn.buttonEl.style.padding = "0.5em";
|
||||
btn.buttonEl.style.marginLeft = margin;
|
||||
setStyle(btn.buttonEl, {
|
||||
padding: "0.5em",
|
||||
marginLeft: margin,
|
||||
});
|
||||
btn.setTooltip(tooltip);
|
||||
|
||||
if (iconId) {
|
||||
@@ -260,8 +276,8 @@ export class LaTexPrompt extends FloatingModal {
|
||||
this.close();
|
||||
}
|
||||
|
||||
async onOpen(): Promise<void> {
|
||||
await super.onOpen();
|
||||
onOpen(): void {
|
||||
super.onOpen();
|
||||
this.editorView.focus();
|
||||
}
|
||||
|
||||
@@ -396,9 +412,9 @@ export class GenericInputPrompt extends Modal {
|
||||
this.contentEl.empty();
|
||||
if (this.blockPointerInputOutsideModal) {
|
||||
const bgEl = this.bgEl;
|
||||
bgEl.style.pointerEvents = this.blockPointerInputOutsideModal
|
||||
? "none"
|
||||
: "auto";
|
||||
setStyle(bgEl, {
|
||||
pointerEvents: this.blockPointerInputOutsideModal ? "none" : "auto",
|
||||
});
|
||||
}
|
||||
|
||||
this.titleEl.textContent = this.header;
|
||||
@@ -436,11 +452,15 @@ export class GenericInputPrompt extends Modal {
|
||||
) {
|
||||
const textComponent = new TextAreaComponent(container);
|
||||
|
||||
textComponent.inputEl.style.width = "100%";
|
||||
textComponent.inputEl.style.height = `${this.lines * 2}em`;
|
||||
setStyle(textComponent.inputEl, {
|
||||
width: "100%",
|
||||
height: `${this.lines * 2}em`,
|
||||
});
|
||||
if (this.lines === 1) {
|
||||
textComponent.inputEl.style.resize = "none";
|
||||
textComponent.inputEl.style.overflow = "hidden";
|
||||
setStyle(textComponent.inputEl, {
|
||||
resize: "none",
|
||||
overflow: "hidden",
|
||||
});
|
||||
}
|
||||
textComponent
|
||||
.setPlaceholder(placeholder ?? "")
|
||||
@@ -472,8 +492,10 @@ export class GenericInputPrompt extends Modal {
|
||||
iconId?: string,
|
||||
) {
|
||||
const btn = new ButtonComponent(container);
|
||||
btn.buttonEl.style.padding = "0.5em";
|
||||
btn.buttonEl.style.marginLeft = margin;
|
||||
setStyle(btn.buttonEl, {
|
||||
padding: "0.5em",
|
||||
marginLeft: margin,
|
||||
});
|
||||
btn.setTooltip(tooltip);
|
||||
|
||||
if (iconId) {
|
||||
@@ -497,17 +519,26 @@ export class GenericInputPrompt extends Modal {
|
||||
buttonBarContainer.createDiv();
|
||||
|
||||
if (this.buttons && this.buttons.length > 0) {
|
||||
let b = null;
|
||||
let b: ButtonComponent = null;
|
||||
for (const button of this.buttons) {
|
||||
const btn = new ButtonComponent(actionButtonContainer);
|
||||
btn.buttonEl.style.marginLeft = "5px";
|
||||
setStyle(btn.buttonEl, {
|
||||
marginLeft: "5px",
|
||||
});
|
||||
if (button.tooltip) {
|
||||
btn.setTooltip(button.tooltip);
|
||||
}
|
||||
button.iconId
|
||||
? btn.setIcon(button.iconId)
|
||||
: btn.setButtonText(button.caption);
|
||||
button.tooltip && btn.setTooltip(button.tooltip);
|
||||
|
||||
if (button.iconId) {
|
||||
btn.setIcon(button.iconId);
|
||||
} else {
|
||||
btn.setButtonText(button.caption);
|
||||
}
|
||||
|
||||
if (button.tooltip) {
|
||||
btn.setTooltip(button.tooltip);
|
||||
}
|
||||
|
||||
btn.onClick(() => {
|
||||
const res = button.action(this.input);
|
||||
if (res) {
|
||||
@@ -517,25 +548,32 @@ export class GenericInputPrompt extends Modal {
|
||||
});
|
||||
b = b ?? btn;
|
||||
}
|
||||
if (b) {
|
||||
if (b !== null) {
|
||||
b.setCta();
|
||||
b.buttonEl.style.marginRight = "0";
|
||||
setStyle(b.buttonEl, {
|
||||
marginRight: "0",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
this.createButton(
|
||||
actionButtonContainer,
|
||||
"",
|
||||
this.submitClickCallback.bind(this),
|
||||
t("PROMPT_BUTTON_OK") ?? "",
|
||||
"5px",
|
||||
"check",
|
||||
).setCta().buttonEl.style.marginRight = "0";
|
||||
setStyle(
|
||||
this.createButton(
|
||||
actionButtonContainer,
|
||||
"",
|
||||
() => this.submitClickCallback(),
|
||||
t("PROMPT_BUTTON_OK") ?? "",
|
||||
"5px",
|
||||
"check",
|
||||
).setCta().buttonEl,
|
||||
{
|
||||
marginRight: "0",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
this.createButton(
|
||||
actionButtonContainer,
|
||||
"",
|
||||
this.cancelClickCallback.bind(this),
|
||||
() => this.cancelClickCallback(),
|
||||
t("PROMPT_BUTTON_CANCEL"),
|
||||
"5px",
|
||||
"x",
|
||||
@@ -553,7 +591,7 @@ export class GenericInputPrompt extends Modal {
|
||||
this.createButton(
|
||||
editorButtonContainer,
|
||||
"",
|
||||
this.delBtnClickCallback.bind(this),
|
||||
() => this.delBtnClickCallback(),
|
||||
"Delete",
|
||||
"5px",
|
||||
"delete",
|
||||
@@ -569,7 +607,7 @@ export class GenericInputPrompt extends Modal {
|
||||
this.createButton(
|
||||
editorButtonContainer,
|
||||
"",
|
||||
this.specialCharsBtnClickCallback.bind(this),
|
||||
(evt) => this.specialCharsBtnClickCallback(evt),
|
||||
t("PROMPT_BUTTON_SPECIAL_CHARS"),
|
||||
"5px",
|
||||
"at-sign",
|
||||
@@ -578,7 +616,7 @@ export class GenericInputPrompt extends Modal {
|
||||
this.createButton(
|
||||
editorButtonContainer,
|
||||
"",
|
||||
this.linkBtnClickCallback.bind(this),
|
||||
() => this.linkBtnClickCallback(),
|
||||
t("PROMPT_BUTTON_INSERT_LINK"),
|
||||
"5px",
|
||||
"link",
|
||||
@@ -587,7 +625,7 @@ export class GenericInputPrompt extends Modal {
|
||||
this.createButton(
|
||||
editorButtonContainer,
|
||||
"",
|
||||
this.uppercaseBtnClickCallback.bind(this),
|
||||
() => this.uppercaseBtnClickCallback(),
|
||||
t("PROMPT_BUTTON_UPPERCASE"),
|
||||
"5px",
|
||||
"arrow-big-up",
|
||||
@@ -735,7 +773,7 @@ export class GenericInputPrompt extends Modal {
|
||||
|
||||
// Remove any existing popup
|
||||
const existingPopup = activeDocument.querySelector(
|
||||
".excalidraw-special-chars-popup",
|
||||
".excalidraw-genericInputPrompt-specialCharPopup",
|
||||
);
|
||||
if (existingPopup) {
|
||||
existingPopup.remove();
|
||||
@@ -744,23 +782,14 @@ export class GenericInputPrompt extends Modal {
|
||||
|
||||
// Create popup element
|
||||
const popup = activeDocument.createElement("div");
|
||||
popup.className = "excalidraw-special-chars-popup";
|
||||
popup.style.position = "absolute";
|
||||
popup.style.zIndex = "1000";
|
||||
popup.style.background = "var(--background-primary)";
|
||||
popup.style.border = "1px solid var(--background-modifier-border)";
|
||||
popup.style.borderRadius = "4px";
|
||||
popup.style.padding = "4px";
|
||||
popup.style.boxShadow = "0 2px 8px var(--background-modifier-box-shadow)";
|
||||
popup.style.display = "flex";
|
||||
popup.style.flexWrap = "wrap";
|
||||
popup.style.maxWidth = "200px";
|
||||
popup.addClass("excalidraw-genericInputPrompt-specialCharPopup");
|
||||
|
||||
// Position near the button
|
||||
const rect = (evt.target as HTMLElement).getBoundingClientRect();
|
||||
popup.style.top = `${rect.bottom + 5}px`;
|
||||
popup.style.left = `${rect.left}px`;
|
||||
|
||||
setStyle(popup, {
|
||||
top: `${rect.bottom + 5}px`,
|
||||
left: `${rect.left}px`,
|
||||
});
|
||||
// Special characters to include
|
||||
const specialChars = [
|
||||
",",
|
||||
@@ -782,13 +811,7 @@ export class GenericInputPrompt extends Modal {
|
||||
specialChars.forEach((char) => {
|
||||
const charButton = activeDocument.createElement("button");
|
||||
charButton.textContent = char;
|
||||
charButton.style.margin = "2px";
|
||||
charButton.style.width = "28px";
|
||||
charButton.style.height = "28px";
|
||||
charButton.style.cursor = "pointer";
|
||||
charButton.style.background = "var(--interactive-normal)";
|
||||
charButton.style.border = "none";
|
||||
charButton.style.borderRadius = "4px";
|
||||
charButton.addClass("excalidraw-genericInputPrompt-specialCharButton");
|
||||
|
||||
charButton.addEventListener("click", () => {
|
||||
this.insertStringBtnClickCallback(char);
|
||||
@@ -816,7 +839,7 @@ export class GenericInputPrompt extends Modal {
|
||||
}, 10);
|
||||
};
|
||||
|
||||
async onOpen() {
|
||||
onOpen() {
|
||||
super.onOpen();
|
||||
this.modalEl.classList.add("excalidraw-modal");
|
||||
this.containerEl.classList.add("excalidraw-modal");
|
||||
@@ -842,7 +865,9 @@ export class GenericInputPrompt extends Modal {
|
||||
modalEl.querySelector(".modal-titlebar") ||
|
||||
modalEl.querySelector(".modal-title") ||
|
||||
modalEl;
|
||||
(header as HTMLElement).style.cursor = "move";
|
||||
setStyle(header as HTMLElement, {
|
||||
cursor: "move",
|
||||
});
|
||||
|
||||
// Track focus changes to store the last focused interactive element
|
||||
const onFocusIn = (e: FocusEvent) => {
|
||||
@@ -904,10 +929,12 @@ export class GenericInputPrompt extends Modal {
|
||||
initialX = rect.left;
|
||||
initialY = rect.top;
|
||||
|
||||
modalEl.style.position = "absolute";
|
||||
modalEl.style.margin = "0";
|
||||
modalEl.style.left = `${initialX}px`;
|
||||
modalEl.style.top = `${initialY}px`;
|
||||
setStyle(modalEl, {
|
||||
position: "absolute",
|
||||
margin: "0",
|
||||
left: `${initialX}px`,
|
||||
top: `${initialY}px`,
|
||||
});
|
||||
};
|
||||
|
||||
const onPointerMove = (e: PointerEvent) => {
|
||||
@@ -918,8 +945,10 @@ export class GenericInputPrompt extends Modal {
|
||||
const dx = e.clientX - startX;
|
||||
const dy = e.clientY - startY;
|
||||
|
||||
modalEl.style.left = `${initialX + dx}px`;
|
||||
modalEl.style.top = `${initialY + dy}px`;
|
||||
setStyle(modalEl, {
|
||||
left: `${initialX + dx}px`,
|
||||
top: `${initialY + dy}px`,
|
||||
});
|
||||
};
|
||||
|
||||
const onPointerUp = () => {
|
||||
@@ -1140,7 +1169,7 @@ export class NewFileActions extends Modal {
|
||||
|
||||
this.contentEl.createDiv({ cls: "excalidraw-prompt-center" }, (el) => {
|
||||
//files manually follow one of two options:
|
||||
el.style.textAlign = "right";
|
||||
setStyle(el, { textAlign: "right" });
|
||||
|
||||
const checks = (): boolean => {
|
||||
if (!this.path || this.path === "") {
|
||||
@@ -1274,13 +1303,13 @@ export class MultiOptionConfirmationPrompt<T = boolean | null> extends Modal {
|
||||
this.titleEl.textContent = t("PROMPT_TITLE_CONFIRMATION");
|
||||
|
||||
const messageEl = this.contentEl.createDiv();
|
||||
messageEl.style.marginBottom = "1rem";
|
||||
messageEl.addClass("excalidraw-multiOptionConfirmationPrompt-message");
|
||||
setSanitizedHtml(messageEl, this.message);
|
||||
|
||||
const buttonContainer = this.contentEl.createDiv();
|
||||
buttonContainer.style.display = "flex";
|
||||
buttonContainer.style.justifyContent = "flex-end";
|
||||
buttonContainer.style.flexWrap = "wrap";
|
||||
buttonContainer.addClass(
|
||||
"excalidraw-multiOptionConfirmationPrompt-buttonContainer",
|
||||
);
|
||||
|
||||
// Convert Map to Array for easier iteration
|
||||
const buttonEntries = Array.from(this.buttons.entries());
|
||||
@@ -1299,7 +1328,9 @@ export class MultiOptionConfirmationPrompt<T = boolean | null> extends Modal {
|
||||
}
|
||||
|
||||
if (index < buttonEntries.length - 1) {
|
||||
button.buttonEl.style.marginRight = "0.5rem";
|
||||
setStyle(button.buttonEl, {
|
||||
marginRight: "0.5rem",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1319,8 +1350,8 @@ export class MultiOptionConfirmationPrompt<T = boolean | null> extends Modal {
|
||||
return button;
|
||||
}
|
||||
|
||||
async onOpen() {
|
||||
await super.onOpen();
|
||||
onOpen() {
|
||||
super.onOpen();
|
||||
const defaultButton =
|
||||
this.ctaButtonEl ?? this.contentEl.querySelector("button");
|
||||
// Obsidian modal open may apply its own autofocus after onOpen; defer to enforce default keyboard action.
|
||||
|
||||
@@ -105,7 +105,7 @@ export class PublishOutOfDateFilesDialog extends Modal {
|
||||
super(plugin.app);
|
||||
}
|
||||
|
||||
async onClose() {}
|
||||
onClose() {}
|
||||
|
||||
onOpen() {
|
||||
this.containerEl.classList.add("excalidraw-release");
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { App, MarkdownRenderer, Modal } from "obsidian";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { App, Component, MarkdownRenderer, Modal } from "obsidian";
|
||||
import { Rank, SwordColors } from "src/constants/actionIcons";
|
||||
import { convertSVGStringToElement } from "src/utils/utils";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
|
||||
export class RankMessage extends Modal {
|
||||
private renderComponent: Component;
|
||||
constructor(
|
||||
app: App,
|
||||
private plugin: ExcalidrawPlugin,
|
||||
private filecount: number,
|
||||
private rank: Rank,
|
||||
private color: string,
|
||||
@@ -18,15 +18,17 @@ export class RankMessage extends Modal {
|
||||
}
|
||||
|
||||
onOpen(): void {
|
||||
this.renderComponent = new Component();
|
||||
this.renderComponent.load();
|
||||
//this.contentEl.classList.add("excalidraw-release");
|
||||
this.containerEl.classList.add("excalidraw-release");
|
||||
this.titleEl.setText("Congratulations, glorious knight!");
|
||||
void this.createForm();
|
||||
}
|
||||
|
||||
async onClose() {
|
||||
onClose() {
|
||||
this.contentEl.empty();
|
||||
this.plugin = null;
|
||||
this.renderComponent.unload();
|
||||
}
|
||||
|
||||
async createForm() {
|
||||
@@ -44,12 +46,13 @@ export class RankMessage extends Modal {
|
||||
`You have ${this.filecount} Excalidraw drawings in your Vault earning you a new rank: **${this.rank}**! You've ascended to **${title}**!\n\nI've spent the past 3+ years building this plugin. If you appreciate my work, consider supporting me on [Ko-Fi](${URLs.KO_FI_COM_ZSOLT}) or join the next [Visual Thinking Workshop](${URLs.VISUAL_THINKING_WORKSHOP_COM}) cohort.`,
|
||||
this.contentEl,
|
||||
"",
|
||||
this.plugin,
|
||||
this.renderComponent,
|
||||
);
|
||||
|
||||
this.contentEl.createEl("p", { text: "" }, (el) => {
|
||||
//files manually follow one of two options:
|
||||
el.style.textAlign = "right";
|
||||
|
||||
setStyle(el, { textAlign: "right" });
|
||||
const bOk = el.createEl("button", { text: "Close" });
|
||||
bOk.onclick = () => this.close();
|
||||
});
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { App, MarkdownRenderer, Modal } from "obsidian";
|
||||
import { App, Component, MarkdownRenderer, Modal } from "obsidian";
|
||||
import { isVersionNewerThanOther } from "src/utils/utils";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { RELEASE_NOTES } from "./Messages";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
|
||||
declare const PLUGIN_VERSION: string;
|
||||
|
||||
@@ -16,6 +17,7 @@ export class ReleaseNotes extends Modal {
|
||||
private plugin: ExcalidrawPlugin;
|
||||
private options: ReleaseNotesOptions;
|
||||
private version: string;
|
||||
private renderComponent: Component;
|
||||
|
||||
constructor(
|
||||
app: App,
|
||||
@@ -30,6 +32,8 @@ export class ReleaseNotes extends Modal {
|
||||
}
|
||||
|
||||
onOpen(): void {
|
||||
this.renderComponent = new Component();
|
||||
this.renderComponent.load();
|
||||
const { containerEl, titleEl, headerEl } = this;
|
||||
//this.contentEl.classList.add("excalidraw-release");
|
||||
containerEl.classList.add("excalidraw-release");
|
||||
@@ -39,20 +43,23 @@ export class ReleaseNotes extends Modal {
|
||||
void this.createForm();
|
||||
|
||||
if (headerEl) {
|
||||
headerEl.style.pointerEvents = "none";
|
||||
setStyle(headerEl, { pointerEvents: "none" });
|
||||
} // Disable pointer events on header to allow clicks through
|
||||
}
|
||||
|
||||
async onClose() {
|
||||
onClose() {
|
||||
this.contentEl.empty();
|
||||
this.renderComponent.unload();
|
||||
if (this.options.persistVersion === false) {
|
||||
return;
|
||||
}
|
||||
await this.plugin.loadSettings();
|
||||
if (this.plugin.settings.previousRelease !== PLUGIN_VERSION) {
|
||||
this.plugin.settings.previousRelease = PLUGIN_VERSION;
|
||||
await this.plugin.saveSettings();
|
||||
}
|
||||
void (async () => {
|
||||
await this.plugin.loadSettings();
|
||||
if (this.plugin.settings.previousRelease !== PLUGIN_VERSION) {
|
||||
this.plugin.settings.previousRelease = PLUGIN_VERSION;
|
||||
await this.plugin.saveSettings();
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
async createForm() {
|
||||
@@ -78,12 +85,12 @@ export class ReleaseNotes extends Modal {
|
||||
message,
|
||||
this.contentEl,
|
||||
"",
|
||||
this.plugin,
|
||||
this.renderComponent,
|
||||
);
|
||||
|
||||
this.contentEl.createEl("p", { text: "" }, (el) => {
|
||||
//files manually follow one of two options:
|
||||
el.style.textAlign = "right";
|
||||
setStyle(el, { textAlign: "right" });
|
||||
const bOk = el.createEl("button", { text: "Close" });
|
||||
bOk.onclick = () => this.close();
|
||||
});
|
||||
|
||||
@@ -1,23 +1,27 @@
|
||||
import { MarkdownRenderer, Modal, Notice, request } from "obsidian";
|
||||
import { Component, MarkdownRenderer, Modal, Notice, request } from "obsidian";
|
||||
import ExcalidrawPlugin from "../../core/main";
|
||||
import { errorlog } from "../../utils/utils";
|
||||
import { log } from "src/utils/debugHelper";
|
||||
import { ContentSearcher } from "../components/ContentSearcher";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { mainDocument } from "src/constants/constants";
|
||||
import { t } from "src/lang/helpers";
|
||||
|
||||
const URL =
|
||||
URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_INDEX_NEW_MD;
|
||||
|
||||
export class ScriptInstallPrompt extends Modal {
|
||||
private contentDiv: HTMLDivElement;
|
||||
private renderComponent: Component;
|
||||
|
||||
constructor(private plugin: ExcalidrawPlugin) {
|
||||
super(plugin.app);
|
||||
// this.titleEl.setText(t("INSTAL_MODAL_TITLE"));
|
||||
}
|
||||
|
||||
async onOpen(): Promise<void> {
|
||||
onOpen(): void {
|
||||
this.renderComponent = new Component();
|
||||
this.renderComponent.load();
|
||||
this.contentEl.classList.add("excalidraw-scriptengine-install");
|
||||
this.contentDiv = mainDocument.createElement("div");
|
||||
this.contentEl.appendChild(this.contentDiv);
|
||||
@@ -25,42 +29,42 @@ export class ScriptInstallPrompt extends Modal {
|
||||
new ContentSearcher(this.contentDiv);
|
||||
|
||||
this.containerEl.classList.add("excalidraw-scriptengine-install");
|
||||
try {
|
||||
const source = await request({ url: URL });
|
||||
if (!source) {
|
||||
new Notice(
|
||||
"Error opening the Excalidraw Script Store page. " +
|
||||
"Please double check that you can access the website. " +
|
||||
"I've logged the link in developer console (press CTRL+SHIFT+i)",
|
||||
5000,
|
||||
void (async () => {
|
||||
try {
|
||||
const source = await request({ url: URL });
|
||||
if (!source) {
|
||||
new Notice(t("SCRIPT_INSTALL_PROMPT_FETCH_ERROR"), 5000);
|
||||
log(URL);
|
||||
this.close();
|
||||
return;
|
||||
}
|
||||
await MarkdownRenderer.render(
|
||||
this.plugin.app,
|
||||
source,
|
||||
this.contentDiv,
|
||||
"",
|
||||
this.renderComponent,
|
||||
);
|
||||
log(URL);
|
||||
this.close();
|
||||
return;
|
||||
}
|
||||
await MarkdownRenderer.render(
|
||||
this.plugin.app,
|
||||
source,
|
||||
this.contentDiv,
|
||||
"",
|
||||
this.plugin,
|
||||
);
|
||||
this.contentDiv
|
||||
.querySelectorAll("h1[data-heading],h2[data-heading],h3[data-heading]")
|
||||
.forEach((el) => {
|
||||
el.setAttribute("id", el.getAttribute("data-heading"));
|
||||
this.contentDiv
|
||||
.querySelectorAll(
|
||||
"h1[data-heading],h2[data-heading],h3[data-heading]",
|
||||
)
|
||||
.forEach((el) => {
|
||||
el.setAttribute("id", el.getAttribute("data-heading"));
|
||||
});
|
||||
this.contentDiv.querySelectorAll("a.internal-link").forEach((el) => {
|
||||
el.removeAttribute("target");
|
||||
});
|
||||
this.contentDiv.querySelectorAll("a.internal-link").forEach((el) => {
|
||||
el.removeAttribute("target");
|
||||
});
|
||||
} catch (e) {
|
||||
errorlog({ where: "ScriptInstallPrompt.onOpen", error: e });
|
||||
new Notice("Could not open ScriptEngine repository");
|
||||
this.close();
|
||||
}
|
||||
} catch (e) {
|
||||
errorlog({ where: "ScriptInstallPrompt.onOpen", error: e as unknown });
|
||||
new Notice(t("SCRIPT_INSTALL_PROMPT_OPEN_ERROR"));
|
||||
this.close();
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
onClose(): void {
|
||||
this.contentEl.empty();
|
||||
this.renderComponent.unload();
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ import { App, FuzzySuggestModal, Notice } from "obsidian";
|
||||
import { t } from "../../lang/helpers";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { getEA } from "src/core";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import {
|
||||
CARD_HEIGHT,
|
||||
CARD_WIDTH,
|
||||
|
||||
@@ -14,9 +14,9 @@ export class UIModeSettings extends Modal {
|
||||
void this.createForm();
|
||||
}
|
||||
|
||||
async onClose() {
|
||||
onClose() {
|
||||
if (this.isDirty) {
|
||||
await this.plugin.saveSettings();
|
||||
void this.plugin.saveSettings();
|
||||
}
|
||||
this.plugin = null;
|
||||
}
|
||||
@@ -27,7 +27,9 @@ export class UIModeSettings extends Modal {
|
||||
this.contentEl,
|
||||
this.plugin.settings,
|
||||
this.app,
|
||||
() => this.applySettingsUpdate(),
|
||||
() => {
|
||||
void this.applySettingsUpdate();
|
||||
},
|
||||
() => this.close(),
|
||||
).render();
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ import { InsertPDFModal } from "./InsertPDFModal";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { cleanSectionHeading } from "src/utils/pathUtils";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { hideElement, setStyle, showElement } from "src/utils/styleUtils";
|
||||
|
||||
export class UniversalInsertFileModal extends Modal {
|
||||
private center: { x: number; y: number } = { x: 0, y: 0 };
|
||||
@@ -128,8 +129,8 @@ export class UniversalInsertFileModal extends Modal {
|
||||
: null;
|
||||
|
||||
if (isMarkdown || (isExcalidraw && sections?.length > 0)) {
|
||||
sectionPickerSetting.settingEl.style.display = "";
|
||||
sectionPicker.selectEl.style.display = "block";
|
||||
showElement(sectionPickerSetting.settingEl);
|
||||
showElement(sectionPicker.selectEl);
|
||||
while (sectionPicker.selectEl.options.length > 0) {
|
||||
sectionPicker.selectEl.remove(0);
|
||||
}
|
||||
@@ -143,20 +144,20 @@ export class UniversalInsertFileModal extends Modal {
|
||||
);
|
||||
});
|
||||
} else {
|
||||
sectionPickerSetting.settingEl.style.display = "none";
|
||||
sectionPicker.selectEl.style.display = "none";
|
||||
hideElement(sectionPickerSetting.settingEl);
|
||||
hideElement(sectionPicker.selectEl);
|
||||
}
|
||||
|
||||
if (isExcalidraw && !isSelf) {
|
||||
sizeToggleSetting.settingEl.style.display = "";
|
||||
showElement(sizeToggleSetting.settingEl);
|
||||
} else {
|
||||
sizeToggleSetting.settingEl.style.display = "none";
|
||||
hideElement(sizeToggleSetting.settingEl);
|
||||
}
|
||||
|
||||
if (!isSelf && (isImage || file?.extension === "md")) {
|
||||
actionImage.buttonEl.style.display = "block";
|
||||
showElement(actionImage.buttonEl);
|
||||
} else {
|
||||
actionImage.buttonEl.style.display = "none";
|
||||
hideElement(actionImage.buttonEl);
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -164,15 +165,15 @@ export class UniversalInsertFileModal extends Modal {
|
||||
isAnimatedImage ||
|
||||
(isExcalidraw && sections?.length > 0)
|
||||
) {
|
||||
actionIFrame.buttonEl.style.display = "block";
|
||||
showElement(actionIFrame.buttonEl);
|
||||
} else {
|
||||
actionIFrame.buttonEl.style.display = "none";
|
||||
hideElement(actionIFrame.buttonEl);
|
||||
}
|
||||
|
||||
if (isPDF) {
|
||||
actionPDF.buttonEl.style.display = "block";
|
||||
showElement(actionPDF.buttonEl);
|
||||
} else {
|
||||
actionPDF.buttonEl.style.display = "none";
|
||||
hideElement(actionPDF.buttonEl);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -192,7 +193,7 @@ export class UniversalInsertFileModal extends Modal {
|
||||
);
|
||||
|
||||
const search = new TextComponent(ce);
|
||||
search.inputEl.style.width = "100%";
|
||||
setStyle(search.inputEl, { width: "100%" });
|
||||
const suggester = new FileSuggestionModal(
|
||||
this.app,
|
||||
search,
|
||||
@@ -210,7 +211,7 @@ export class UniversalInsertFileModal extends Modal {
|
||||
.setName(t("UIFM_SECTION_HEAD"))
|
||||
.addDropdown((dropdown) => {
|
||||
sectionPicker = dropdown;
|
||||
sectionPicker.selectEl.style.width = "100%";
|
||||
setStyle(sectionPicker.selectEl, { width: "100%" });
|
||||
});
|
||||
|
||||
const sizeToggleSetting = new Setting(ce)
|
||||
@@ -312,20 +313,6 @@ export class UniversalInsertFileModal extends Modal {
|
||||
return;
|
||||
}
|
||||
return;
|
||||
case "i":
|
||||
if (isVisible(actionImage)) {
|
||||
actionImage.buttonEl.click();
|
||||
}
|
||||
return;
|
||||
case "p":
|
||||
if (isVisible(actionPDF)) {
|
||||
actionPDF.buttonEl.click();
|
||||
}
|
||||
return;
|
||||
case "f":
|
||||
if (isVisible(actionIFrame)) {
|
||||
actionIFrame.buttonEl.click();
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -91,21 +91,22 @@ export class VersionMismatchPrompt extends Modal {
|
||||
});
|
||||
|
||||
setElementDisplay(buttonBar, "flex");
|
||||
buttonBar.style.gap = "0.5rem";
|
||||
buttonBar.style.marginTop = "1rem";
|
||||
redownloadBtn.style.backgroundColor = "var(--interactive-accent)";
|
||||
redownloadBtn.style.color = "var(--text-on-accent)";
|
||||
buttonBar.addClass("excalidraw-versionmismatch-buttonbar");
|
||||
redownloadBtn.addClass("mod-cta");
|
||||
}
|
||||
|
||||
async onClose() {
|
||||
onClose() {
|
||||
super.onClose();
|
||||
if (this.isDirty) {
|
||||
await this.plugin.saveSettings();
|
||||
void this.plugin.saveSettings();
|
||||
}
|
||||
if (!this.resolvePromise) {
|
||||
return;
|
||||
}
|
||||
if (!this.resolved) {
|
||||
this.resolvePromise && this.resolvePromise(false);
|
||||
this.resolvePromise(false);
|
||||
} else {
|
||||
this.resolvePromise && this.resolvePromise(true);
|
||||
this.resolvePromise(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { ExcalidrawTextElement } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { Notice } from "obsidian";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { NamedExcalidrawFrameElement } from "src/types/excalidrawElementTypes";
|
||||
@@ -173,10 +172,7 @@ export async function copyLinkToSelectedElementToClipboard(
|
||||
const ownerDoc = wrapper.ownerDocument ?? mainDocument;
|
||||
|
||||
const anchorRow = ownerDoc.createElement("label");
|
||||
anchorRow.style.display = "flex";
|
||||
anchorRow.style.alignItems = "center";
|
||||
anchorRow.style.gap = "8px";
|
||||
anchorRow.style.marginTop = "8px";
|
||||
anchorRow.addClass("excalidraw-copylinkprompt-label");
|
||||
|
||||
const anchorCb = ownerDoc.createElement("input");
|
||||
anchorCb.type = "checkbox";
|
||||
@@ -195,10 +191,7 @@ export async function copyLinkToSelectedElementToClipboard(
|
||||
|
||||
if (frameNameIsValid) {
|
||||
const frameRow = ownerDoc.createElement("label");
|
||||
frameRow.style.display = "flex";
|
||||
frameRow.style.alignItems = "center";
|
||||
frameRow.style.gap = "8px";
|
||||
frameRow.style.marginTop = "8px";
|
||||
frameRow.addClass("excalidraw-copylinkprompt-label");
|
||||
|
||||
const frameCb = ownerDoc.createElement("input");
|
||||
frameCb.type = "checkbox";
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
FileId,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { App, MarkdownRenderer, Notice, TFile } from "obsidian";
|
||||
import { App, Component, MarkdownRenderer, Notice, TFile } from "obsidian";
|
||||
import {
|
||||
DEFAULT_MD_EMBED_CSS,
|
||||
fileid,
|
||||
@@ -57,7 +57,7 @@ import {
|
||||
shouldRenderMermaid,
|
||||
} from "../utils/mermaidUtils";
|
||||
import { mermaidToExcalidraw } from "src/constants/constants";
|
||||
import { ImageKey, imageCache } from "./ImageCache";
|
||||
import { ImageKey, getImageCache } from "./ImageCache";
|
||||
import { FILENAMEPARTS, PreviewImageType } from "../types/utilTypes";
|
||||
import {
|
||||
ColorMap,
|
||||
@@ -69,6 +69,12 @@ import {
|
||||
} from "src/types/embeddedFileLoaderTypes";
|
||||
import { ExportSettings } from "src/types/exportUtilTypes";
|
||||
import { setStyleText } from "src/utils/htmlUtils";
|
||||
import { hideElement, setStyle } from "src/utils/styleUtils";
|
||||
import {
|
||||
isInstanceOfHTMLImageElement,
|
||||
isInstanceOfSVGElement,
|
||||
} from "src/utils/typechecks";
|
||||
import { strictArrayBuffer } from "src/utils/obsidianUtils";
|
||||
|
||||
//An ugly workaround for the following situation.
|
||||
//File A is a markdown file that has an embedded Excalidraw file B
|
||||
@@ -144,7 +150,7 @@ const replaceSVGColors = (
|
||||
|
||||
// Modify the fill and stroke attributes of child nodes
|
||||
const childNodes = (node: ChildNode) => {
|
||||
if (node instanceof SVGElement) {
|
||||
if (isInstanceOfSVGElement(node)) {
|
||||
const oldFill = node.getAttribute("fill")?.toLocaleLowerCase();
|
||||
const oldStroke = node.getAttribute("stroke")?.toLocaleLowerCase();
|
||||
|
||||
@@ -211,7 +217,12 @@ export class EmbeddedFile {
|
||||
this.colorMap = colorMapJSON
|
||||
? JSON.parse(colorMapJSON.toLocaleLowerCase())
|
||||
: null;
|
||||
} catch (_) {
|
||||
} catch (error) {
|
||||
console.log(
|
||||
`Error parsing colorMap for file ${imgPath}`,
|
||||
this.constructor,
|
||||
error,
|
||||
);
|
||||
this.colorMap = null;
|
||||
}
|
||||
}
|
||||
@@ -489,7 +500,7 @@ export class EmbeddedFilesLoader {
|
||||
!hasColorMap &&
|
||||
this.plugin.settings.allowImageCacheInScene &&
|
||||
file &&
|
||||
imageCache.isReady();
|
||||
getImageCache().isReady();
|
||||
const hasFilenameParts = Boolean(
|
||||
inFile instanceof EmbeddedFile && inFile.filenameparts,
|
||||
);
|
||||
@@ -524,7 +535,7 @@ export class EmbeddedFilesLoader {
|
||||
};
|
||||
|
||||
const maybeSVG = shouldUseCache
|
||||
? await imageCache.getImageFromCache(cacheKey, {
|
||||
? await getImageCache().getImageFromCache(cacheKey, {
|
||||
skipDependencyCheck: cacheValidation === "stale-first",
|
||||
})
|
||||
: undefined;
|
||||
@@ -612,7 +623,7 @@ export class EmbeddedFilesLoader {
|
||||
if (shouldUseCache && !maybeSVG) {
|
||||
//cache SVG should have the width and height parameters and not the embedded font
|
||||
//see svgWithFont below
|
||||
imageCache.addImageToCache(cacheKey, "", svg);
|
||||
getImageCache().addImageToCache(cacheKey, "", svg);
|
||||
}
|
||||
|
||||
if (!svg.hasAttribute("width") && svg.hasAttribute("viewBox")) {
|
||||
@@ -826,6 +837,9 @@ export class EmbeddedFilesLoader {
|
||||
addFiles,
|
||||
depth,
|
||||
isThemeChange = false,
|
||||
// the fileIDWhitelist is designed to support partial loading of Excalidraw drawings.
|
||||
// See getTemplate in excalidrawAutomateUtils. By providing the whitelist loading the scene will skip images
|
||||
// not on the list (e.g. when rendering an image fragment based on a groupID or frame reference)
|
||||
fileIDWhiteList,
|
||||
forceReloadFileIDs,
|
||||
cacheValidation = "validated",
|
||||
@@ -848,7 +862,7 @@ export class EmbeddedFilesLoader {
|
||||
new Notice(t("INFINITE_LOOP_WARNING") + depth.toString(), 6000);
|
||||
return;
|
||||
}
|
||||
const entries = excalidrawData.getFileEntries();
|
||||
const entries = Array.from(excalidrawData.getFileEntries());
|
||||
//debug({where:"EmbeddedFileLoader.loadSceneFiles",uid:this.uid,isDark:this.isDark,sceneTheme:excalidrawData.scene.appState.theme});
|
||||
if (this.isDark === undefined) {
|
||||
this.isDark = excalidrawData?.scene?.appState?.theme === "dark";
|
||||
@@ -869,7 +883,6 @@ export class EmbeddedFilesLoader {
|
||||
});
|
||||
}
|
||||
});
|
||||
let entry: IteratorResult<[FileId, EmbeddedFile]>;
|
||||
const files: FileData[][] = [];
|
||||
files.push([]);
|
||||
let batch = 0;
|
||||
@@ -879,12 +892,12 @@ export class EmbeddedFilesLoader {
|
||||
function* loadIterator(
|
||||
this: EmbeddedFilesLoader,
|
||||
): Generator<Promise<void>> {
|
||||
while (!(entry = entries.next()).done) {
|
||||
if (fileIDWhiteList && !fileIDWhiteList.has(entry.value[0])) {
|
||||
for (const entry of entries) {
|
||||
if (fileIDWhiteList && !fileIDWhiteList.has(entry[0])) {
|
||||
continue;
|
||||
}
|
||||
const embeddedFile: EmbeddedFile = entry.value[1];
|
||||
const id = entry.value[0];
|
||||
const embeddedFile: EmbeddedFile = entry[1];
|
||||
const id = entry[0];
|
||||
yield createSafeLoadTask(
|
||||
async () => {
|
||||
if (this.terminate) {
|
||||
@@ -1114,7 +1127,7 @@ export class EmbeddedFilesLoader {
|
||||
const pageNum = isNaN(linkParts.page) ? 1 : (linkParts.page ?? 1);
|
||||
const requestedScale = this.plugin.settings.pdfScale;
|
||||
const shouldUseCache =
|
||||
imageCache.isReady() &&
|
||||
getImageCache().isReady() &&
|
||||
(!options || this.plugin.settings.allowImageCacheInScene);
|
||||
const cacheKey: ImageKey = {
|
||||
filepath: file.path,
|
||||
@@ -1137,7 +1150,7 @@ export class EmbeddedFilesLoader {
|
||||
inlineFonts: false,
|
||||
};
|
||||
const cachedData = shouldUseCache
|
||||
? await imageCache.getImageCacheData(cacheKey, {
|
||||
? await getImageCache().getImageCacheData(cacheKey, {
|
||||
skipDependencyCheck: options?.cacheValidation === "stale-first",
|
||||
minRenderScale:
|
||||
options?.cacheValidation === "stale-first"
|
||||
@@ -1326,12 +1339,13 @@ export class EmbeddedFilesLoader {
|
||||
});
|
||||
});
|
||||
const base64 = await blobToBase64(blob);
|
||||
shouldUseCache &&
|
||||
imageCache.addImageToCache(cacheKey, "", blob, {
|
||||
if (shouldUseCache) {
|
||||
getImageCache().addImageToCache(cacheKey, "", blob, {
|
||||
renderScale: requestedScale,
|
||||
size: { width, height },
|
||||
pdfPageViewProps: viewProps,
|
||||
});
|
||||
}
|
||||
const result: [DataURL, Size, PDFPageViewProps, number, boolean] = [
|
||||
`data:image/png;base64,${base64}` as DataURL,
|
||||
{ width, height },
|
||||
@@ -1404,10 +1418,11 @@ export class EmbeddedFilesLoader {
|
||||
case "":
|
||||
fontDef = "";
|
||||
break;
|
||||
default:
|
||||
default: {
|
||||
const font = await getFontDataURL(plugin.app, fontName, file.path);
|
||||
fontDef = font.fontDef;
|
||||
fontName = font.fontName;
|
||||
}
|
||||
}
|
||||
|
||||
if (fileCache?.frontmatter && fileCache.frontmatter.banner !== null) {
|
||||
@@ -1473,22 +1488,26 @@ export class EmbeddedFilesLoader {
|
||||
const mdDIV = createDiv();
|
||||
mdDIV.setAttribute("xmlns", "http://www.w3.org/1999/xhtml");
|
||||
mdDIV.setAttribute("class", "excalidraw-md-host");
|
||||
// mdDIV.setAttribute("style",style);
|
||||
if (fontName !== "") {
|
||||
mdDIV.style.fontFamily = fontName;
|
||||
setStyle(mdDIV, { fontFamily: fontName });
|
||||
}
|
||||
mdDIV.style.overflow = "auto";
|
||||
mdDIV.style.display = "block";
|
||||
mdDIV.style.color = fontColor && fontColor !== "" ? fontColor : "initial";
|
||||
setStyle(mdDIV, {
|
||||
overflow: "auto",
|
||||
display: "block",
|
||||
color: fontColor && fontColor !== "" ? fontColor : "initial",
|
||||
});
|
||||
|
||||
const renderComponent = new Component();
|
||||
renderComponent.load();
|
||||
//await MarkdownRenderer.renderMarkdown(text, mdDIV, file.path, plugin);
|
||||
await MarkdownRenderer.render(
|
||||
this.plugin.app,
|
||||
text,
|
||||
mdDIV,
|
||||
file.path,
|
||||
this.plugin,
|
||||
renderComponent,
|
||||
);
|
||||
renderComponent.unload();
|
||||
|
||||
mdDIV
|
||||
.querySelectorAll(":scope > *[class^='frontmatter']")
|
||||
@@ -1528,7 +1547,7 @@ export class EmbeddedFilesLoader {
|
||||
//First I need to create a fully self contained copy of the document to convert
|
||||
//blank styles into inline styles using computedStyle
|
||||
const iframeHost = mainDocument.body.createDiv();
|
||||
iframeHost.style.display = "none";
|
||||
hideElement(iframeHost);
|
||||
const iframe = iframeHost.createEl("iframe");
|
||||
const iframeDoc = iframe.contentWindow.document;
|
||||
if (style) {
|
||||
@@ -1547,9 +1566,10 @@ export class EmbeddedFilesLoader {
|
||||
const elementStyle = el.style;
|
||||
const computedStyle = window.getComputedStyle(el);
|
||||
let style = "";
|
||||
for (const prop in elementStyle) {
|
||||
if (elementStyle.hasOwnProperty(prop)) {
|
||||
style += `${prop}: ${computedStyle[prop]};`;
|
||||
for (const [prop] of Object.entries(elementStyle)) {
|
||||
if (Object.hasOwn(elementStyle ?? {}, prop)) {
|
||||
const value = computedStyle.getPropertyValue(prop);
|
||||
style += `${prop}: ${value};`;
|
||||
}
|
||||
}
|
||||
el.setAttribute("style", style);
|
||||
@@ -1581,8 +1601,10 @@ export class EmbeddedFilesLoader {
|
||||
//finalize SVG
|
||||
svgStyle = ` width="${linkParts.width}px" height="${svgHeight}px"`;
|
||||
foreignObjectStyle = ` width="${linkParts.width}px" height="${svgHeight}px"`;
|
||||
mdDIV.style.height = `${svgHeight - footerHeight}px`;
|
||||
mdDIV.style.overflow = "hidden";
|
||||
setStyle(mdDIV, {
|
||||
height: `${svgHeight - footerHeight}px`,
|
||||
overflow: "hidden",
|
||||
});
|
||||
|
||||
const imageList = mdDIV.querySelectorAll(
|
||||
"img:not([src^='data:image/svg+xml'])",
|
||||
@@ -1592,8 +1614,8 @@ export class EmbeddedFilesLoader {
|
||||
}
|
||||
if (hasSVGwithBitmap && this.isDark) {
|
||||
imageList.forEach((img) => {
|
||||
if (img instanceof HTMLImageElement) {
|
||||
img.style.filter = THEME_FILTER;
|
||||
if (isInstanceOfHTMLImageElement(img)) {
|
||||
setStyle(img, { filter: THEME_FILTER });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1650,16 +1672,21 @@ export const generateIdFromFile = async (
|
||||
|
||||
// Hash the combined data (file and key, if provided)
|
||||
// Ensure we pass an ArrayBuffer (not ArrayBufferLike) to subtle.digest
|
||||
const buffer: ArrayBuffer = dataToHash.buffer.slice(
|
||||
dataToHash.byteOffset,
|
||||
dataToHash.byteOffset + dataToHash.byteLength,
|
||||
) as ArrayBuffer;
|
||||
const buffer = strictArrayBuffer(
|
||||
dataToHash.buffer.slice(
|
||||
dataToHash.byteOffset,
|
||||
dataToHash.byteOffset + dataToHash.byteLength,
|
||||
),
|
||||
);
|
||||
const hashBuffer = await window.crypto.subtle.digest("SHA-1", buffer);
|
||||
id = Array.from(new Uint8Array(hashBuffer))
|
||||
.map((byte) => byte.toString(16).padStart(2, "0"))
|
||||
.join("") as FileId;
|
||||
} catch (error) {
|
||||
errorlog({ where: "EmbeddedFileLoader.generateIdFromFile", error });
|
||||
errorlog({
|
||||
where: "EmbeddedFileLoader.generateIdFromFile",
|
||||
error: error as unknown,
|
||||
});
|
||||
id = fileid() as FileId;
|
||||
}
|
||||
return id;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import LZString from "lz-string";
|
||||
import {
|
||||
FillStyle,
|
||||
StrokeStyle,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
RoundnessType,
|
||||
ExcalidrawFrameElement,
|
||||
ExcalidrawTextContainer,
|
||||
ElementsMap,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { ColorMap, MimeType } from "../types/embeddedFileLoaderTypes";
|
||||
import {
|
||||
@@ -202,7 +204,7 @@ import { AIRequest, ExcalidrawAISettings } from "src/types/AIUtilTypes";
|
||||
import { getAspectRatio } from "src/utils/YoutTubeUtils";
|
||||
import { getPDFCropRect } from "src/utils/PDFUtils";
|
||||
import { CaptureUpdateActionType } from "@zsviczian/excalidraw/types/element/src";
|
||||
import { URL_REGISTRY, URLs } from "src/constants/safeUrls";
|
||||
import { URL_REGISTRY } from "src/constants/safeUrls";
|
||||
|
||||
type ExcalidrawAutomateHelpTarget = ((...args: unknown[]) => unknown) | string;
|
||||
|
||||
@@ -815,6 +817,9 @@ export class ExcalidrawAutomate {
|
||||
startArrowHead: string; //"arrow"|"bar"|"circle"|"circle_outline"|"triangle"|"triangle_outline"|"diamond"|"diamond_outline"|null
|
||||
endArrowHead: string;
|
||||
};
|
||||
setStyle(style: Partial<ExcalidrawAutomate["style"]>) {
|
||||
Object.assign(this.style, style);
|
||||
}
|
||||
canvas: {
|
||||
theme: string; //"dark"|"light"
|
||||
viewBackgroundColor: string;
|
||||
@@ -1059,13 +1064,13 @@ export class ExcalidrawAutomate {
|
||||
setFillStyle(val: number): "hachure" | "cross-hatch" | "solid" {
|
||||
switch (val) {
|
||||
case 0:
|
||||
this.style.fillStyle = "hachure";
|
||||
this.setStyle({ fillStyle: "hachure" });
|
||||
return "hachure";
|
||||
case 1:
|
||||
this.style.fillStyle = "cross-hatch";
|
||||
this.setStyle({ fillStyle: "cross-hatch" });
|
||||
return "cross-hatch";
|
||||
default:
|
||||
this.style.fillStyle = "solid";
|
||||
this.setStyle({ fillStyle: "solid" });
|
||||
return "solid";
|
||||
}
|
||||
}
|
||||
@@ -1078,13 +1083,13 @@ export class ExcalidrawAutomate {
|
||||
setStrokeStyle(val: number): "solid" | "dashed" | "dotted" {
|
||||
switch (val) {
|
||||
case 0:
|
||||
this.style.strokeStyle = "solid";
|
||||
this.setStyle({ strokeStyle: "solid" });
|
||||
return "solid";
|
||||
case 1:
|
||||
this.style.strokeStyle = "dashed";
|
||||
this.setStyle({ strokeStyle: "dashed" });
|
||||
return "dashed";
|
||||
default:
|
||||
this.style.strokeStyle = "dotted";
|
||||
this.setStyle({ strokeStyle: "dotted" });
|
||||
return "dotted";
|
||||
}
|
||||
}
|
||||
@@ -1097,12 +1102,14 @@ export class ExcalidrawAutomate {
|
||||
setStrokeSharpness(val: number): "round" | "sharp" {
|
||||
switch (val) {
|
||||
case 0:
|
||||
this.style.roundness = {
|
||||
type: ROUNDNESS.LEGACY,
|
||||
};
|
||||
this.setStyle({
|
||||
roundness: {
|
||||
type: ROUNDNESS.LEGACY,
|
||||
},
|
||||
});
|
||||
return "round";
|
||||
default:
|
||||
this.style.roundness = null; //sharp
|
||||
this.setStyle({ roundness: null }); //sharp
|
||||
return "sharp";
|
||||
}
|
||||
}
|
||||
@@ -1113,7 +1120,7 @@ export class ExcalidrawAutomate {
|
||||
* @returns {string} The font family string.
|
||||
*/
|
||||
setFontFamily(val: number): string {
|
||||
this.style.fontFamily = val;
|
||||
this.setStyle({ fontFamily: val });
|
||||
return getFontFamilyString({ fontFamily: val });
|
||||
}
|
||||
|
||||
@@ -2360,7 +2367,7 @@ export class ExcalidrawAutomate {
|
||||
|
||||
let boxId: string = null;
|
||||
const strokeColor = this.style.strokeColor;
|
||||
this.style.strokeColor = formatting?.boxStrokeColor ?? strokeColor;
|
||||
this.setStyle({ strokeColor: formatting?.boxStrokeColor ?? strokeColor });
|
||||
const boxPadding = formatting?.boxPadding ?? 30;
|
||||
if (formatting?.box) {
|
||||
switch (formatting.box) {
|
||||
@@ -2397,7 +2404,7 @@ export class ExcalidrawAutomate {
|
||||
);
|
||||
}
|
||||
}
|
||||
this.style.strokeColor = strokeColor;
|
||||
this.setStyle({ strokeColor });
|
||||
const isContainerBound = boxId && formatting.box !== "blob";
|
||||
const newTextElement = {
|
||||
text,
|
||||
@@ -2438,7 +2445,7 @@ export class ExcalidrawAutomate {
|
||||
const dimensions = refreshTextDimensions(
|
||||
textElement,
|
||||
container,
|
||||
arrayToMap(this.getElements()),
|
||||
arrayToMap(this.getElements()) as ElementsMap,
|
||||
originalText,
|
||||
);
|
||||
|
||||
@@ -3051,13 +3058,13 @@ export class ExcalidrawAutomate {
|
||||
angle -= Math.PI;
|
||||
//delta = -delta;
|
||||
}
|
||||
this.style.angle = angle;
|
||||
this.setStyle({ angle });
|
||||
const id = this.addText(
|
||||
line.x + line.points[1][0] / 2 - size.width / 2, //+delta,
|
||||
line.y + line.points[1][1] / 2 - size.height, //-5*size.height/6,
|
||||
label,
|
||||
);
|
||||
this.style.angle = 0;
|
||||
this.setStyle({ angle: 0 });
|
||||
return id;
|
||||
}
|
||||
|
||||
@@ -3657,8 +3664,8 @@ export class ExcalidrawAutomate {
|
||||
* @param {ExcalidrawElement[]} [scene.elements] - Array of elements in the scene.
|
||||
* @param {AppState} [scene.appState] - The app state of the scene.
|
||||
* @param {BinaryFiles} [scene.files] - The files in the scene.
|
||||
* @param {boolean} [scene.commitToHistory] - Whether to commit the scene to history. @deprecated Use scene.storageOption instead
|
||||
* @param {"capture" | "none" | "update"} [scene.storeAction] - The store action for the scene. @deprecated Use scene.storageOption instead
|
||||
* @param {boolean} [scene.commitToHistory] - Deprecated: Use scene.storageOption instead.
|
||||
* @param {"capture" | "none" | "update"} [scene.storeAction] - Deprecated: Use scene.storageOption instead
|
||||
* @param {"IMMEDIATELY" | "NEVER" | "EVENTUALLY"} [scene.captureUpdate] - The capture update action for the scene.
|
||||
* @param {boolean} [restore=false] - Whether to restore legacy elements in the scene.
|
||||
*/
|
||||
@@ -4153,7 +4160,7 @@ export class ExcalidrawAutomate {
|
||||
* @returns {ExcalidrawElement[][]} Array of arrays of grouped elements.
|
||||
*/
|
||||
getMaximumGroups(elements: ExcalidrawElement[]): ExcalidrawElement[][] {
|
||||
return getMaximumGroups(elements, arrayToMap(elements));
|
||||
return getMaximumGroups(elements, arrayToMap(elements) as ElementsMap);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4547,20 +4554,25 @@ export class ExcalidrawAutomate {
|
||||
|
||||
/**
|
||||
* Clones an array of Excalidraw elements or a clipboard string.
|
||||
* Ensures that relationships (containers, bound elements, groups, bindings)
|
||||
* Ensures that relationships (containers, bound elements, groups, bindings)
|
||||
* are correctly remapped to the newly generated IDs.
|
||||
*
|
||||
*
|
||||
* @param {ExcalidrawElement[] | string} elementsOrClipboard - The elements array or Excalidraw clipboard string.
|
||||
* @returns {ExcalidrawElement[]} An array of cloned elements with new IDs and updated relationships.
|
||||
*/
|
||||
cloneElements(elementsOrClipboard: ExcalidrawElement[] | string): ExcalidrawElement[] {
|
||||
cloneElements(
|
||||
elementsOrClipboard: ExcalidrawElement[] | string,
|
||||
): ExcalidrawElement[] {
|
||||
let elements: ExcalidrawElement[] = [];
|
||||
|
||||
// 1. Parse the input
|
||||
if (typeof elementsOrClipboard === "string") {
|
||||
try {
|
||||
const parsed = JSON.parse(elementsOrClipboard);
|
||||
if (parsed.type === "excalidraw/clipboard" && Array.isArray(parsed.elements)) {
|
||||
if (
|
||||
parsed.type === "excalidraw/clipboard" &&
|
||||
Array.isArray(parsed.elements)
|
||||
) {
|
||||
elements = parsed.elements;
|
||||
} else if (Array.isArray(parsed)) {
|
||||
elements = parsed;
|
||||
@@ -4574,11 +4586,15 @@ export class ExcalidrawAutomate {
|
||||
} else if (Array.isArray(elementsOrClipboard)) {
|
||||
elements = elementsOrClipboard;
|
||||
} else {
|
||||
console.error("Invalid input. Expected array of elements or clipboard string.");
|
||||
console.error(
|
||||
"Invalid input. Expected array of elements or clipboard string.",
|
||||
);
|
||||
return [];
|
||||
}
|
||||
|
||||
if (!elements || elements.length === 0) return [];
|
||||
if (!elements || elements.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// 2. Create ID mappings
|
||||
const idMap = new Map<string, string>();
|
||||
@@ -4587,7 +4603,7 @@ export class ExcalidrawAutomate {
|
||||
// Pre-generate new IDs for elements and groups
|
||||
elements.forEach((el) => {
|
||||
idMap.set(el.id, nanoid());
|
||||
|
||||
|
||||
if (el.groupIds && Array.isArray(el.groupIds)) {
|
||||
el.groupIds.forEach((groupId: string) => {
|
||||
if (!groupMap.has(groupId)) {
|
||||
@@ -4598,16 +4614,18 @@ export class ExcalidrawAutomate {
|
||||
});
|
||||
|
||||
// 3. Clone and remap relationships
|
||||
const clonedElements: any[] = elements.map((el) => {
|
||||
const clonedElements: ExcalidrawElement[] = elements.map((el) => {
|
||||
// Deep clone the element
|
||||
const newEl = JSON.parse(JSON.stringify(el));
|
||||
|
||||
|
||||
// Update element ID
|
||||
newEl.id = idMap.get(el.id)!;
|
||||
|
||||
// Remap Group IDs
|
||||
if (newEl.groupIds && Array.isArray(newEl.groupIds)) {
|
||||
newEl.groupIds = newEl.groupIds.map((groupId: string) => groupMap.get(groupId) || groupId);
|
||||
newEl.groupIds = newEl.groupIds.map(
|
||||
(groupId: string) => groupMap.get(groupId) || groupId,
|
||||
);
|
||||
}
|
||||
|
||||
// Remap Container ID (e.g., text inside a rectangle)
|
||||
@@ -4617,17 +4635,19 @@ export class ExcalidrawAutomate {
|
||||
|
||||
// Remap Bound Elements (e.g., the rectangle holding the text, or arrows attached to a shape)
|
||||
if (newEl.boundElements && Array.isArray(newEl.boundElements)) {
|
||||
newEl.boundElements = newEl.boundElements.map((bound: { id: string, type: string }) => ({
|
||||
...bound,
|
||||
id: idMap.get(bound.id) || bound.id // Fallback to original ID if bound element wasn't cloned
|
||||
}));
|
||||
newEl.boundElements = newEl.boundElements.map(
|
||||
(bound: { id: string; type: string }) => ({
|
||||
...bound,
|
||||
id: idMap.get(bound.id) || bound.id, // Fallback to original ID if bound element wasn't cloned
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Remap Arrow Start Binding
|
||||
if (newEl.startBinding && idMap.has(newEl.startBinding.elementId)) {
|
||||
newEl.startBinding = {
|
||||
...newEl.startBinding,
|
||||
elementId: idMap.get(newEl.startBinding.elementId)
|
||||
elementId: idMap.get(newEl.startBinding.elementId),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4635,7 +4655,7 @@ export class ExcalidrawAutomate {
|
||||
if (newEl.endBinding && idMap.has(newEl.endBinding.elementId)) {
|
||||
newEl.endBinding = {
|
||||
...newEl.endBinding,
|
||||
elementId: idMap.get(newEl.endBinding.elementId)
|
||||
elementId: idMap.get(newEl.endBinding.elementId),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4818,6 +4838,10 @@ export class ExcalidrawAutomate {
|
||||
getPolyBool(): typeof PolyBool {
|
||||
const defaultEpsilon = 0.0000000001;
|
||||
PolyBool.epsilon(defaultEpsilon);
|
||||
|
||||
if ("buildLog" in PolyBool) {
|
||||
PolyBool.buildLog(false);
|
||||
}
|
||||
return PolyBool;
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
import { isObsidianThemeDark } from "../utils/obsidianUtils";
|
||||
import { cleanBlockRef, cleanSectionHeading } from "../utils/pathUtils";
|
||||
import {
|
||||
ElementsMap,
|
||||
ExcalidrawElement,
|
||||
ExcalidrawImageElement,
|
||||
ExcalidrawTextElement,
|
||||
@@ -65,6 +66,7 @@ import { t } from "../lang/helpers";
|
||||
import { displayFontMessage } from "../utils/excalidrawViewUtils";
|
||||
import { getPDFRect } from "../utils/PDFUtils";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { errorlog } from "src/utils/coreUtils";
|
||||
|
||||
type SceneDataWithFiles = SceneData & { files: BinaryFiles };
|
||||
|
||||
@@ -268,7 +270,7 @@ export function getJSON(data: string): { scene: string; pos: number } {
|
||||
if (parts.value && parts.value.length > 1) {
|
||||
const result = parts.value[2];
|
||||
return {
|
||||
scene: result.substr(0, result.lastIndexOf("}") + 1),
|
||||
scene: result.substring(0, result.lastIndexOf("}") + 1),
|
||||
pos: parts.value.index,
|
||||
}; //this is a workaround in case sync merges two files together and one version is still an old version without the ```codeblock
|
||||
}
|
||||
@@ -568,16 +570,22 @@ export class ExcalidrawData {
|
||||
URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG,
|
||||
)[1] ?? "1.8.16";
|
||||
|
||||
const elements = this.scene.elements;
|
||||
const elements = this.scene.elements as Mutable<
|
||||
ExcalidrawElement & { boundElementIds?: string[] }
|
||||
>[];
|
||||
for (const el of elements) {
|
||||
if (el.type === "iframe" && !el.customData) {
|
||||
//@ts-ignore -- retyping in ExcalidrawData is possible, this is not the live inmutable object
|
||||
el.type = "embeddable";
|
||||
}
|
||||
|
||||
if (el.boundElements) {
|
||||
const map = new Map<string, string>();
|
||||
const map = new Map<string, "text" | "arrow">();
|
||||
let alreadyHasText: boolean = false;
|
||||
el.boundElements.forEach((item: { id: string; type: string }) => {
|
||||
if (item.type !== "text" && item.type !== "arrow") {
|
||||
return;
|
||||
}
|
||||
if (item.type === "text") {
|
||||
if (!alreadyHasText) {
|
||||
map.set(item.id, item.type);
|
||||
@@ -588,7 +596,9 @@ export class ExcalidrawData {
|
||||
);
|
||||
if (elementToClean) {
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1600
|
||||
elementToClean.containerId = null;
|
||||
if (elementToClean.type === "text") {
|
||||
elementToClean.containerId = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -631,27 +641,31 @@ export class ExcalidrawData {
|
||||
if (el.y === null) {
|
||||
el.y = 0;
|
||||
}
|
||||
/* FixedPointBinding type no longer has focus property. restoreElemenets should take care of this
|
||||
if (el.startBinding?.focus === null) {
|
||||
el.startBinding.focus = 0;
|
||||
}
|
||||
if (el.endBinding?.focus === null) {
|
||||
el.endBinding.focus = 0;
|
||||
}
|
||||
*/
|
||||
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/497
|
||||
if (el.fontSize === null) {
|
||||
if (el.type === "text" && el.fontSize === null) {
|
||||
el.fontSize = 20;
|
||||
}
|
||||
|
||||
if (el.type === "text" && !el.hasOwnProperty("autoResize")) {
|
||||
if (el.type === "text" && !Object.hasOwn(el ?? {}, "autoResize")) {
|
||||
el.autoResize = true;
|
||||
}
|
||||
|
||||
if (el.type === "text" && !el.hasOwnProperty("lineHeight")) {
|
||||
el.lineHeight = getLineHeight(el.fontFamily);
|
||||
if (el.type === "text" && !Object.hasOwn(el ?? {}, "lineHeight")) {
|
||||
el.lineHeight = getLineHeight(el.fontFamily) as number & {
|
||||
_brand: "unitlessLineHeight";
|
||||
};
|
||||
}
|
||||
|
||||
if (el.type === "image" && !el.hasOwnProperty("roundness")) {
|
||||
if (el.type === "image" && !Object.hasOwn(el ?? {}, "roundness")) {
|
||||
el.roundness = null;
|
||||
}
|
||||
}
|
||||
@@ -686,7 +700,7 @@ export class ExcalidrawData {
|
||||
container.id === textEl.containerId,
|
||||
)[0];
|
||||
const boundEl = container.boundElements.filter(
|
||||
(boundEl: { id: string; type: string }) =>
|
||||
(boundEl: { id: string; type: "text" | "arrow" }) =>
|
||||
!(
|
||||
boundEl.type === "text" &&
|
||||
!elements.some(
|
||||
@@ -694,10 +708,18 @@ export class ExcalidrawData {
|
||||
)
|
||||
),
|
||||
);
|
||||
container.boundElements = [{ id: textEl.id, type: "text" }].concat(
|
||||
boundEl,
|
||||
);
|
||||
} catch (_) {}
|
||||
container.boundElements = [
|
||||
{ id: textEl.id, type: "text" as "text" | "arrow" },
|
||||
].concat(boundEl);
|
||||
} catch (e) {
|
||||
errorlog({
|
||||
message: "unexpected error in initializeNonInitializedFields",
|
||||
context: this.initializeNonInitializedFields.bind(
|
||||
this,
|
||||
) as unknown,
|
||||
error: e as unknown,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -746,7 +768,9 @@ export class ExcalidrawData {
|
||||
.forEach((textEl: Mutable<ExcalidrawTextElement>) => {
|
||||
textEl.containerId = null;
|
||||
}); // log({message:"cleanup",textEl})});
|
||||
} catch {}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -854,7 +878,7 @@ export class ExcalidrawData {
|
||||
|
||||
const timer = window.setTimeout(() => {
|
||||
const notice = new Notice(t("FONT_LOAD_SLOW"), 15000);
|
||||
notice.noticeEl.oncontextmenu = () => {
|
||||
notice.messageEl.oncontextmenu = () => {
|
||||
displayFontMessage(this.app);
|
||||
};
|
||||
}, 5000);
|
||||
@@ -876,7 +900,7 @@ export class ExcalidrawData {
|
||||
}
|
||||
|
||||
//girdSize, gridStep, previousGridSize, gridModeEnabled migration
|
||||
if (this.scene.appState.hasOwnProperty("previousGridSize")) {
|
||||
if (Object.hasOwn(this.scene.appState ?? {}, "previousGridSize")) {
|
||||
//if previousGridSize was present this is legacy data
|
||||
if (this.scene.appState.gridSize === null) {
|
||||
this.scene.appState.gridSize = this.scene.appState.previousGridSize;
|
||||
@@ -887,7 +911,9 @@ export class ExcalidrawData {
|
||||
delete this.scene.appState.previousGridSize;
|
||||
}
|
||||
|
||||
if (this.scene.appState?.gridColor?.hasOwnProperty("MajorGridFrequency")) {
|
||||
if (
|
||||
Object.hasOwn(this.scene.appState?.gridColor ?? {}, "MajorGridFrequency")
|
||||
) {
|
||||
//if this is present, this is legacy data
|
||||
if (this.scene.appState.gridColor.MajorGridFrequency > 1) {
|
||||
this.scene.gridStep = this.scene.appState.gridColor.MajorGridFrequency;
|
||||
@@ -1165,7 +1191,7 @@ export class ExcalidrawData {
|
||||
private async updateSceneTextElements() {
|
||||
//update text in scene based on textElements Map
|
||||
//first get scene text elements
|
||||
const elementsMap = arrayToMap(this.scene.elements);
|
||||
const elementsMap = arrayToMap(this.scene.elements) as ElementsMap;
|
||||
const texts = this.scene.elements?.filter(
|
||||
(el: ExcalidrawElement) => el.type === "text" && !el.isDeleted,
|
||||
) as Mutable<ExcalidrawTextElement>[];
|
||||
@@ -1187,7 +1213,13 @@ export class ExcalidrawData {
|
||||
te.y = y;
|
||||
te.width = width;
|
||||
te.height = height;
|
||||
} catch (_e) {}
|
||||
} catch (error) {
|
||||
console.log(
|
||||
"error updating text element dimensions, likely due to element being deleted meanwhile",
|
||||
"updateSceneTextElements",
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+32
-11
@@ -1,12 +1,10 @@
|
||||
import { App, Notice, TFile } from "obsidian";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
import { PDFPageViewProps, Size } from "src/types/embeddedFileLoaderTypes";
|
||||
import { convertSVGStringToElement } from "../utils/utils";
|
||||
import { convertSVGStringToElement, errorlog } from "../utils/utils";
|
||||
import { FILENAMEPARTS, PreviewImageType } from "../types/utilTypes";
|
||||
import { hasExcalidrawEmbeddedImagesTreeChanged } from "../utils/fileUtils";
|
||||
const DB_NAME = `Excalidraw ${(app as unknown as { appId: string }).appId}`;
|
||||
const CACHE_STORE = "imageCache";
|
||||
const BACKUP_STORE = "drawingBAK";
|
||||
import { EXCALIDRAW_PLUGIN } from "src/constants/constants";
|
||||
|
||||
type FileCacheData = {
|
||||
mtime: number;
|
||||
@@ -276,14 +274,18 @@ class ImageCache {
|
||||
transaction.commit();
|
||||
resolve();
|
||||
})
|
||||
.catch((error) => reject(error));
|
||||
.catch((error) => reject(error as Error));
|
||||
}
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
const error = request.error;
|
||||
console.log(error);
|
||||
const errorMsg = `Failed to purge invalid files from IndexedDB. Error: ${error.message}`;
|
||||
errorlog({
|
||||
where: "purgeInvalideCacheFiles",
|
||||
error: error,
|
||||
message: errorMsg,
|
||||
});
|
||||
reject(new Error(errorMsg));
|
||||
};
|
||||
});
|
||||
@@ -321,14 +323,18 @@ class ImageCache {
|
||||
transaction.commit();
|
||||
resolve();
|
||||
})
|
||||
.catch((error) => reject(error));
|
||||
.catch((error) => reject(error as Error));
|
||||
}
|
||||
};
|
||||
|
||||
request.onerror = () => {
|
||||
const error = request.error;
|
||||
const errorMsg = `Failed to purge invalid backup files from IndexedDB. Error: ${error.message}`;
|
||||
console.log(error);
|
||||
errorlog({
|
||||
where: "purgeInvalidBackupFiles",
|
||||
error: error,
|
||||
message: errorMsg,
|
||||
});
|
||||
reject(new Error(errorMsg));
|
||||
};
|
||||
});
|
||||
@@ -402,7 +408,7 @@ class ImageCache {
|
||||
this.getCacheData(key),
|
||||
new Promise<undefined>((_, reject) =>
|
||||
window.setTimeout(() => {
|
||||
reject(undefined);
|
||||
reject(new Error("Timeout while retrieving cache data"));
|
||||
}, 100),
|
||||
),
|
||||
]);
|
||||
@@ -441,7 +447,12 @@ class ImageCache {
|
||||
}
|
||||
this.touchCacheData(key, cachedData);
|
||||
return { cacheData: cachedData, key };
|
||||
} catch (_) {
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"unexpected error in getResolvedCacheData",
|
||||
this.getResolvedCacheData.bind(this),
|
||||
error,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -601,4 +612,14 @@ class ImageCache {
|
||||
}
|
||||
}
|
||||
|
||||
export const imageCache = new ImageCache(DB_NAME, CACHE_STORE, BACKUP_STORE);
|
||||
let imageCache: ImageCache = null;
|
||||
|
||||
export const getImageCache = (): ImageCache => {
|
||||
if (!imageCache) {
|
||||
const DB_NAME = `Excalidraw ${EXCALIDRAW_PLUGIN.app.appId}`;
|
||||
const CACHE_STORE = "imageCache";
|
||||
const BACKUP_STORE = "drawingBAK";
|
||||
imageCache = new ImageCache(DB_NAME, CACHE_STORE, BACKUP_STORE);
|
||||
}
|
||||
return imageCache;
|
||||
};
|
||||
+38
-56
@@ -1,56 +1,10 @@
|
||||
// LaTeX.ts
|
||||
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { App } from "obsidian";
|
||||
import { TFile } from "obsidian";
|
||||
import ExcalidrawView from "../view/ExcalidrawView";
|
||||
import { FileData, MimeType } from "src/types/embeddedFileLoaderTypes";
|
||||
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import ExcalidrawPlugin from "src/core/main";
|
||||
|
||||
type MathJaxData = {
|
||||
mimeType: MimeType;
|
||||
fileId: FileId;
|
||||
dataURL: DataURL;
|
||||
created: number;
|
||||
size: { height: number; width: number };
|
||||
};
|
||||
|
||||
type MathJaxContext = App | ExcalidrawPlugin;
|
||||
|
||||
type MathJaxModule = {
|
||||
tex2dataURL: (
|
||||
tex: string,
|
||||
scale: number,
|
||||
pluginOrApp: MathJaxContext,
|
||||
) => Promise<MathJaxData>;
|
||||
clearMathJaxVariables: () => void;
|
||||
};
|
||||
|
||||
declare const loadMathjaxToSVG: () => Promise<MathJaxModule>;
|
||||
let mathjaxLoaded = false;
|
||||
let tex2dataURLExternal:
|
||||
| ((
|
||||
tex: string,
|
||||
scale: number,
|
||||
pluginOrApp: MathJaxContext,
|
||||
) => Promise<MathJaxData>)
|
||||
| null = null;
|
||||
let clearVariables: (() => void) | null = null;
|
||||
|
||||
let loadMathJaxPromise: Promise<void> | null = null;
|
||||
|
||||
const loadMathJax = async () => {
|
||||
if (!loadMathJaxPromise) {
|
||||
loadMathJaxPromise = (async () => {
|
||||
if (!mathjaxLoaded) {
|
||||
const module = await loadMathjaxToSVG();
|
||||
tex2dataURLExternal = module.tex2dataURL;
|
||||
clearVariables = module.clearMathJaxVariables;
|
||||
mathjaxLoaded = true;
|
||||
}
|
||||
})();
|
||||
}
|
||||
return loadMathJaxPromise;
|
||||
};
|
||||
import type { ExcalidrawExtrasAPI } from "@zsviczian/excalidraw-extras-api";
|
||||
|
||||
export const updateEquation = async (
|
||||
equation: string,
|
||||
@@ -58,8 +12,8 @@ export const updateEquation = async (
|
||||
view: ExcalidrawView,
|
||||
addFiles: (files: FileData[], view: ExcalidrawView) => void,
|
||||
) => {
|
||||
await loadMathJax();
|
||||
const data = await tex2dataURLExternal?.(equation, 4, view.app);
|
||||
// view.plugin gives us access to the gateway
|
||||
const data = await tex2dataURL(equation, 4, view.plugin);
|
||||
if (data) {
|
||||
const files: FileData[] = [];
|
||||
files.push({
|
||||
@@ -85,13 +39,41 @@ export async function tex2dataURL(
|
||||
dataURL: DataURL;
|
||||
created: number;
|
||||
size: { height: number; width: number };
|
||||
}> {
|
||||
await loadMathJax();
|
||||
return tex2dataURLExternal(tex, scale, plugin);
|
||||
} | null> {
|
||||
// 1. Ask the gateway to verify the Extras plugin and return the MathJax API
|
||||
const mathjaxAPI = await plugin.extrasGateway.getMathJax();
|
||||
|
||||
if (!mathjaxAPI) {
|
||||
// The Gateway handles the user prompts. If it returns null, the user cancelled,
|
||||
// or they don't have the plugin/proper version. We abort cleanly.
|
||||
return null;
|
||||
}
|
||||
|
||||
// 2. Resolve Preamble File using cachedRead for performance
|
||||
let preambleStr: string | null = null;
|
||||
const preamblePath = plugin.settings.latexPreambleLocation || "preamble.sty";
|
||||
const preambleFile = plugin.app.vault.getAbstractFileByPath(preamblePath);
|
||||
|
||||
if (preambleFile instanceof TFile) {
|
||||
preambleStr = await plugin.app.vault.cachedRead(preambleFile);
|
||||
}
|
||||
|
||||
// 3. Hand the request off to the cleanly isolated Extras plugin
|
||||
return (await mathjaxAPI.tex2dataURL(tex, scale, preambleStr)) as {
|
||||
mimeType: MimeType;
|
||||
fileId: FileId;
|
||||
dataURL: DataURL;
|
||||
created: number;
|
||||
size: { height: number; width: number };
|
||||
};
|
||||
}
|
||||
|
||||
export const clearMathJaxVariables = () => {
|
||||
if (clearVariables) {
|
||||
clearVariables();
|
||||
export const clearMathJaxVariables = (plugin: ExcalidrawPlugin) => {
|
||||
// Try to access without prompting the user.
|
||||
// If the plugin is disabled, we don't need to clear variables anyway.
|
||||
const api = plugin.app.plugins.plugins["excalidraw-extras"]
|
||||
?.api as ExcalidrawExtrasAPI;
|
||||
if (api?.mathjax) {
|
||||
api.mathjax.clearMathJaxVariables();
|
||||
}
|
||||
};
|
||||
@@ -424,7 +424,12 @@ export class ScriptEngine {
|
||||
hint,
|
||||
instructions,
|
||||
);
|
||||
} catch (_) {
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"unexpected error in suggester",
|
||||
this.suggester.bind(this),
|
||||
error,
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
IMAGE_TYPES,
|
||||
VIDEO_TYPES,
|
||||
} from "src/constants/constants";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
|
||||
export class FileSuggestionModal extends SuggestionModal<LinkSuggestion> {
|
||||
text: TextComponent;
|
||||
@@ -49,8 +50,10 @@ export class FileSuggestionModal extends SuggestionModal<LinkSuggestion> {
|
||||
this.limit = 20;
|
||||
this.filesAndAliases = filesAndAliases;
|
||||
this.text = input;
|
||||
this.suggestEl.style.maxWidth = "100%";
|
||||
this.suggestEl.style.width = `${input.inputEl.clientWidth}px`;
|
||||
setStyle(this.suggestEl, {
|
||||
maxWidth: "100%",
|
||||
width: `${input.inputEl.clientWidth}px`,
|
||||
});
|
||||
|
||||
// Pre-bind the handler
|
||||
this.handleGetFile = this.getFile.bind(this);
|
||||
@@ -104,9 +107,6 @@ export class FileSuggestionModal extends SuggestionModal<LinkSuggestion> {
|
||||
const titleEl = contentEl.createDiv("suggestion-title");
|
||||
const noteEl = contentEl.createDiv("suggestion-note");
|
||||
|
||||
//el.style.flexDirection = "column";
|
||||
//content.style.flexDirection = "initial";
|
||||
|
||||
if (!item) {
|
||||
titleEl.setText(this.emptyStateText);
|
||||
itemEl.addClass("is-selected");
|
||||
|
||||
@@ -14,8 +14,8 @@ import {
|
||||
import { KeyBlocker } from "src/types/excalidrawAutomateTypes";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { nanoid } from "src/constants/constants";
|
||||
import { sleep } from "src/utils/utils";
|
||||
import { getEA } from "src/core";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
|
||||
type HeadingSuggestion = {
|
||||
kind: "heading";
|
||||
@@ -163,9 +163,11 @@ export class InlineLinkSuggester
|
||||
const width = hostRect?.width ?? this.widthHost?.clientWidth;
|
||||
|
||||
if (width && this.hasCustomWidthHost) {
|
||||
this.suggestEl.style.width = `${width}px`;
|
||||
this.suggestEl.style.maxWidth = `${width}px`;
|
||||
this.suggestEl.style.minWidth = `${width}px`;
|
||||
setStyle(this.suggestEl, {
|
||||
width: `${width}px`,
|
||||
maxWidth: `${width}px`,
|
||||
minWidth: `${width}px`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -192,10 +194,11 @@ export class InlineLinkSuggester
|
||||
}
|
||||
|
||||
const clampedMinWidth = Math.min(minWidth, availableWidth);
|
||||
|
||||
this.suggestEl.style.width = "";
|
||||
this.suggestEl.style.minWidth = `${clampedMinWidth}px`;
|
||||
this.suggestEl.style.maxWidth = `${availableWidth}px`;
|
||||
setStyle(this.suggestEl, {
|
||||
width: "",
|
||||
minWidth: `${clampedMinWidth}px`,
|
||||
maxWidth: `${availableWidth}px`,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -209,7 +212,7 @@ export class InlineLinkSuggester
|
||||
return input;
|
||||
}
|
||||
|
||||
async onInputChanged(): Promise<void> {
|
||||
onInputChanged(): void {
|
||||
const inputStr = this.modifyInput(this.inputEl.value);
|
||||
this.caretPos = this.inputEl.selectionStart ?? inputStr.length;
|
||||
|
||||
@@ -245,21 +248,23 @@ export class InlineLinkSuggester
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.mode === "heading") {
|
||||
await this.loadHeadings(this.activeFile);
|
||||
} else if (this.mode === "block") {
|
||||
await this.loadParagraphs(this.activeFile);
|
||||
} else if (this.mode === "frame" || this.mode === "clippedframe") {
|
||||
await this.loadFrames(this.activeFile, this.mode);
|
||||
} else {
|
||||
this.headingItems = [];
|
||||
this.paragraphItems = [];
|
||||
this.frameItems = [];
|
||||
}
|
||||
void (async () => {
|
||||
if (this.mode === "heading") {
|
||||
await this.loadHeadings(this.activeFile);
|
||||
} else if (this.mode === "block") {
|
||||
await this.loadParagraphs(this.activeFile);
|
||||
} else if (this.mode === "frame" || this.mode === "clippedframe") {
|
||||
await this.loadFrames(this.activeFile, this.mode);
|
||||
} else {
|
||||
this.headingItems = [];
|
||||
this.paragraphItems = [];
|
||||
this.frameItems = [];
|
||||
}
|
||||
|
||||
this.tagItems = [];
|
||||
this.block = true;
|
||||
super.onInputChanged();
|
||||
this.tagItems = [];
|
||||
this.block = true;
|
||||
super.onInputChanged();
|
||||
})();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -283,7 +288,7 @@ export class InlineLinkSuggester
|
||||
this.tagItems = this.getTagSuggestions();
|
||||
|
||||
this.block = true;
|
||||
await super.onInputChanged();
|
||||
super.onInputChanged();
|
||||
}
|
||||
|
||||
private getTagSuggestions(): TagSuggestion[] {
|
||||
@@ -382,7 +387,7 @@ export class InlineLinkSuggester
|
||||
return item.path + (item.alias ? `|${item.alias}` : "");
|
||||
}
|
||||
|
||||
async onChooseItem(item: InlineSuggestion | undefined): Promise<void> {
|
||||
onChooseItem(item: InlineSuggestion | undefined): void {
|
||||
if (!item) {
|
||||
return;
|
||||
}
|
||||
@@ -405,18 +410,20 @@ export class InlineLinkSuggester
|
||||
}
|
||||
|
||||
if (this.isParagraph(item)) {
|
||||
const id = await this.ensureParagraphHasId(item);
|
||||
if (!id) {
|
||||
return;
|
||||
}
|
||||
const linktext = this.app.metadataCache.fileToLinktext(
|
||||
item.file,
|
||||
this.getSourcePath() ?? "",
|
||||
true,
|
||||
);
|
||||
const aliasSuffix =
|
||||
this.activeAlias !== null ? `|${this.activeAlias}` : "";
|
||||
this.insertLink(`[[${linktext}#^${id}${aliasSuffix}]]`);
|
||||
void (async () => {
|
||||
const id = await this.ensureParagraphHasId(item);
|
||||
if (!id) {
|
||||
return;
|
||||
}
|
||||
const linktext = this.app.metadataCache.fileToLinktext(
|
||||
item.file,
|
||||
this.getSourcePath() ?? "",
|
||||
true,
|
||||
);
|
||||
const aliasSuffix =
|
||||
this.activeAlias !== null ? `|${this.activeAlias}` : "";
|
||||
this.insertLink(`[[${linktext}#^${id}${aliasSuffix}]]`);
|
||||
})();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -438,19 +445,19 @@ export class InlineLinkSuggester
|
||||
this.insertLink(linkString);
|
||||
}
|
||||
|
||||
async selectSuggestion(
|
||||
selectSuggestion(
|
||||
value: FuzzyMatch<InlineSuggestion>,
|
||||
evt: MouseEvent | KeyboardEvent,
|
||||
) {
|
||||
evt?.preventDefault?.();
|
||||
evt?.stopPropagation?.();
|
||||
await this.onChooseItem(value?.item);
|
||||
void this.onChooseItem(value?.item);
|
||||
}
|
||||
|
||||
open(): void {
|
||||
this.block = true;
|
||||
this.syncWidth();
|
||||
this.suggestEl.style.pointerEvents = "all";
|
||||
setStyle(this.suggestEl, { pointerEvents: "all" });
|
||||
super.open();
|
||||
}
|
||||
|
||||
|
||||
@@ -119,7 +119,12 @@ function canCreateWorkerFromBlob() {
|
||||
worker.terminate();
|
||||
URL.revokeObjectURL(url);
|
||||
IS_WORKER_SUPPORTED = true;
|
||||
} catch (_) {
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"unexpected error in canCreateWorkerFromBlob",
|
||||
canCreateWorkerFromBlob,
|
||||
error,
|
||||
);
|
||||
IS_WORKER_SUPPORTED = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ import { t } from "src/lang/helpers";
|
||||
import { escapeRegExp } from "../../utils/utils";
|
||||
import { htmlToMarkdown, Notice, setIcon } from "obsidian";
|
||||
import { mainDocument } from "src/constants/constants";
|
||||
import { setStyle } from "src/utils/styleUtils";
|
||||
import { isInstanceOfHTMLElement } from "src/utils/typechecks";
|
||||
|
||||
export class ContentSearcher {
|
||||
private contentDiv: HTMLElement;
|
||||
@@ -114,7 +116,7 @@ export class ContentSearcher {
|
||||
|
||||
const childNodes = Array.from(exportContent.childNodes);
|
||||
const startIndex = childNodes.findIndex(
|
||||
(node) => node instanceof HTMLElement && node.tagName === "HR",
|
||||
(node) => isInstanceOfHTMLElement(node) && node.tagName === "HR",
|
||||
);
|
||||
const nodesToExport =
|
||||
startIndex > -1 ? childNodes.slice(startIndex) : childNodes;
|
||||
@@ -152,22 +154,22 @@ export class ContentSearcher {
|
||||
};
|
||||
this.showHideButton.onclick = () => {
|
||||
const setOpacity = (value: string | null) => {
|
||||
this.inputContainer.style.opacity = value;
|
||||
this.prevButton.style.opacity = value;
|
||||
this.nextButton.style.opacity = value;
|
||||
this.exportMarkdown.style.opacity = value;
|
||||
this.customElemenentContainer.style.opacity = value;
|
||||
setStyle(this.inputContainer, { opacity: value });
|
||||
setStyle(this.prevButton, { opacity: value });
|
||||
setStyle(this.nextButton, { opacity: value });
|
||||
setStyle(this.exportMarkdown, { opacity: value });
|
||||
setStyle(this.customElemenentContainer, { opacity: value });
|
||||
};
|
||||
if (this.showHideButton.hasClass("search-visible")) {
|
||||
this.showHideButton.removeClass("search-visible");
|
||||
this.showHideButton.addClass("search-hidden");
|
||||
this.searchBarWrapper.style.backgroundColor = "transparent";
|
||||
setStyle(this.searchBarWrapper, { backgroundColor: "transparent" });
|
||||
setOpacity("0");
|
||||
setIcon(this.showHideButton, "maximize-2");
|
||||
} else {
|
||||
this.showHideButton.removeClass("search-hidden");
|
||||
this.showHideButton.addClass("search-visible");
|
||||
this.searchBarWrapper.style.backgroundColor = null;
|
||||
setStyle(this.searchBarWrapper, { backgroundColor: null });
|
||||
setOpacity(null);
|
||||
setIcon(this.showHideButton, "minimize-2");
|
||||
}
|
||||
@@ -299,7 +301,7 @@ export class ContentSearcher {
|
||||
|
||||
if (currentActiveIndex !== -1) {
|
||||
highlights[currentActiveIndex].classList.remove("active-highlight");
|
||||
highlights[currentActiveIndex].style.border = "none";
|
||||
setStyle(highlights[currentActiveIndex], { border: "none" });
|
||||
}
|
||||
|
||||
let nextActiveIndex = 0;
|
||||
@@ -389,8 +391,9 @@ export class ContentSearcher {
|
||||
parent = parent.parentElement;
|
||||
}
|
||||
|
||||
return mainDocument.scrollingElement instanceof HTMLElement
|
||||
? mainDocument.scrollingElement
|
||||
: null;
|
||||
if (isInstanceOfHTMLElement(mainDocument.scrollingElement)) {
|
||||
return mainDocument.scrollingElement;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -115,17 +115,24 @@ export const findArc = (
|
||||
const arc = [];
|
||||
const step = sweep ? -1 : 1;
|
||||
|
||||
for (let i = indexDest; true; i += step) {
|
||||
arc.push(points[i]);
|
||||
let i = indexDest;
|
||||
|
||||
if (i === indexCur) {
|
||||
break;
|
||||
}
|
||||
// Checking if indices exist prevents runtime crashes
|
||||
if (indexCur !== -1 && indexDest !== -1) {
|
||||
while (i >= -1 && i <= points.length) {
|
||||
arc.push(points[i]);
|
||||
|
||||
if (sweep && i === 0) {
|
||||
i = points.length;
|
||||
} else if (!sweep && i === points.length - 1) {
|
||||
i = -1;
|
||||
if (i === indexCur) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (sweep && i === 0) {
|
||||
i = points.length;
|
||||
} else if (!sweep && i === points.length - 1) {
|
||||
i = -1;
|
||||
} else {
|
||||
i += step;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -381,7 +381,7 @@ const walkers = {
|
||||
let localGroup = randomId();
|
||||
|
||||
switch (fillRule) {
|
||||
case "nonzero":
|
||||
case "nonzero": {
|
||||
let initialWindingOrder = "clockwise";
|
||||
|
||||
elements = points.map((pointArr, idx): ExcalidrawDraw => {
|
||||
@@ -421,6 +421,7 @@ const walkers = {
|
||||
};
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "evenodd":
|
||||
elements = points.map((pointArr, idx): ExcalidrawDraw => {
|
||||
const tPoints: Point[] = transformPoints(pointArr, mat4.clone(mat));
|
||||
|
||||
Vendored
-1
@@ -23,7 +23,6 @@ import {
|
||||
AppState,
|
||||
BinaryFiles,
|
||||
DataURL,
|
||||
GenerateDiagramToCode,
|
||||
Zoom,
|
||||
} from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
|
||||
@@ -4,7 +4,6 @@ import { ViewStateResult, WorkspaceLeaf } from "obsidian";
|
||||
import {
|
||||
AppState,
|
||||
BinaryFiles,
|
||||
ExcalidrawInitialDataState,
|
||||
ExcalidrawProps,
|
||||
LibraryItems,
|
||||
SceneData,
|
||||
@@ -50,10 +49,6 @@ export type ExcalidrawViewScene = Omit<
|
||||
files: BinaryFiles;
|
||||
};
|
||||
|
||||
export type ExcalidrawViewInitialData = ExcalidrawInitialDataState & {
|
||||
libraryItems?: LibraryItems;
|
||||
};
|
||||
|
||||
export type ExcalidrawViewAppState = Omit<
|
||||
Partial<AppState>,
|
||||
"showHyperlinkPopup"
|
||||
|
||||
@@ -64,3 +64,67 @@ export interface ExportSettings {
|
||||
frameRendering?: FrameRenderingOptions; //optional, overrides relevant appState settings for rendering the frame
|
||||
skipInliningFonts?: boolean;
|
||||
}
|
||||
|
||||
// Electron IPC interfaces
|
||||
export interface PrintToPDFOptions {
|
||||
includeName: boolean;
|
||||
pageSize: string | { width: number; height: number };
|
||||
landscape: boolean;
|
||||
margins: { top: number; left: number; right: number; bottom: number };
|
||||
scaleFactor: number;
|
||||
scale: number;
|
||||
open: boolean;
|
||||
filepath: string;
|
||||
// Prefer CSS @page size over the numeric pageSize for mixed-size documents
|
||||
preferCSSPageSize?: boolean;
|
||||
// Exclude page ranges from output (Chromium/Electron supports either string "2-" or array)
|
||||
pageRanges?: string | { from: number; to: number }[];
|
||||
}
|
||||
|
||||
export interface SaveDialogOptions {
|
||||
defaultPath: string;
|
||||
filters: { name: string; extensions: string[] }[];
|
||||
properties: string[];
|
||||
}
|
||||
|
||||
export interface SaveDialogReturnValue {
|
||||
canceled: boolean;
|
||||
filePath?: string;
|
||||
}
|
||||
|
||||
type CaptureRect = {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
type NativeImageLike = {
|
||||
toPNG(): Uint8Array | Buffer;
|
||||
};
|
||||
|
||||
interface ElectronWebContentsLike {
|
||||
capturePage(rect: CaptureRect): Promise<NativeImageLike>;
|
||||
getZoomFactor(): number;
|
||||
setZoomFactor(factor: number): void;
|
||||
}
|
||||
|
||||
interface ElectronWebUtilsLike {
|
||||
getPathForFile(file: File): string;
|
||||
}
|
||||
|
||||
export interface ElectronAPI {
|
||||
ipcRenderer: {
|
||||
send(channel: string, ...args: unknown[]): void;
|
||||
once(channel: string, func: (...args: unknown[]) => void): void;
|
||||
};
|
||||
remote: {
|
||||
dialog: {
|
||||
showSaveDialog(
|
||||
options: SaveDialogOptions,
|
||||
): Promise<SaveDialogReturnValue>;
|
||||
};
|
||||
getCurrentWebContents(): ElectronWebContentsLike;
|
||||
};
|
||||
webUtils: ElectronWebUtilsLike;
|
||||
}
|
||||
Vendored
+1
@@ -1,6 +1,7 @@
|
||||
declare module "polybooljs" {
|
||||
interface PolyBoolStatic {
|
||||
epsilon(value: number): void;
|
||||
buildLog(value: boolean): void;
|
||||
}
|
||||
|
||||
const PolyBool: PolyBoolStatic;
|
||||
|
||||
Vendored
+7
-10
@@ -106,7 +106,7 @@ export type ObsidianCommandManager = {
|
||||
};
|
||||
|
||||
export type ObsidianDraggable = {
|
||||
type?: "file" | "files" | "link" | string;
|
||||
type?: "file" | "files" | "link" | "text" | "unknown";
|
||||
file?: TFile;
|
||||
files?: TFile[];
|
||||
title?: string;
|
||||
@@ -158,20 +158,16 @@ export type LocalGraphView = View & {
|
||||
};
|
||||
|
||||
declare global {
|
||||
const LZString: {
|
||||
compressToBase64: (value: string) => string;
|
||||
decompressFromBase64: (value: string) => string | null;
|
||||
};
|
||||
|
||||
interface Window {
|
||||
ExcalidrawAutomate: ExcalidrawAutomate;
|
||||
pdfjsLib: PdfJsLibrary;
|
||||
unpackBase64Deflate?: (value: string) => string;
|
||||
PolyBool?: PolyBoolLibrary;
|
||||
electronWindow?: {
|
||||
isAlwaysOnTop(): boolean;
|
||||
setAlwaysOnTop(flag: boolean): void;
|
||||
};
|
||||
eval: typeof window.eval;
|
||||
eval: (x: string) => unknown;
|
||||
React?: typeof import("react");
|
||||
ReactDOM?: typeof import("react-dom/client");
|
||||
ExcalidrawLib?: typeof ExcalidrawLib;
|
||||
@@ -196,9 +192,10 @@ declare module "obsidian" {
|
||||
setType(name: string, type: string): void;
|
||||
};
|
||||
plugins: {
|
||||
plugins: {
|
||||
[key: string]: Plugin | undefined;
|
||||
};
|
||||
manifests: Record<string, PluginManifest>;
|
||||
plugins: Record<string, (Plugin & { api?: unknown }) | undefined>;
|
||||
enablePlugin(id: string): Promise<void>;
|
||||
disablePlugin(id: string): Promise<void>;
|
||||
};
|
||||
}
|
||||
interface FileManager {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { TFile } from "obsidian";
|
||||
|
||||
export type FILENAMEPARTS = {
|
||||
filepath: string;
|
||||
hasBlockref: boolean;
|
||||
@@ -32,3 +34,25 @@ export type PaneTarget =
|
||||
| "popout-window"
|
||||
| "new-tab"
|
||||
| "md-properties";
|
||||
|
||||
export interface NestedFileNode {
|
||||
file: TFile;
|
||||
/**
|
||||
* All distinct dependency paths from the root file down to this embedded file.
|
||||
* Each path is an ordered array of TFile objects starting with the `rootFile` at index 0.
|
||||
*
|
||||
* @example
|
||||
* If Root -> A -> B2.2 and Root -> B -> B2 -> B2.2
|
||||
* The paths for B2.2 will be:
|
||||
* [
|
||||
* [Root, A, B2.2],
|
||||
* [Root, B, B2, B2.2]
|
||||
* ]
|
||||
*
|
||||
* Usage: To find which top-level embeds to reload if this file changes,
|
||||
* you can map over `paths` and collect `path[1]`.
|
||||
*/
|
||||
paths: TFile[][];
|
||||
}
|
||||
|
||||
export type NestedFileMap = Map<TFile, NestedFileNode>;
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
ExcalidrawAISettings,
|
||||
AIFileInput,
|
||||
AIImageInput,
|
||||
AIModelConfig,
|
||||
AIProvider,
|
||||
AIProviderProfile,
|
||||
AIRequest,
|
||||
@@ -31,6 +30,7 @@ import {
|
||||
getGeminiImageRequestConfig,
|
||||
getGeminiSupportedSizes,
|
||||
} from "src/utils/geminiImageModelUtils";
|
||||
import { strictArrayBuffer } from "./obsidianUtils";
|
||||
|
||||
type NormalizedBinaryInput = {
|
||||
source: string;
|
||||
@@ -1769,12 +1769,15 @@ const buildMultipartFormBody = (
|
||||
|
||||
chunks.push(encoder.encode(`--${boundary}--\r\n`));
|
||||
const combined = concatUint8Arrays(chunks);
|
||||
|
||||
return {
|
||||
contentType: `multipart/form-data; boundary=${boundary}`,
|
||||
body: combined.buffer.slice(
|
||||
combined.byteOffset,
|
||||
combined.byteOffset + combined.byteLength,
|
||||
) as ArrayBuffer,
|
||||
body: strictArrayBuffer(
|
||||
combined.buffer.slice(
|
||||
combined.byteOffset,
|
||||
combined.byteOffset + combined.byteLength,
|
||||
),
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
import { App, Modal, Notice, Setting } from "obsidian";
|
||||
import type ExcalidrawPlugin from "../core/main";
|
||||
import type {
|
||||
ExcalidrawExtrasAPI,
|
||||
ExtrasComponent,
|
||||
} from "@zsviczian/excalidraw-extras-api";
|
||||
import { t } from "../lang/helpers";
|
||||
import en from "src/lang/locale/en";
|
||||
|
||||
const EXTRAS_PLUGIN_ID = "excalidraw-extras";
|
||||
|
||||
const REQUIRED_EXTRAS_VERSIONS: Record<
|
||||
string,
|
||||
{ min?: string; exact?: string }
|
||||
> = {
|
||||
plugin: { min: "0.0.14" },
|
||||
mathjax: { min: "1.0.0" },
|
||||
mermaid: { exact: "2.2.2" },
|
||||
pdf: { min: "1.0.0" },
|
||||
filesystem: { min: "1.0.0" },
|
||||
};
|
||||
|
||||
type ActionResolution = "success" | "ignore" | "cancel";
|
||||
|
||||
export type VersionCheckResult = {
|
||||
valid: boolean;
|
||||
isExact?: boolean;
|
||||
compName?: string;
|
||||
reqVersion?: string;
|
||||
currentVersion?: string;
|
||||
};
|
||||
|
||||
export class ExcalidrawExtrasGateway {
|
||||
private ignoredComponents: Set<string> = new Set();
|
||||
private activationTask: Promise<ActionResolution> | null = null;
|
||||
|
||||
constructor(
|
||||
public app: App,
|
||||
public plugin: ExcalidrawPlugin,
|
||||
) {}
|
||||
|
||||
public async getMathJax(): Promise<ExcalidrawExtrasAPI["mathjax"] | null> {
|
||||
const api = await this.ensureActiveAndGetAPI("mathjax");
|
||||
return api ? api.mathjax : null;
|
||||
}
|
||||
|
||||
public async getExportToPDF(): Promise<ExcalidrawExtrasAPI["pdf"] | null> {
|
||||
const api = await this.ensureActiveAndGetAPI("pdf");
|
||||
return api ? api.pdf : null;
|
||||
}
|
||||
|
||||
public async getMermaid(): Promise<ExcalidrawExtrasAPI["mermaid"] | null> {
|
||||
const api = await this.ensureActiveAndGetAPI("mermaid");
|
||||
return api ? api.mermaid : null;
|
||||
}
|
||||
|
||||
public async getFileSystem(): Promise<
|
||||
ExcalidrawExtrasAPI["filesystem"] | null
|
||||
> {
|
||||
const api = await this.ensureActiveAndGetAPI("filesystem");
|
||||
return api ? api.filesystem : null;
|
||||
}
|
||||
|
||||
private async ensureActiveAndGetAPI(
|
||||
component: ExtrasComponent,
|
||||
): Promise<ExcalidrawExtrasAPI | null> {
|
||||
if (this.ignoredComponents.has(component)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (this.activationTask === null) {
|
||||
this.activationTask = (async () => {
|
||||
try {
|
||||
return await this.handleActivation(component);
|
||||
} finally {
|
||||
this.activationTask = null;
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
const resolution = await this.activationTask;
|
||||
|
||||
if (resolution === "ignore") {
|
||||
this.ignoredComponents.add(component);
|
||||
return null;
|
||||
}
|
||||
if (resolution === "cancel") {
|
||||
return null;
|
||||
}
|
||||
|
||||
// At this point, we assume "success", retrieve API and verify versions
|
||||
const api = this.getAPI();
|
||||
if (!api) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!this.checkVersion(component, api).valid) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return api;
|
||||
}
|
||||
|
||||
private async handleActivation(
|
||||
component: ExtrasComponent,
|
||||
): Promise<ActionResolution> {
|
||||
// If everything is already perfect, return success immediately
|
||||
if (this.isInstalled() && this.isPluginEnabled()) {
|
||||
const api = this.getAPI();
|
||||
// Added version check to the success path so it opens the modal if an update is needed
|
||||
if (
|
||||
api &&
|
||||
api.features.isActive(component) &&
|
||||
this.checkVersion(component, api).valid
|
||||
) {
|
||||
return "success";
|
||||
}
|
||||
}
|
||||
|
||||
// Otherwise, open the progressive modal
|
||||
return new Promise((resolve) => {
|
||||
const modal = new ExtrasActivationModal(
|
||||
this.app,
|
||||
component,
|
||||
this,
|
||||
resolve,
|
||||
);
|
||||
modal.open();
|
||||
});
|
||||
}
|
||||
|
||||
public isInstalled(): boolean {
|
||||
return !!this.app.plugins.manifests[EXTRAS_PLUGIN_ID];
|
||||
}
|
||||
|
||||
public isPluginEnabled(): boolean {
|
||||
return !!this.app.plugins.plugins[EXTRAS_PLUGIN_ID];
|
||||
}
|
||||
|
||||
public getAPI(): ExcalidrawExtrasAPI | null {
|
||||
return (
|
||||
(this.app.plugins.plugins[EXTRAS_PLUGIN_ID]
|
||||
?.api as ExcalidrawExtrasAPI) || null
|
||||
);
|
||||
}
|
||||
|
||||
public checkVersion(
|
||||
component: string,
|
||||
api: ExcalidrawExtrasAPI,
|
||||
): VersionCheckResult {
|
||||
// 1. Check overall plugin version first
|
||||
const pluginReq = REQUIRED_EXTRAS_VERSIONS.plugin;
|
||||
if (pluginReq) {
|
||||
const manifest = this.app.plugins.manifests[EXTRAS_PLUGIN_ID];
|
||||
const pluginVersion = manifest?.version || "0.0.0";
|
||||
const pluginCompName = t("EXTRAS_GATEWAY_COMP_PLUGIN");
|
||||
|
||||
if (pluginReq.exact && pluginVersion !== pluginReq.exact) {
|
||||
return {
|
||||
valid: false,
|
||||
isExact: true,
|
||||
compName: pluginCompName,
|
||||
reqVersion: pluginReq.exact,
|
||||
currentVersion: pluginVersion,
|
||||
};
|
||||
}
|
||||
if (
|
||||
pluginReq.min &&
|
||||
this.compareVersions(pluginVersion, pluginReq.min) < 0
|
||||
) {
|
||||
return {
|
||||
valid: false,
|
||||
isExact: false,
|
||||
compName: pluginCompName,
|
||||
reqVersion: pluginReq.min,
|
||||
currentVersion: pluginVersion,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Check specific component version
|
||||
const currentVersion = api.versions[component as keyof typeof api.versions];
|
||||
const req = REQUIRED_EXTRAS_VERSIONS[component];
|
||||
if (!req) {
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
const compName = t(
|
||||
`EXTRAS_GATEWAY_COMP_${component.toUpperCase()}` as keyof typeof en,
|
||||
);
|
||||
|
||||
if (req.exact && currentVersion !== req.exact) {
|
||||
return {
|
||||
valid: false,
|
||||
isExact: true,
|
||||
compName,
|
||||
reqVersion: req.exact,
|
||||
currentVersion,
|
||||
};
|
||||
}
|
||||
if (req.min && this.compareVersions(currentVersion, req.min) < 0) {
|
||||
return {
|
||||
valid: false,
|
||||
isExact: false,
|
||||
compName,
|
||||
reqVersion: req.min,
|
||||
currentVersion,
|
||||
};
|
||||
}
|
||||
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
public async enableFeature(
|
||||
component: ExtrasComponent,
|
||||
api: ExcalidrawExtrasAPI,
|
||||
minutes: number = 0,
|
||||
) {
|
||||
await api.features.enable(component, minutes);
|
||||
}
|
||||
|
||||
private compareVersions(v1: string, v2: string): number {
|
||||
const a = v1.split(".").map(Number);
|
||||
const b = v2.split(".").map(Number);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
if ((a[i] || 0) > (b[i] || 0)) {
|
||||
return 1;
|
||||
}
|
||||
if ((a[i] || 0) < (b[i] || 0)) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A progressive state-machine modal that evaluates the environment at each render
|
||||
* and advances when prerequisites are satisfied.
|
||||
*/
|
||||
class ExtrasActivationModal extends Modal {
|
||||
private hasResolved = false;
|
||||
|
||||
constructor(
|
||||
app: App,
|
||||
private component: ExtrasComponent,
|
||||
private gateway: ExcalidrawExtrasGateway,
|
||||
private resolvePromise: (value: ActionResolution) => void,
|
||||
) {
|
||||
super(app);
|
||||
}
|
||||
|
||||
onOpen() {
|
||||
void this.renderStep();
|
||||
}
|
||||
|
||||
async renderStep() {
|
||||
const { contentEl } = this;
|
||||
contentEl.empty();
|
||||
|
||||
const compName = t(
|
||||
`EXTRAS_GATEWAY_COMP_${this.component.toUpperCase()}` as keyof typeof en,
|
||||
);
|
||||
|
||||
// Step 1: Install Plugin
|
||||
if (!this.gateway.isInstalled()) {
|
||||
contentEl.createEl("h2", { text: t("EXTRAS_GATEWAY_TITLE") });
|
||||
contentEl.createEl("p", {
|
||||
text: t("EXTRAS_GATEWAY_DESC").replace("{component}", compName),
|
||||
});
|
||||
|
||||
this.addControls(
|
||||
contentEl,
|
||||
() => {
|
||||
window.open(`obsidian://show-plugin?id=${EXTRAS_PLUGIN_ID}`);
|
||||
this.resolveAndClose("cancel");
|
||||
},
|
||||
t("EXTRAS_GATEWAY_INSTALL_BTN"),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 2: Plugin installed but disabled
|
||||
if (this.gateway.isInstalled() && !this.gateway.isPluginEnabled()) {
|
||||
contentEl.createEl("h2", { text: t("EXTRAS_GATEWAY_TITLE") });
|
||||
contentEl.createEl("p", {
|
||||
text: t("EXTRAS_GATEWAY_DESC").replace("{component}", compName),
|
||||
});
|
||||
contentEl.createEl("p", {
|
||||
text: t("EXTRAS_GATEWAY_MANUAL_ENABLE_NOTICE"),
|
||||
});
|
||||
|
||||
new Setting(contentEl)
|
||||
.addButton((btn) =>
|
||||
btn
|
||||
.setButtonText(t("EXTRAS_GATEWAY_UPDATE_BTN"))
|
||||
.setCta()
|
||||
.onClick(() => {
|
||||
this.resolveAndClose("cancel");
|
||||
window.setTimeout(() => {
|
||||
window.open(`obsidian://show-plugin?id=${EXTRAS_PLUGIN_ID}`);
|
||||
}, 50);
|
||||
}),
|
||||
)
|
||||
.addButton((btn) =>
|
||||
btn
|
||||
.setButtonText(t("BACKUP_CANCEL"))
|
||||
.onClick(() => this.resolveAndClose("cancel")),
|
||||
)
|
||||
.addButton((btn) =>
|
||||
btn
|
||||
.setButtonText(t("EXTRAS_GATEWAY_IGNORE_SESSION"))
|
||||
.setWarning()
|
||||
.onClick(() => this.resolveAndClose("ignore")),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 3: API & Version Checks
|
||||
const api = this.gateway.getAPI();
|
||||
if (!api) {
|
||||
new Notice(t("EXTRAS_GATEWAY_API_MISSING"));
|
||||
this.resolveAndClose("cancel");
|
||||
return;
|
||||
}
|
||||
|
||||
const versionCheck = this.gateway.checkVersion(this.component, api);
|
||||
if (!versionCheck.valid) {
|
||||
contentEl.createEl("h2", { text: t("EXTRAS_GATEWAY_UPDATE_TITLE") });
|
||||
|
||||
const msg = t(
|
||||
versionCheck.isExact
|
||||
? "EXTRAS_GATEWAY_UPDATE_EXACT"
|
||||
: "EXTRAS_GATEWAY_UPDATE_MIN",
|
||||
)
|
||||
.replace("{component}", versionCheck.compName)
|
||||
.replace("{reqVersion}", versionCheck.reqVersion)
|
||||
.replace("{currentVersion}", versionCheck.currentVersion);
|
||||
|
||||
contentEl.createEl("p", { text: msg });
|
||||
|
||||
new Setting(contentEl)
|
||||
.addButton((btn) =>
|
||||
btn
|
||||
.setButtonText(t("EXTRAS_GATEWAY_UPDATE_BTN"))
|
||||
.setCta()
|
||||
.onClick(() => {
|
||||
this.resolveAndClose("cancel");
|
||||
window.setTimeout(() => {
|
||||
window.open(`obsidian://show-plugin?id=${EXTRAS_PLUGIN_ID}`);
|
||||
}, 50);
|
||||
}),
|
||||
)
|
||||
.addButton((btn) =>
|
||||
btn
|
||||
.setButtonText(t("BACKUP_CANCEL"))
|
||||
.onClick(() => this.resolveAndClose("cancel")),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 4: Enable Specific Feature Setting
|
||||
if (!api.features.isActive(this.component)) {
|
||||
contentEl.createEl("h2", { text: t("EXTRAS_GATEWAY_FEATURE_TITLE") });
|
||||
contentEl.createEl("p", {
|
||||
text: t("EXTRAS_GATEWAY_FEATURE_DESC").replace("{component}", compName),
|
||||
});
|
||||
|
||||
const featureBtnText = t(
|
||||
"EXTRAS_GATEWAY_ENABLE_FEATURE_PERM_BTN",
|
||||
).replace("{component}", compName);
|
||||
|
||||
this.addControls(
|
||||
contentEl,
|
||||
(minutes) => {
|
||||
void (async () => {
|
||||
await this.gateway.enableFeature(this.component, api, minutes);
|
||||
await this.renderStep(); // Re-evaluate state!
|
||||
})();
|
||||
},
|
||||
featureBtnText,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Final Step: Everything is active!
|
||||
this.resolveAndClose("success");
|
||||
}
|
||||
|
||||
private addControls(
|
||||
container: HTMLElement,
|
||||
onEnable: (minutes: number) => void,
|
||||
permBtnText: string,
|
||||
) {
|
||||
new Setting(container).addButton((btn) =>
|
||||
btn
|
||||
.setButtonText(permBtnText)
|
||||
.setCta()
|
||||
.onClick(() => onEnable(0)),
|
||||
);
|
||||
|
||||
const isSessionOnly =
|
||||
this.component === "mathjax" || this.component === "mermaid";
|
||||
if (this.gateway.isInstalled() && this.gateway.isPluginEnabled()) {
|
||||
if (isSessionOnly) {
|
||||
new Setting(container)
|
||||
.setName(t("EXTRAS_GATEWAY_TEMP_ENABLE_TITLE"))
|
||||
.setDesc(t("EXTRAS_GATEWAY_SESSION_ENABLE_DESC"))
|
||||
.addButton((btn) =>
|
||||
btn
|
||||
.setButtonText(t("EXTRAS_GATEWAY_ENABLE_CURRENT_SESSION"))
|
||||
.onClick(() => onEnable(-1)),
|
||||
);
|
||||
} else {
|
||||
new Setting(container)
|
||||
.setName(t("EXTRAS_GATEWAY_TEMP_ENABLE_TITLE"))
|
||||
.setDesc(t("EXTRAS_GATEWAY_TEMP_ENABLE_DESC"))
|
||||
.addButton((btn) =>
|
||||
btn.setButtonText("5 Min").onClick(() => onEnable(5)),
|
||||
)
|
||||
.addButton((btn) =>
|
||||
btn.setButtonText("30 Min").onClick(() => onEnable(30)),
|
||||
)
|
||||
.addButton((btn) =>
|
||||
btn.setButtonText("1 Hour").onClick(() => onEnable(60)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
new Setting(container)
|
||||
.addButton((btn) =>
|
||||
btn
|
||||
.setButtonText(t("BACKUP_CANCEL"))
|
||||
.onClick(() => this.resolveAndClose("cancel")),
|
||||
)
|
||||
.addButton((btn) =>
|
||||
btn
|
||||
.setButtonText(t("EXTRAS_GATEWAY_IGNORE_SESSION"))
|
||||
.setWarning()
|
||||
.onClick(() => this.resolveAndClose("ignore")),
|
||||
);
|
||||
}
|
||||
|
||||
private resolveAndClose(
|
||||
result: ActionResolution,
|
||||
shouldClose: boolean = true,
|
||||
) {
|
||||
if (this.hasResolved) {
|
||||
return;
|
||||
}
|
||||
this.hasResolved = true;
|
||||
this.resolvePromise(result);
|
||||
if (shouldClose) {
|
||||
this.close();
|
||||
}
|
||||
}
|
||||
|
||||
onClose() {
|
||||
this.contentEl.empty();
|
||||
if (!this.hasResolved) {
|
||||
this.resolveAndClose("cancel", false);
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
-9
@@ -206,13 +206,15 @@ export const createImageCropperFile = async (
|
||||
|
||||
newImage.frameId = frameID;
|
||||
|
||||
targetEA.style.opacity = 50;
|
||||
targetEA.style.fillStyle = "solid";
|
||||
targetEA.style.strokeStyle = "solid";
|
||||
targetEA.style.strokeColor = "black";
|
||||
targetEA.style.backgroundColor = "black";
|
||||
targetEA.style.roughness = 0;
|
||||
targetEA.style.roundness = null;
|
||||
targetEA.setStyle({
|
||||
opacity: 50,
|
||||
fillStyle: "solid",
|
||||
strokeStyle: "solid",
|
||||
strokeColor: "black",
|
||||
backgroundColor: "black",
|
||||
roughness: 0,
|
||||
roundness: null,
|
||||
});
|
||||
targetEA.canvas.theme = "light";
|
||||
targetEA.canvas.viewBackgroundColor = isPDF ? "#5d5d5d" : "#3d3d3d";
|
||||
|
||||
@@ -221,8 +223,10 @@ export const createImageCropperFile = async (
|
||||
if (templateFile && templateFile instanceof TFile) {
|
||||
const { appState } = await targetEA.getSceneFromFile(templateFile);
|
||||
if (appState) {
|
||||
targetEA.style.fontFamily = appState.currentItemFontFamily;
|
||||
targetEA.style.fontSize = appState.currentItemFontSize;
|
||||
targetEA.setStyle({
|
||||
fontFamily: appState.currentItemFontFamily,
|
||||
fontSize: appState.currentItemFontSize,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,8 @@ export async function getDataURL(
|
||||
const dataURL = reader.result as DataURL;
|
||||
resolve(dataURL);
|
||||
};
|
||||
reader.onerror = (error) => reject(error);
|
||||
reader.onerror = (error: ProgressEvent<FileReader>) =>
|
||||
reject(new Error(`Failed to read file as DataURL.}`));
|
||||
reader.readAsDataURL(new Blob([new Uint8Array(file)], { type: mimeType }));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import { App, TFile, WorkspaceLeaf, WorkspaceSplit } from "obsidian";
|
||||
import type { LocalGraphView } from "src/types/types";
|
||||
import { getLinkParts } from "./sceneDataUtils";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { setStyle } from "./styleUtils";
|
||||
|
||||
export const createLeaf = (
|
||||
view: ExcalidrawView,
|
||||
@@ -28,9 +29,11 @@ export const createLeaf = (
|
||||
rootSplit.getRoot = () =>
|
||||
view.app.workspace[doc === mainDocument ? "rootSplit" : "floatingSplit"];
|
||||
rootSplit.getContainer = () => getContainerForDocument(doc);
|
||||
rootSplit.containerEl.style.width = "100%";
|
||||
rootSplit.containerEl.style.height = "100%";
|
||||
rootSplit.containerEl.style.borderRadius = "var(--embeddable-radius)";
|
||||
setStyle(rootSplit.containerEl, {
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
borderRadius: "var(--embeddable-radius)",
|
||||
});
|
||||
view.plugin.setDebounceActiveLeafChangeHandler();
|
||||
return {
|
||||
leaf: view.app.workspace.createLeafInParent(rootSplit, 0),
|
||||
@@ -152,7 +155,9 @@ export function predictViewType(app: App, file: TFile): string {
|
||||
if (typeof vt === "string" && vt) {
|
||||
return vt;
|
||||
}
|
||||
} catch {}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 2) Try extension mapping from registry
|
||||
@@ -166,7 +171,9 @@ export function predictViewType(app: App, file: TFile): string {
|
||||
if (typeof vt === "string" && vt) {
|
||||
return vt;
|
||||
}
|
||||
} catch {}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
export const durationTreshold = 0; //0.05; //ms
|
||||
|
||||
export const DEBUGGING = false;
|
||||
|
||||
export const log = console.log.bind(window.console);
|
||||
//eslint-disable-next-line obsidianmd/rule-custom-message
|
||||
export const log = (...args: unknown[]) => console.log(...args);
|
||||
export const debug = (
|
||||
fn: (...args: unknown[]) => unknown,
|
||||
fnName: string,
|
||||
...messages: unknown[]
|
||||
) => {
|
||||
//console.log(fnName,fn,...messages);
|
||||
console.log(fnName, ...messages);
|
||||
log(fnName, ...messages);
|
||||
};
|
||||
|
||||
let timestamp: number[] = [];
|
||||
@@ -47,19 +46,15 @@ export class CustomMutationObserver {
|
||||
}
|
||||
|
||||
observe(target: Node, options: MutationObserverInit) {
|
||||
const wrappedCallback: MutationCallback = async (
|
||||
mutationsList,
|
||||
observer,
|
||||
) => {
|
||||
const wrappedCallback: MutationCallback = (mutationsList, observer) => {
|
||||
const startTime = performance.now(); // Get start time
|
||||
await this.originalCallback(mutationsList, observer); // Invoke the original callback
|
||||
this.originalCallback(mutationsList, observer); // Invoke the original callback
|
||||
const endTime = performance.now(); // Get end time
|
||||
const executionTime = endTime - startTime;
|
||||
if (executionTime > durationTreshold) {
|
||||
console.log(
|
||||
`Excalidraw ${this.name} MutationObserver callback took ${executionTime}ms to execute`,
|
||||
observer,
|
||||
);
|
||||
const message = `Excalidraw ${this.name} MutationObserver callback took ${executionTime}ms to execute`;
|
||||
// eslint-disable-next-line obsidianmd/rule-custom-message -- needed for production debugging
|
||||
console.log(message, observer);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -190,7 +190,7 @@ export const setDynamicStyle = (
|
||||
|
||||
const toolspanel = view.toolsPanelRef?.current?.containerRef?.current;
|
||||
if (toolspanel) {
|
||||
let toolsStyle = toolspanel.getAttribute("style");
|
||||
let toolsStyle = toolspanel.getAttribute("style") ?? "";
|
||||
toolsStyle = toolsStyle.replace(/--color-primary.*/, "");
|
||||
toolspanel.setAttribute("style", toolsStyle + styleString);
|
||||
}
|
||||
|
||||
@@ -40,8 +40,6 @@ import {
|
||||
isVersionNewerThanOther,
|
||||
scaleLoadedImage,
|
||||
} from "src/utils/utils";
|
||||
import { LaTexPrompt } from "src/shared/Dialogs/Prompt";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { EmbeddedFilesLoader } from "src/shared/EmbeddedFileLoader";
|
||||
import {
|
||||
@@ -59,7 +57,6 @@ import {
|
||||
sceneRemoveInternalLinks,
|
||||
} from "./excalidrawViewUtils";
|
||||
import { ScriptEngine } from "src/shared/Scripts";
|
||||
import { getEA } from "src/core";
|
||||
import { ColorMap, FileData } from "src/types/embeddedFileLoaderTypes";
|
||||
import { ExportSettings } from "src/types/exportUtilTypes";
|
||||
|
||||
@@ -828,57 +825,6 @@ export function repositionElementsToCursor(
|
||||
});
|
||||
}
|
||||
|
||||
export const insertLaTeXToView = (
|
||||
view: ExcalidrawView,
|
||||
center: boolean = false,
|
||||
) => {
|
||||
const app = view.plugin.app;
|
||||
const ea = getEA(view);
|
||||
LaTexPrompt.Prompt(
|
||||
app,
|
||||
t("ENTER_LATEX"),
|
||||
view.plugin.settings.latexBoilerplate,
|
||||
).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, scaleX, scaleY);
|
||||
if (center) {
|
||||
const el = ea.getElement(id);
|
||||
const { width, height } = el;
|
||||
const { x, y } = ea.getViewCenterPosition();
|
||||
el.x = x - width / 2;
|
||||
el.y = y - height / 2;
|
||||
}
|
||||
await ea.addElementsToView(!center, false, true);
|
||||
ea.selectElementsInView([id]);
|
||||
}
|
||||
ea.destroy();
|
||||
},
|
||||
() => {},
|
||||
);
|
||||
};
|
||||
|
||||
export const search = async (view: ExcalidrawView) => {
|
||||
const ea = view.plugin.ea;
|
||||
ea.reset();
|
||||
|
||||
@@ -7,6 +7,7 @@ import { getCommonBoundingBox, restoreElements } from "src/constants/constants";
|
||||
import { getEA } from "src/core";
|
||||
import { t } from "src/lang/helpers";
|
||||
import type ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { errorlog } from "./utils";
|
||||
|
||||
function estimateBounds(
|
||||
elements: ExcalidrawElement[],
|
||||
@@ -64,8 +65,10 @@ export const insertLaTeXToView = (
|
||||
) => {
|
||||
const app = view.plugin.app;
|
||||
const ea = getEA(view);
|
||||
|
||||
void import("src/shared/Dialogs/Prompt").then(({ LaTexPrompt }) => {
|
||||
LaTexPrompt.Prompt(
|
||||
view.plugin,
|
||||
app,
|
||||
t("ENTER_LATEX"),
|
||||
view.plugin.settings.latexBoilerplate,
|
||||
@@ -82,31 +85,41 @@ export const insertLaTeXToView = (
|
||||
!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) {
|
||||
if (dataurl && 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, scaleX, scaleY);
|
||||
if (center) {
|
||||
const el = ea.getElement(id);
|
||||
const { width, height } = el;
|
||||
const { x, y } = ea.getViewCenterPosition();
|
||||
el.x = x - width / 2;
|
||||
el.y = y - height / 2;
|
||||
if (el) {
|
||||
const { width, height } = el;
|
||||
const { x, y } = ea.getViewCenterPosition();
|
||||
el.x = x - width / 2;
|
||||
el.y = y - height / 2;
|
||||
}
|
||||
}
|
||||
await ea.addElementsToView(!center, false, true);
|
||||
ea.selectElementsInView([id]);
|
||||
}
|
||||
ea.destroy();
|
||||
},
|
||||
() => {},
|
||||
(e) => {
|
||||
// Promise rejection handler (e.g. user cancelled prompt or Extras plugin is missing)
|
||||
if (e && e instanceof Error) {
|
||||
errorlog({ message: "LaTeX Insertion aborted", error: e as unknown });
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -26,8 +26,10 @@ import {
|
||||
ExcalidrawFrameElement,
|
||||
ExcalidrawImageElement,
|
||||
ExcalidrawTextElement,
|
||||
FileId,
|
||||
NonDeletedExcalidrawElement,
|
||||
} from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { getAllNestedExcalidrawFiles } from "./fileUtils";
|
||||
import {
|
||||
getEmbeddedFilenameParts,
|
||||
getLinkParts,
|
||||
@@ -45,6 +47,7 @@ import { EmbeddedFile } from "src/shared/EmbeddedFileLoader";
|
||||
import { CaptureUpdateAction } from "src/constants/constants";
|
||||
import { setSanitizedHtml } from "./htmlUtils";
|
||||
import { URLs } from "src/constants/safeUrls";
|
||||
import { isInstanceOfHTMLDivElement } from "./typechecks";
|
||||
|
||||
type CommandLinkOptInPlugin = {
|
||||
settings: {
|
||||
@@ -74,14 +77,14 @@ class CommandLinkOptInPrompt extends Modal {
|
||||
setSanitizedHtml(messageEl, this.message);
|
||||
|
||||
const buttonContainer = this.contentEl.createDiv();
|
||||
buttonContainer.style.display = "flex";
|
||||
buttonContainer.style.justifyContent = "flex-end";
|
||||
buttonContainer.style.marginTop = "1rem";
|
||||
buttonContainer.addClass(
|
||||
"excalidraw-commandLinkOptInPrompt-buttonContainer",
|
||||
);
|
||||
|
||||
const denyButton = buttonContainer.createEl("button", {
|
||||
text: t("ENABLE_COMMAND_LINKS_CONFIRM_DENY"),
|
||||
});
|
||||
denyButton.style.marginRight = "0.5rem";
|
||||
denyButton.addClass("excalidraw-commandLinkOptInPrompt-denyButton");
|
||||
denyButton.onclick = () => {
|
||||
this.selectedValue = null;
|
||||
this.close();
|
||||
@@ -116,7 +119,7 @@ const getCommandLinkOptInPlugin = (app: App): CommandLinkOptInPlugin | null => {
|
||||
return candidate as unknown as CommandLinkOptInPlugin;
|
||||
}
|
||||
if (EXCALIDRAW_PLUGIN && EXCALIDRAW_PLUGIN.app === app) {
|
||||
return EXCALIDRAW_PLUGIN as unknown as CommandLinkOptInPlugin;
|
||||
return EXCALIDRAW_PLUGIN;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
@@ -148,6 +151,75 @@ const executeCommandLinkWithConfirmation = async (cmd: string, app: App) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the set of top-level embedded-file IDs that need to be rebuilt on
|
||||
* leaf switch because either the file itself or any nested Excalidraw dependency
|
||||
* was modified since the view last completed a scene load.
|
||||
*/
|
||||
export function getChangedTopLevelDependencyFileIDs(
|
||||
view: ExcalidrawView,
|
||||
): Set<FileId> {
|
||||
const changedFileIDs = new Set<FileId>();
|
||||
if (!view.file || !view.excalidrawData || view.lastSceneLoadTime === 0) {
|
||||
return changedFileIDs;
|
||||
}
|
||||
|
||||
const plugin = view.plugin;
|
||||
const lastLoadTime = view.lastSceneLoadTime;
|
||||
|
||||
// Map from embedded Excalidraw file path → fileIds that reference it,
|
||||
// used to propagate nested-dependency changes to top-level entries.
|
||||
const excalidrawFileIdsByPath = new Map<string, Set<FileId>>();
|
||||
|
||||
for (const [fileId, embeddedFile] of view.excalidrawData.getFileEntries()) {
|
||||
const embeddedTarget = embeddedFile?.file;
|
||||
if (!embeddedTarget || embeddedFile.mtime === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Direct change: the embedded target itself was modified after the last load.
|
||||
if (embeddedTarget.stat.mtime > lastLoadTime) {
|
||||
changedFileIDs.add(fileId);
|
||||
}
|
||||
|
||||
// Track Excalidraw embeds so we can walk their nested deps below.
|
||||
if (plugin.isExcalidrawFile(embeddedTarget)) {
|
||||
const set =
|
||||
excalidrawFileIdsByPath.get(embeddedTarget.path) ?? new Set<FileId>();
|
||||
set.add(fileId);
|
||||
excalidrawFileIdsByPath.set(embeddedTarget.path, set);
|
||||
}
|
||||
}
|
||||
|
||||
if (excalidrawFileIdsByPath.size === 0) {
|
||||
return changedFileIDs;
|
||||
}
|
||||
|
||||
// Walk the full nested dependency tree of the root drawing.
|
||||
// If any nested file changed since lastLoadTime, mark all top-level embeds
|
||||
// that include it (identified via path[1]) as needing a rebuild.
|
||||
const nestedTree = getAllNestedExcalidrawFiles(plugin, view.file, false);
|
||||
for (const [file, node] of nestedTree.entries()) {
|
||||
if (file.stat.mtime <= lastLoadTime) {
|
||||
continue;
|
||||
}
|
||||
for (const path of node.paths) {
|
||||
const topLevelDep = path[1];
|
||||
if (!topLevelDep) {
|
||||
continue;
|
||||
}
|
||||
const fileIds = excalidrawFileIdsByPath.get(topLevelDep.path);
|
||||
if (fileIds) {
|
||||
for (const fileId of fileIds) {
|
||||
changedFileIDs.add(fileId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return changedFileIDs;
|
||||
}
|
||||
|
||||
export async function insertImageToView(
|
||||
ea: ExcalidrawAutomate,
|
||||
position: { x: number; y: number },
|
||||
@@ -159,8 +231,10 @@ export async function insertImageToView(
|
||||
if (shouldInsertToView) {
|
||||
ea.clear();
|
||||
}
|
||||
ea.style.strokeColor = "transparent";
|
||||
ea.style.backgroundColor = "transparent";
|
||||
ea.setStyle({
|
||||
backgroundColor: "transparent",
|
||||
strokeColor: "transparent",
|
||||
});
|
||||
const api = ea.getExcalidrawAPI();
|
||||
ea.canvas.theme = api.getAppState().theme;
|
||||
const id = await ea.addImage(position.x, position.y, file, scale);
|
||||
@@ -194,15 +268,23 @@ export async function insertEmbeddableToView(
|
||||
const st = api.getAppState();
|
||||
|
||||
if (ea.plugin.settings.embeddableMarkdownDefaults.backgroundMatchElement) {
|
||||
ea.style.backgroundColor = st.currentItemBackgroundColor;
|
||||
ea.setStyle({
|
||||
backgroundColor: st.currentItemBackgroundColor,
|
||||
});
|
||||
} else {
|
||||
ea.style.backgroundColor = "transparent";
|
||||
ea.setStyle({
|
||||
backgroundColor: "transparent",
|
||||
});
|
||||
}
|
||||
|
||||
if (ea.plugin.settings.embeddableMarkdownDefaults.borderMatchElement) {
|
||||
ea.style.strokeColor = st.currentItemStrokeColor;
|
||||
ea.setStyle({
|
||||
strokeColor: st.currentItemStrokeColor,
|
||||
});
|
||||
} else {
|
||||
ea.style.strokeColor = "transparent";
|
||||
ea.setStyle({
|
||||
strokeColor: "transparent",
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -226,8 +308,10 @@ export async function insertEmbeddableToView(
|
||||
link.match(/\[\[[^\]]+?\.([^.\]]+)]]/)?.[1]?.toLocaleLowerCase(),
|
||||
))
|
||||
) {
|
||||
ea.style.strokeColor = "transparent";
|
||||
ea.style.backgroundColor = "transparent";
|
||||
ea.setStyle({
|
||||
strokeColor: "transparent",
|
||||
backgroundColor: "transparent",
|
||||
});
|
||||
height = getAudioElementHeight();
|
||||
}
|
||||
const id = ea.addEmbeddable(
|
||||
@@ -259,7 +343,12 @@ export async function addTextWithOEmbed(
|
||||
};
|
||||
const title = data?.title?.trim();
|
||||
return title && !data.error ? title : null;
|
||||
} catch (_) {
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"unexpected error in resolveTitleFromOEmbed",
|
||||
resolveTitleFromOEmbed,
|
||||
error,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
@@ -289,7 +378,12 @@ export async function addTextWithOEmbed(
|
||||
(candidate) => candidate && candidate.trim().length > 0,
|
||||
);
|
||||
return title?.trim() ?? null;
|
||||
} catch (_) {
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"unexpected error in resolveTitleFromPage",
|
||||
resolveTitleFromPage,
|
||||
error,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
@@ -320,7 +414,13 @@ export async function addTextWithOEmbed(
|
||||
} finally {
|
||||
ea.destroy();
|
||||
}
|
||||
} catch (_) {}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"unexpected error in addTextWithOEmbed",
|
||||
addTextWithOEmbed,
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function getLinkTextFromLink(text: string): string {
|
||||
@@ -792,7 +892,7 @@ export function getViewColorPalette(
|
||||
|
||||
const api = view.excalidrawAPI;
|
||||
const { colorPalette } = api.getAppState();
|
||||
if (!colorPalette || !colorPalette.hasOwnProperty(palette)) {
|
||||
if (!colorPalette || !Object.hasOwn(colorPalette ?? {}, palette)) {
|
||||
return getDefaultColorPalette();
|
||||
}
|
||||
|
||||
@@ -929,7 +1029,7 @@ export const setMobileNavbarPosition = (dock: boolean) => {
|
||||
const navbar = mainDocument.querySelector(
|
||||
"body>.app-container>.mobile-navbar",
|
||||
);
|
||||
if (navbar && navbar instanceof HTMLDivElement) {
|
||||
if (navbar && isInstanceOfHTMLDivElement(navbar)) {
|
||||
if (dock) {
|
||||
navbar.addClass("excalidraw-mobile-navbar-docked");
|
||||
} else {
|
||||
|
||||
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user