mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-12-03 06:43:35 +00:00
Compare commits
120
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bdd55aea2c | ||
|
|
b26cb5d067 | ||
|
|
d2e1d72678 | ||
|
|
76e5d82c0f | ||
|
|
9391ba45a3 | ||
|
|
e08db69c4c | ||
|
|
59d2650a99 | ||
|
|
fcecb19d11 | ||
|
|
5cbe209666 | ||
|
|
922aa5d17b | ||
|
|
6206962185 | ||
|
|
0204a1d19c | ||
|
|
cfa18cdd6d | ||
|
|
ab3bed01cd | ||
|
|
711142a899 | ||
|
|
cc5a3006c9 | ||
|
|
03d3e25611 | ||
|
|
478fca4306 | ||
|
|
0446b3dbed | ||
|
|
b0b2afb972 | ||
|
|
5d5970c62d | ||
|
|
4bcb9be49d | ||
|
|
8d9546f4cd | ||
|
|
5257a0a73f | ||
|
|
955b0de308 | ||
|
|
e2739fe34c | ||
|
|
3ac427f813 | ||
|
|
36044e41a1 | ||
|
|
91156279c5 | ||
|
|
1083c9fb10 | ||
|
|
1e40fe28db | ||
|
|
c3d8f8e5d5 | ||
|
|
49d657aad9 | ||
|
|
d844daaaec | ||
|
|
ecd24f57a6 | ||
|
|
30c901e6f3 | ||
|
|
2d7873ad0d | ||
|
|
b1786a35e8 | ||
|
|
7033020101 | ||
|
|
1657837830 | ||
|
|
97f425b6de | ||
|
|
46d69db8a6 | ||
|
|
6326c62bcd | ||
|
|
f0e231a3e5 | ||
|
|
7b1d91ce0d | ||
|
|
b6fd3bd665 | ||
|
|
7c24821011 | ||
|
|
9ae74c7af0 | ||
|
|
14d5521483 | ||
|
|
6865fdf33c | ||
|
|
c573d2cba3 | ||
|
|
9186537a1a | ||
|
|
d89a212c46 | ||
|
|
6a1d773d87 | ||
|
|
4c23be299c | ||
|
|
1136f19bb6 | ||
|
|
230c0e9c4b | ||
|
|
dddd13e439 | ||
|
|
83337cbec7 | ||
|
|
7c14328226 | ||
|
|
dd579e8d52 | ||
|
|
c5b34b0e50 | ||
|
|
6651db8c3a | ||
|
|
60a692ba7b | ||
|
|
a21481aae5 | ||
|
|
e1ec75f7c7 | ||
|
|
b15a9cff91 | ||
|
|
c7bbb0ca0f | ||
|
|
3dd3f6c5a3 | ||
|
|
3931fa95b8 | ||
|
|
fc03c0bfd2 | ||
|
|
00ce6b1883 | ||
|
|
a9a2c63873 | ||
|
|
4bd42bff9a | ||
|
|
a2ae59965b | ||
|
|
49d6e2180e | ||
|
|
75f69af2cd | ||
|
|
f2eed2a755 | ||
|
|
9b0c656e0b | ||
|
|
ada0caea1a | ||
|
|
37c1c2459f | ||
|
|
38ad0c9eed | ||
|
|
dd37894ddd | ||
|
|
54bb7558f7 | ||
|
|
d698f2d3f7 | ||
|
|
135e634df3 | ||
|
|
bec690c792 | ||
|
|
d57d8ecc9d | ||
|
|
ab5d26078c | ||
|
|
1b7f9c19de | ||
|
|
22324613f3 | ||
|
|
3baf7de216 | ||
|
|
250a1a14d5 | ||
|
|
fd0d84d240 | ||
|
|
a9ffdde8e5 | ||
|
|
5206aff1cf | ||
|
|
8022f9a89b | ||
|
|
5216d81db9 | ||
|
|
949789ec8c | ||
|
|
53f21bca9b | ||
|
|
1246eca2f3 | ||
|
|
06014da0b7 | ||
|
|
24b6a610b8 | ||
|
|
35dd6dd650 | ||
|
|
26ce6dfe0d | ||
|
|
ebaab2702c | ||
|
|
1638d9cc42 | ||
|
|
9bb5d7249e | ||
|
|
7986ed4000 | ||
|
|
4d9a8d90ba | ||
|
|
3994f63e69 | ||
|
|
956cdf07ea | ||
|
|
03692dfd77 | ||
|
|
5340669fd6 | ||
|
|
df281889ff | ||
|
|
25629ee5eb | ||
|
|
e6e61d3a99 | ||
|
|
7c9a2e9d57 | ||
|
|
41177030ae | ||
|
|
6a09b3f873 |
No files matched your search
+11
-1
@@ -10,6 +10,11 @@ type DataURL = string & { _brand: "DataURL" };
|
||||
type FileId = string & { _brand: "FileId" };
|
||||
const fileid = customAlphabet("1234567890abcdef", 40);
|
||||
|
||||
type Tex2DataURLOptions = {
|
||||
applyThemeFilter?: boolean;
|
||||
themeFilter?: string;
|
||||
};
|
||||
|
||||
let adaptor: LiteAdaptor;
|
||||
let html: any;
|
||||
let preamble: string;
|
||||
@@ -38,7 +43,8 @@ async function getImageSize(src: string): Promise<{ height: number; width: numbe
|
||||
export async function tex2dataURL(
|
||||
tex: string,
|
||||
scale: number = 4,
|
||||
plugin?: any
|
||||
plugin?: any,
|
||||
options?: Tex2DataURLOptions
|
||||
): Promise<{
|
||||
mimeType: string;
|
||||
fileId: FileId;
|
||||
@@ -81,6 +87,10 @@ export async function tex2dataURL(
|
||||
styleNode.appendChild(document.createTextNode(".mjx-solid { stroke-width: 80px; }"));
|
||||
svg.appendChild(styleNode);
|
||||
|
||||
if (options?.applyThemeFilter && options.themeFilter) {
|
||||
svg.setAttribute("filter", options.themeFilter);
|
||||
}
|
||||
|
||||
if (svg) {
|
||||
if(svg.width.baseVal.valueInSpecifiedUnits < 2) {
|
||||
svg.width.baseVal.valueAsString = `${(svg.width.baseVal.valueInSpecifiedUnits+1).toFixed(3)}ex`;
|
||||
|
||||
@@ -2949,4 +2949,642 @@ export type Offsets = Partial<{
|
||||
left: number;
|
||||
}>;
|
||||
|
||||
/* ************************************** */
|
||||
/* node_modules/@zsviczian/excalidraw/types/element/src/bounds.d.ts */
|
||||
/* ************************************** */
|
||||
export type RectangleBox = {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
angle: number;
|
||||
};
|
||||
export type SceneBounds = readonly [
|
||||
sceneX: number,
|
||||
sceneY: number,
|
||||
sceneX2: number,
|
||||
sceneY2: number
|
||||
];
|
||||
export declare class ElementBounds {
|
||||
private static boundsCache;
|
||||
private static nonRotatedBoundsCache;
|
||||
static getBounds(element: ExcalidrawElement, elementsMap: ElementsMap, nonRotated?: boolean): Bounds;
|
||||
private static calculateBounds;
|
||||
}
|
||||
export declare const getElementAbsoluteCoords: (element: ExcalidrawElement, elementsMap: ElementsMap, includeBoundText?: boolean) => [number, number, number, number, number, number];
|
||||
/**
|
||||
* Given an element, return the line segments that make up the element.
|
||||
*
|
||||
* Uses helpers from /math
|
||||
*/
|
||||
export declare const getElementLineSegments: (element: ExcalidrawElement, elementsMap: ElementsMap) => LineSegment<GlobalPoint>[];
|
||||
/**
|
||||
* Scene -> Scene coords, but in x1,x2,y1,y2 format.
|
||||
*
|
||||
* Rectangle here means any rectangular frame, not an excalidraw element.
|
||||
*/
|
||||
export declare const getRectangleBoxAbsoluteCoords: (boxSceneCoords: RectangleBox) => number[];
|
||||
export declare const getDiamondPoints: (element: ExcalidrawElement) => number[];
|
||||
export declare const getCubicBezierCurveBound: (p0: GlobalPoint, p1: GlobalPoint, p2: GlobalPoint, p3: GlobalPoint) => Bounds;
|
||||
export declare const getMinMaxXYFromCurvePathOps: (ops: Op[], transformXY?: (p: GlobalPoint) => GlobalPoint) => Bounds;
|
||||
export declare const getBoundsFromPoints: (points: ExcalidrawFreeDrawElement["points"]) => Bounds;
|
||||
/** @returns number in pixels */
|
||||
export declare const getArrowheadSize: (arrowhead: Arrowhead) => number;
|
||||
/** @returns number in degrees */
|
||||
export declare const getArrowheadAngle: (arrowhead: Arrowhead) => Degrees;
|
||||
export declare const getArrowheadPoints: (element: ExcalidrawLinearElement, shape: Drawable[], position: "start" | "end", arrowhead: Arrowhead) => number[] | null;
|
||||
export declare const getElementBounds: (element: ExcalidrawElement, elementsMap: ElementsMap, nonRotated?: boolean) => Bounds;
|
||||
export declare const getCommonBounds: (elements: ElementsMapOrArray, elementsMap?: ElementsMap) => Bounds;
|
||||
export declare const getDraggedElementsBounds: (elements: ExcalidrawElement[], dragOffset: {
|
||||
x: number;
|
||||
y: number;
|
||||
}) => number[];
|
||||
export declare const getResizedElementAbsoluteCoords: (element: ExcalidrawElement, nextWidth: number, nextHeight: number, normalizePoints: boolean) => Bounds;
|
||||
export declare const getElementPointsCoords: (element: ExcalidrawLinearElement, points: readonly (readonly [number, number])[]) => Bounds;
|
||||
export declare const getClosestElementBounds: (elements: readonly ExcalidrawElement[], from: {
|
||||
x: number;
|
||||
y: number;
|
||||
}) => Bounds;
|
||||
export interface BoundingBox {
|
||||
minX: number;
|
||||
minY: number;
|
||||
maxX: number;
|
||||
maxY: number;
|
||||
midX: number;
|
||||
midY: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
export declare const getCommonBoundingBox: (elements: readonly ExcalidrawElement[] | readonly NonDeleted<ExcalidrawElement>[]) => BoundingBox;
|
||||
/**
|
||||
* returns scene coords of user's editor viewport (visible canvas area) bounds
|
||||
*/
|
||||
export declare const getVisibleSceneBounds: ({ scrollX, scrollY, width, height, zoom, }: AppState) => SceneBounds;
|
||||
export declare const getCenterForBounds: (bounds: Bounds) => GlobalPoint;
|
||||
/**
|
||||
* Get the axis-aligned bounding box for a given element
|
||||
*/
|
||||
export declare const aabbForElement: (element: Readonly<ExcalidrawElement>, elementsMap: ElementsMap, offset?: [number, number, number, number]) => Bounds;
|
||||
export declare const pointInsideBounds: <P extends GlobalPoint | LocalPoint>(p: P, bounds: Bounds) => boolean;
|
||||
export declare const doBoundsIntersect: (bounds1: Bounds | null, bounds2: Bounds | null) => boolean;
|
||||
export declare const elementCenterPoint: (element: ExcalidrawElement, elementsMap: ElementsMap, xOffset?: number, yOffset?: number) => GlobalPoint;
|
||||
|
||||
/* ************************************** */
|
||||
/* node_modules/@zsviczian/excalidraw/types/excalidraw/components/App.d.ts */
|
||||
/* ************************************** */
|
||||
export declare const ExcalidrawContainerContext: React.Context<{
|
||||
container: HTMLDivElement | null;
|
||||
id: string | null;
|
||||
}>;
|
||||
export declare const useApp: () => AppClassProperties;
|
||||
export declare const useAppProps: () => AppProps;
|
||||
export declare const useEditorInterface: () => Readonly<{
|
||||
formFactor: "phone" | "tablet" | "desktop";
|
||||
desktopUIMode: "compact" | "full" | "tray";
|
||||
userAgent: Readonly<{
|
||||
isMobileDevice: boolean;
|
||||
platform: "ios" | "android" | "other" | "unknown";
|
||||
}>;
|
||||
isTouchScreen: boolean;
|
||||
canFitSidebar: boolean;
|
||||
isLandscape: boolean;
|
||||
preferTrayMode: boolean;
|
||||
}>;
|
||||
export declare const useStylesPanelMode: () => StylesPanelMode;
|
||||
export declare const useExcalidrawContainer: () => {
|
||||
container: HTMLDivElement | null;
|
||||
id: string | null;
|
||||
};
|
||||
export declare const useExcalidrawElements: () => readonly NonDeletedExcalidrawElement[];
|
||||
export declare const useExcalidrawAppState: () => AppState;
|
||||
export declare const useExcalidrawSetAppState: () => <K extends keyof AppState>(state: AppState | ((prevState: Readonly<AppState>, props: Readonly<any>) => AppState | Pick<AppState, K> | null) | Pick<AppState, K> | null, callback?: (() => void) | undefined) => void;
|
||||
export declare const useExcalidrawActionManager: () => ActionManager;
|
||||
declare class App extends React.Component<AppProps, AppState> {
|
||||
canvas: AppClassProperties["canvas"];
|
||||
interactiveCanvas: AppClassProperties["interactiveCanvas"];
|
||||
rc: RoughCanvas;
|
||||
unmounted: boolean;
|
||||
actionManager: ActionManager;
|
||||
editorInterface: EditorInterface;
|
||||
private stylesPanelMode;
|
||||
private excalidrawContainerRef;
|
||||
scene: Scene;
|
||||
fonts: Fonts;
|
||||
renderer: Renderer;
|
||||
visibleElements: readonly NonDeletedExcalidrawElement[];
|
||||
private resizeObserver;
|
||||
library: AppClassProperties["library"];
|
||||
libraryItemsFromStorage: LibraryItems | undefined;
|
||||
id: string;
|
||||
private store;
|
||||
private history;
|
||||
private shouldRenderAllEmbeddables;
|
||||
excalidrawContainerValue: {
|
||||
container: HTMLDivElement | null;
|
||||
id: string;
|
||||
};
|
||||
files: BinaryFiles;
|
||||
imageCache: AppClassProperties["imageCache"];
|
||||
private iFrameRefs;
|
||||
/**
|
||||
* Indicates whether the embeddable's url has been validated for rendering.
|
||||
* If value not set, indicates that the validation is pending.
|
||||
* Initially or on url change the flag is not reset so that we can guarantee
|
||||
* the validation came from a trusted source (the editor).
|
||||
**/
|
||||
private embedsValidationStatus;
|
||||
/** embeds that have been inserted to DOM (as a perf optim, we don't want to
|
||||
* insert to DOM before user initially scrolls to them) */
|
||||
private initializedEmbeds;
|
||||
private handleToastClose;
|
||||
private elementsPendingErasure;
|
||||
flowChartCreator: FlowChartCreator;
|
||||
private flowChartNavigator;
|
||||
bindModeHandler: ReturnType<typeof setTimeout> | null;
|
||||
hitLinkElement?: NonDeletedExcalidrawElement;
|
||||
lastPointerDownEvent: React.PointerEvent<HTMLElement> | null;
|
||||
lastPointerUpEvent: React.PointerEvent<HTMLElement> | PointerEvent | null;
|
||||
lastPointerMoveEvent: PointerEvent | null;
|
||||
lastPointerMoveCoords: {
|
||||
x: number;
|
||||
y: number;
|
||||
} | null;
|
||||
lastViewportPosition: {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
allowMobileMode: boolean;
|
||||
animationFrameHandler: AnimationFrameHandler;
|
||||
laserTrails: LaserTrails;
|
||||
eraserTrail: EraserTrail;
|
||||
lassoTrail: LassoTrail;
|
||||
onChangeEmitter: Emitter<[elements: readonly ExcalidrawElement[], appState: AppState, files: BinaryFiles]>;
|
||||
onPointerDownEmitter: Emitter<[activeTool: {
|
||||
lastActiveTool: import("../types").ActiveTool | null;
|
||||
locked: boolean;
|
||||
fromSelection: boolean;
|
||||
} & import("../types").ActiveTool, pointerDownState: Readonly<{
|
||||
origin: Readonly<{
|
||||
x: number;
|
||||
y: number;
|
||||
}>;
|
||||
originInGrid: Readonly<{
|
||||
x: number;
|
||||
y: number;
|
||||
}>;
|
||||
scrollbars: ReturnType<typeof isOverScrollBars>;
|
||||
lastCoords: {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
originalElements: Map<string, NonDeleted<ExcalidrawElement>>;
|
||||
resize: {
|
||||
handleType: import("@excalidraw/element").MaybeTransformHandleType;
|
||||
isResizing: boolean;
|
||||
offset: {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
arrowDirection: "origin" | "end";
|
||||
center: {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
};
|
||||
hit: {
|
||||
element: NonDeleted<ExcalidrawElement> | null;
|
||||
allHitElements: NonDeleted<ExcalidrawElement>[];
|
||||
wasAddedToSelection: boolean;
|
||||
hasBeenDuplicated: boolean;
|
||||
hasHitCommonBoundingBoxOfSelectedElements: boolean;
|
||||
};
|
||||
withCmdOrCtrl: boolean;
|
||||
drag: {
|
||||
hasOccurred: boolean;
|
||||
offset: {
|
||||
x: number;
|
||||
y: number;
|
||||
} | null;
|
||||
origin: {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
blockDragging: boolean;
|
||||
};
|
||||
eventListeners: {
|
||||
onMove: null | ReturnType<typeof import("@excalidraw/common").throttleRAF>;
|
||||
onUp: null | ((event: PointerEvent) => void);
|
||||
onKeyDown: null | ((event: KeyboardEvent) => void);
|
||||
onKeyUp: null | ((event: KeyboardEvent) => void);
|
||||
};
|
||||
boxSelection: {
|
||||
hasOccurred: boolean;
|
||||
};
|
||||
}>, event: React.PointerEvent<HTMLElement>]>;
|
||||
onPointerUpEmitter: Emitter<[activeTool: {
|
||||
lastActiveTool: import("../types").ActiveTool | null;
|
||||
locked: boolean;
|
||||
fromSelection: boolean;
|
||||
} & import("../types").ActiveTool, pointerDownState: Readonly<{
|
||||
origin: Readonly<{
|
||||
x: number;
|
||||
y: number;
|
||||
}>;
|
||||
originInGrid: Readonly<{
|
||||
x: number;
|
||||
y: number;
|
||||
}>;
|
||||
scrollbars: ReturnType<typeof isOverScrollBars>;
|
||||
lastCoords: {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
originalElements: Map<string, NonDeleted<ExcalidrawElement>>;
|
||||
resize: {
|
||||
handleType: import("@excalidraw/element").MaybeTransformHandleType;
|
||||
isResizing: boolean;
|
||||
offset: {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
arrowDirection: "origin" | "end";
|
||||
center: {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
};
|
||||
hit: {
|
||||
element: NonDeleted<ExcalidrawElement> | null;
|
||||
allHitElements: NonDeleted<ExcalidrawElement>[];
|
||||
wasAddedToSelection: boolean;
|
||||
hasBeenDuplicated: boolean;
|
||||
hasHitCommonBoundingBoxOfSelectedElements: boolean;
|
||||
};
|
||||
withCmdOrCtrl: boolean;
|
||||
drag: {
|
||||
hasOccurred: boolean;
|
||||
offset: {
|
||||
x: number;
|
||||
y: number;
|
||||
} | null;
|
||||
origin: {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
blockDragging: boolean;
|
||||
};
|
||||
eventListeners: {
|
||||
onMove: null | ReturnType<typeof import("@excalidraw/common").throttleRAF>;
|
||||
onUp: null | ((event: PointerEvent) => void);
|
||||
onKeyDown: null | ((event: KeyboardEvent) => void);
|
||||
onKeyUp: null | ((event: KeyboardEvent) => void);
|
||||
};
|
||||
boxSelection: {
|
||||
hasOccurred: boolean;
|
||||
};
|
||||
}>, event: PointerEvent]>;
|
||||
onUserFollowEmitter: Emitter<[payload: OnUserFollowedPayload]>;
|
||||
onScrollChangeEmitter: Emitter<[scrollX: number, scrollY: number, zoom: Readonly<{
|
||||
value: import("../types").NormalizedZoomValue;
|
||||
}>]>;
|
||||
missingPointerEventCleanupEmitter: Emitter<[event: PointerEvent | null]>;
|
||||
onRemoveEventListenersEmitter: Emitter<[]>;
|
||||
constructor(props: AppProps);
|
||||
updateEditorAtom: <Value, Args extends unknown[], Result>(atom: WritableAtom<Value, Args, Result>, ...args: Args) => Result;
|
||||
private onWindowMessage;
|
||||
private handleSkipBindMode;
|
||||
private resetDelayedBindMode;
|
||||
private previousHoveredBindableElement;
|
||||
private handleDelayedBindModeChange;
|
||||
private cacheEmbeddableRef;
|
||||
/**
|
||||
* Returns gridSize taking into account `gridModeEnabled`.
|
||||
* If disabled, returns null.
|
||||
*/
|
||||
getEffectiveGridSize: () => NullableGridSize;
|
||||
private getHTMLIFrameElement;
|
||||
private handleEmbeddableCenterClick;
|
||||
private isIframeLikeElementCenter;
|
||||
private updateEmbedValidationStatus;
|
||||
private updateEmbeddables;
|
||||
private renderEmbeddables;
|
||||
private getFrameNameDOMId;
|
||||
frameNameBoundsCache: FrameNameBoundsCache;
|
||||
private resetEditingFrame;
|
||||
private renderFrameNames;
|
||||
private toggleOverscrollBehavior;
|
||||
render(): import("react/jsx-runtime").JSX.Element;
|
||||
focusContainer: AppClassProperties["focusContainer"];
|
||||
getSceneElementsIncludingDeleted: () => readonly import("@excalidraw/element/types").OrderedExcalidrawElement[];
|
||||
getSceneElementsMapIncludingDeleted: () => Map<string, Ordered<ExcalidrawElement>> & import("@excalidraw/common/utility-types").MakeBrand<"SceneElementsMap">;
|
||||
getSceneElements: () => readonly Ordered<NonDeletedExcalidrawElement>[];
|
||||
onInsertElements: (elements: readonly ExcalidrawElement[]) => void;
|
||||
onExportImage: (type: keyof typeof EXPORT_IMAGE_TYPES, elements: ExportedElements, opts: {
|
||||
exportingFrame: ExcalidrawFrameLikeElement | null;
|
||||
}) => Promise<void>;
|
||||
private magicGenerations;
|
||||
private updateMagicGeneration;
|
||||
plugins: {
|
||||
diagramToCode?: {
|
||||
generate: GenerateDiagramToCode;
|
||||
};
|
||||
};
|
||||
setPlugins(plugins: Partial<App["plugins"]>): void;
|
||||
private onMagicFrameGenerate;
|
||||
private onIframeSrcCopy;
|
||||
onMagicframeToolSelect: () => void;
|
||||
private openEyeDropper;
|
||||
dismissLinearEditor: () => void;
|
||||
syncActionResult: (actionResult: ActionResult) => void;
|
||||
private onBlur;
|
||||
private onUnload;
|
||||
private disableEvent;
|
||||
private resetHistory;
|
||||
private resetStore;
|
||||
/**
|
||||
* Resets scene & history.
|
||||
* ! Do not use to clear scene user action !
|
||||
*/
|
||||
private resetScene;
|
||||
private initializeScene;
|
||||
private getFormFactor;
|
||||
refreshEditorInterface: (preferTrayMode?: boolean) => void;
|
||||
private reconcileStylesPanelMode;
|
||||
/** TO BE USED LATER */
|
||||
private setDesktopUIMode;
|
||||
private isTouchScreen;
|
||||
private setTrayModeEnabled;
|
||||
isTrayModeEnabled: () => boolean;
|
||||
private clearImageShapeCache;
|
||||
componentDidMount(): Promise<void>;
|
||||
componentWillUnmount(): void;
|
||||
private onResize;
|
||||
/** generally invoked only if fullscreen was invoked programmatically */
|
||||
private onFullscreenChange;
|
||||
private removeEventListeners;
|
||||
private addEventListeners;
|
||||
componentDidUpdate(prevProps: AppProps, prevState: AppState): void;
|
||||
private renderInteractiveSceneCallback;
|
||||
private onScroll;
|
||||
private onCut;
|
||||
private onCopy;
|
||||
private static resetTapTwice;
|
||||
private onTouchStart;
|
||||
private onTouchEnd;
|
||||
private insertClipboardContent;
|
||||
pasteFromClipboard: (event: ClipboardEvent) => Promise<void>;
|
||||
addElementsFromPasteOrLibrary: (opts: {
|
||||
elements: readonly ExcalidrawElement[];
|
||||
files: BinaryFiles | null;
|
||||
position: {
|
||||
clientX: number;
|
||||
clientY: number;
|
||||
} | "cursor" | "center";
|
||||
retainSeed?: boolean;
|
||||
fitToContent?: boolean;
|
||||
}) => void;
|
||||
private addElementsFromMixedContentPaste;
|
||||
private addTextFromPaste;
|
||||
setAppState: React.Component<any, AppState>["setState"];
|
||||
removePointer: (event: React.PointerEvent<HTMLElement> | PointerEvent) => void;
|
||||
toggleLock: (source?: "keyboard" | "ui") => void;
|
||||
updateFrameRendering: (opts: Partial<AppState["frameRendering"]> | ((prevState: AppState["frameRendering"]) => Partial<AppState["frameRendering"]>)) => void;
|
||||
togglePenMode: (force: boolean | null) => void;
|
||||
onHandToolToggle: () => void;
|
||||
/**
|
||||
* Zooms on canvas viewport center
|
||||
*/
|
||||
zoomCanvas: (
|
||||
/**
|
||||
* Decimal fraction, auto-clamped between MIN_ZOOM and MAX_ZOOM.
|
||||
* 1 = 100% zoom, 2 = 200% zoom, 0.5 = 50% zoom
|
||||
*/
|
||||
value: number) => void;
|
||||
private cancelInProgressAnimation;
|
||||
scrollToContent: (
|
||||
/**
|
||||
* target to scroll to
|
||||
*
|
||||
* - string - id of element or group, or url containing elementLink
|
||||
* - ExcalidrawElement | ExcalidrawElement[] - element(s) objects
|
||||
*/
|
||||
target?: string | ExcalidrawElement | readonly ExcalidrawElement[], opts?: ({
|
||||
fitToContent?: boolean;
|
||||
fitToViewport?: never;
|
||||
viewportZoomFactor?: number;
|
||||
animate?: boolean;
|
||||
duration?: number;
|
||||
} | {
|
||||
fitToContent?: never;
|
||||
fitToViewport?: boolean;
|
||||
/** when fitToViewport=true, how much screen should the content cover,
|
||||
* between 0.1 (10%) and 1 (100%)
|
||||
*/
|
||||
viewportZoomFactor?: number;
|
||||
animate?: boolean;
|
||||
duration?: number;
|
||||
}) & {
|
||||
minZoom?: number;
|
||||
maxZoom?: number;
|
||||
canvasOffsets?: Offsets;
|
||||
}) => void;
|
||||
private maybeUnfollowRemoteUser;
|
||||
/** use when changing scrollX/scrollY/zoom based on user interaction */
|
||||
private translateCanvas;
|
||||
setForceRenderAllEmbeddables: (force: boolean) => void;
|
||||
zoomToFit: (target?: readonly ExcalidrawElement[], maxZoom?: number, //null will zoom to max based on viewport
|
||||
margin?: number) => void;
|
||||
getColorAtScenePoint: ({ sceneX, sceneY, }: {
|
||||
sceneX: number;
|
||||
sceneY: number;
|
||||
}) => string | null;
|
||||
startLineEditor: (el: ExcalidrawLinearElement, selectedPointsIndices?: number[] | null) => void;
|
||||
refreshAllArrows: () => void;
|
||||
updateContainerSize: (containers: NonDeletedExcalidrawElement[]) => void;
|
||||
setToast: (toast: {
|
||||
message: string;
|
||||
closable?: boolean;
|
||||
duration?: number;
|
||||
} | null) => void;
|
||||
restoreFileFromShare: () => Promise<void>;
|
||||
/**
|
||||
* adds supplied files to existing files in the appState.
|
||||
* NOTE if file already exists in editor state, the file data is not updated
|
||||
* */
|
||||
addFiles: ExcalidrawImperativeAPI["addFiles"];
|
||||
setMobileModeAllowed: (allow: boolean) => void;
|
||||
private debounceClearHighlightSearchResults;
|
||||
selectElements: ExcalidrawImperativeAPI["selectElements"];
|
||||
bringToFront: ExcalidrawImperativeAPI["bringToFront"];
|
||||
bringForward: ExcalidrawImperativeAPI["bringForward"];
|
||||
sendToBack: ExcalidrawImperativeAPI["sendToBack"];
|
||||
sendBackward: ExcalidrawImperativeAPI["sendBackward"];
|
||||
private addMissingFiles;
|
||||
updateScene: <K extends keyof AppState>(sceneData: {
|
||||
elements?: SceneData["elements"];
|
||||
appState?: Pick<AppState, K> | null;
|
||||
collaborators?: SceneData["collaborators"];
|
||||
/**
|
||||
* Controls which updates should be captured by the `Store`. Captured updates are emmitted and listened to by other components, such as `History` for undo / redo purposes.
|
||||
*
|
||||
* - `CaptureUpdateAction.IMMEDIATELY`: Updates are immediately undoable. Use for most local updates.
|
||||
* - `CaptureUpdateAction.NEVER`: Updates never make it to undo/redo stack. Use for remote updates or scene initialization.
|
||||
* - `CaptureUpdateAction.EVENTUALLY`: Updates will be eventually be captured as part of a future increment.
|
||||
*
|
||||
* Check [API docs](https://docs.excalidraw.com/docs/@excalidraw/excalidraw/api/props/excalidraw-api#captureUpdate) for more details.
|
||||
*
|
||||
* @default CaptureUpdateAction.EVENTUALLY
|
||||
*/
|
||||
captureUpdate?: SceneData["captureUpdate"];
|
||||
forceFlushSync?: boolean;
|
||||
}) => void;
|
||||
applyDeltas: (deltas: StoreDelta[], options?: ApplyToOptions) => [SceneElementsMap, AppState, boolean];
|
||||
mutateElement: <TElement extends Mutable<ExcalidrawElement>>(element: TElement, updates: ElementUpdate<TElement>, informMutation?: boolean) => TElement;
|
||||
private triggerRender;
|
||||
/**
|
||||
* @returns whether the menu was toggled on or off
|
||||
*/
|
||||
toggleSidebar: ({ name, tab, force, }: {
|
||||
name: SidebarName | null;
|
||||
tab?: SidebarTabName;
|
||||
force?: boolean;
|
||||
}) => boolean;
|
||||
private updateCurrentCursorPosition;
|
||||
getEditorUIOffsets: () => Offsets;
|
||||
private onKeyDown;
|
||||
private onKeyUp;
|
||||
private isToolSupported;
|
||||
setActiveTool: (tool: ({
|
||||
type: ToolType;
|
||||
} | {
|
||||
type: "custom";
|
||||
customType: string;
|
||||
}) & {
|
||||
locked?: boolean;
|
||||
fromSelection?: boolean;
|
||||
}, keepSelection?: boolean) => void;
|
||||
setOpenDialog: (dialogType: AppState["openDialog"]) => void;
|
||||
private setCursor;
|
||||
private resetCursor;
|
||||
/**
|
||||
* returns whether user is making a gesture with >= 2 fingers (points)
|
||||
* on o touch screen (not on a trackpad). Currently only relates to Darwin
|
||||
* (iOS/iPadOS,MacOS), but may work on other devices in the future if
|
||||
* GestureEvent is standardized.
|
||||
*/
|
||||
private isTouchScreenMultiTouchGesture;
|
||||
getName: () => string;
|
||||
private onGestureStart;
|
||||
private onGestureChange;
|
||||
private onGestureEnd;
|
||||
private handleTextWysiwyg;
|
||||
private deselectElements;
|
||||
private getTextElementAtPosition;
|
||||
private getElementAtPosition;
|
||||
private getElementsAtPosition;
|
||||
getElementHitThreshold(element: ExcalidrawElement): number;
|
||||
private hitElement;
|
||||
private getTextBindableContainerAtPosition;
|
||||
private startTextEditing;
|
||||
private debounceDoubleClickTimestamp;
|
||||
private startImageCropping;
|
||||
private finishImageCropping;
|
||||
private handleCanvasDoubleClick;
|
||||
private getElementLinkAtPosition;
|
||||
private redirectToLink;
|
||||
private getTopLayerFrameAtSceneCoords;
|
||||
private handleCanvasPointerMove;
|
||||
private handleEraser;
|
||||
private handleTouchMove;
|
||||
handleHoverSelectedLinearElement(linearElementEditor: LinearElementEditor, scenePointerX: number, scenePointerY: number): void;
|
||||
private handleCanvasPointerDown;
|
||||
private handleCanvasPointerUp;
|
||||
private maybeOpenContextMenuAfterPointerDownOnTouchDevices;
|
||||
private resetContextMenuTimer;
|
||||
/**
|
||||
* pointerup may not fire in certian cases (user tabs away...), so in order
|
||||
* to properly cleanup pointerdown state, we need to fire any hanging
|
||||
* pointerup handlers manually
|
||||
*/
|
||||
private maybeCleanupAfterMissingPointerUp;
|
||||
handleCanvasPanUsingWheelOrSpaceDrag: (event: React.PointerEvent<HTMLElement> | MouseEvent) => boolean;
|
||||
private startRightClickPanning;
|
||||
private updateGestureOnPointerDown;
|
||||
private initialPointerDownState;
|
||||
private handleDraggingScrollBar;
|
||||
private clearSelectionIfNotUsingSelection;
|
||||
/**
|
||||
* @returns whether the pointer event has been completely handled
|
||||
*/
|
||||
private handleSelectionOnPointerDown;
|
||||
private isASelectedElement;
|
||||
private isHittingCommonBoundingBoxOfSelectedElements;
|
||||
private handleTextOnPointerDown;
|
||||
private handleFreeDrawElementOnPointerDown;
|
||||
insertIframeElement: ({ sceneX, sceneY, width, height, }: {
|
||||
sceneX: number;
|
||||
sceneY: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}) => NonDeleted<ExcalidrawIframeElement>;
|
||||
insertEmbeddableElement: ({ sceneX, sceneY, link, }: {
|
||||
sceneX: number;
|
||||
sceneY: number;
|
||||
link: string;
|
||||
}) => NonDeleted<ExcalidrawEmbeddableElement> | undefined;
|
||||
private newImagePlaceholder;
|
||||
private handleLinearElementOnPointerDown;
|
||||
private getCurrentItemRoundness;
|
||||
private createGenericElementOnPointerDown;
|
||||
private createFrameElementOnPointerDown;
|
||||
private maybeCacheReferenceSnapPoints;
|
||||
private maybeCacheVisibleGaps;
|
||||
private onKeyDownFromPointerDownHandler;
|
||||
private onKeyUpFromPointerDownHandler;
|
||||
private onPointerMoveFromPointerDownHandler;
|
||||
private handlePointerMoveOverScrollbars;
|
||||
private onPointerUpFromPointerDownHandler;
|
||||
private restoreReadyToEraseElements;
|
||||
private eraseElements;
|
||||
private initializeImage;
|
||||
/**
|
||||
* use during async image initialization,
|
||||
* when the placeholder image could have been modified in the meantime,
|
||||
* and when you don't want to loose those modifications
|
||||
*/
|
||||
private getLatestInitializedImageElement;
|
||||
private onImageToolbarButtonClick;
|
||||
private getImageNaturalDimensions;
|
||||
/** updates image cache, refreshing updated elements and/or setting status
|
||||
to error for images that fail during <img> element creation */
|
||||
private updateImageCache;
|
||||
/** adds new images to imageCache and re-renders if needed */
|
||||
private addNewImagesToImageCache;
|
||||
/** generally you should use `addNewImagesToImageCache()` directly if you need
|
||||
* to render new images. This is just a failsafe */
|
||||
private scheduleImageRefresh;
|
||||
private updateBindingEnabledOnPointerMove;
|
||||
setSelection(elements: readonly NonDeletedExcalidrawElement[]): void;
|
||||
private clearSelection;
|
||||
private handleInteractiveCanvasRef;
|
||||
private insertImages;
|
||||
private handleAppOnDrop;
|
||||
loadFileToCanvas: (file: File, fileHandle: FileSystemHandle | null) => Promise<void>;
|
||||
private handleCanvasContextMenu;
|
||||
private maybeDragNewGenericElement;
|
||||
private maybeHandleCrop;
|
||||
private maybeHandleResize;
|
||||
private getContextMenuItems;
|
||||
private handleWheel;
|
||||
private getTextWysiwygSnappedToCenterPosition;
|
||||
private savePointer;
|
||||
private resetShouldCacheIgnoreZoomDebounced;
|
||||
private updateDOMRect;
|
||||
refresh: () => void;
|
||||
private getCanvasOffsets;
|
||||
watchState: () => void;
|
||||
private updateLanguage;
|
||||
}
|
||||
export default App;
|
||||
|
||||
```
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,45 @@
|
||||
async function compress () {
|
||||
ea = ExcalidrawAutomate;
|
||||
const f = app.workspace.activeLeaf.view.file;
|
||||
const data = await app.vault.read(f);
|
||||
const compressed = ea.compressToBase64(data);
|
||||
let result = '';
|
||||
const chunkSize = 256;
|
||||
for (let i = 0; i < compressed.length; i += chunkSize) {
|
||||
result += compressed.slice(i, i + chunkSize) + '\n\n';
|
||||
}
|
||||
|
||||
await app.vault.modify(f,`/*
|
||||
# Mind Map Builder: Technical Specification & User Guide
|
||||
|
||||
## Overview
|
||||
**Mind Map Builder** transforms the Obsidian-Excalidraw canvas into a rapid brainstorming environment, allowing users to build complex, structured, and visually organized mind maps using primarily keyboard shortcuts.
|
||||
|
||||
The script balances **automation** (auto-layout, recursive grouping, and contrast-aware coloring) with **explicit flexibility** (node pinning and redirection logic), ensuring that the mind map stays organized even as it grows to hundreds of nodes. It leverages the Excalidraw Sidepanel API to provide a persistent control interface utilizing the Obsidian sidepanel, that can also be undocked into a floating modal.
|
||||
|
||||
> [!Note]
|
||||
> Mindmap Builder is Minified for reasons of size and performance. You can find the source here: [Mindmap Builder.js](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Mindmap%20Builder.js)
|
||||
|
||||
\`\`\`js*/
|
||||
if (!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.19.0")) {
|
||||
new Notice("Please update the Excalidraw Plugin to version 2.19.0 or higher.");
|
||||
return;
|
||||
}
|
||||
|
||||
const existingTab = ea.checkForActiveSidepanelTabForScript();
|
||||
if (existingTab) {
|
||||
const hostEA = existingTab.getHostEA();
|
||||
if (hostEA && hostEA !== ea) {
|
||||
hostEA.activateMindmap = true;
|
||||
hostEA.setView(ea.targetView);
|
||||
existingTab.open();
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
const mmbSource = \`${result}\`;
|
||||
const script = ea.decompressFromBase64(mmbSource.replaceAll("\\n", "").trim())
|
||||
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
|
||||
await new AsyncFunction("ea", "utils", script)(ea, utils);
|
||||
`);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+623
-3085
File diff suppressed because it is too large.
Load diff
@@ -1 +1 @@
|
||||
[{"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":1748189277Line truncated
|
||||
@@ -470,7 +470,7 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
|
||||
```excalidraw-script-install
|
||||
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20Builder.md
|
||||
```
|
||||
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/zsviczian'>@zsviczian</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Mindmap%20Builder.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Rapid mind mapping workflow driven by keyboard shortcuts: add sibling/child nodes, auto-layout and branch styling, quick navigation, optional recursive grouping, and Markdown copy/paste import/export for bullet-list sync.<br><a href="https://www.youtube.com/watch?v=qY66yoobaX4" target="_blank"><img src ="https://i.ytimg.com/vi/qY66yoobaX4/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/qY66yoobaX4' target='_blank'>Link to video on YouTube</a><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-mindmap-builder.png'></td></tr></table>
|
||||
<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/Mindmap%20Builder.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Rapid mind mapping workflow driven by keyboard shortcuts: add sibling/child nodes, auto-layout and branch styling, quick navigation, optional recursive grouping, and Markdown copy/paste import/export for bullet-list sync.Sign up for the <a href="https://visual-thinking-workshop.com/mindmap" target="_blank">MindMap Builder Self-Paced Course</a>!<br><a href="https://www.youtube.com/watch?v=qY66yoobaX4" target="_blank"><img src ="https://i.ytimg.com/vi/qY66yoobaX4/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/qY66yoobaX4' target='_blank'>Link to video on YouTube</a><br><a href="https://www.youtube.com/watch?v=5G9QF-u9w0Q" target="_blank"><img src ="https://i.ytimg.com/vi/5G9QF-u9w0Q/maxresdefault.jpg" style="width:400px;"></a><br><a href='https://youtu.be/5G9QF-u9w0Q' target='_blank'>Link to video on YouTube</a><br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-mindmap-builder.png'></td></tr></table>
|
||||
|
||||
## Mindmap connector
|
||||
```excalidraw-script-install
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.19.1",
|
||||
"version": "2.20.0-beta-2",
|
||||
"minAppVersion": "1.5.7",
|
||||
"description": "Sketch Your Mind. An Obsidian plugin to edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.19.1",
|
||||
"version": "2.19.2",
|
||||
"minAppVersion": "1.5.7",
|
||||
"description": "Sketch Your Mind. An Obsidian plugin to edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
Generated
+1014
-1114
File diff suppressed because it is too large.
Load diff
+3
-2
@@ -17,14 +17,15 @@
|
||||
"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"
|
||||
"doc": "npm run lib && node scripts/generate-script-library.js",
|
||||
"mindmap": "node scripts/deploy-mindmap-builder.js"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@zsviczian/excalidraw": "0.18.0-67",
|
||||
"@zsviczian/excalidraw": "0.18.0-69",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
const path = require("path");
|
||||
const fs = require("fs/promises");
|
||||
const { minify } = require("uglify-js");
|
||||
const LZString = require("lz-string");
|
||||
|
||||
const CHUNK_SIZE = 256;
|
||||
const NEEDLE = "const removeKeydownHandlers";
|
||||
|
||||
const root = path.resolve(__dirname, "..");
|
||||
const sourcePath = path.join(root, "ea-scripts", "Mindmap Builder.js");
|
||||
const outputPath = path.join(root, "ea-scripts", "Mindmap Builder.md");
|
||||
|
||||
const HEADER = `/*
|
||||
|
||||
# Mind Map Builder
|
||||
|
||||

|
||||
|
||||
## Overview
|
||||
**Mind Map Builder** transforms the Obsidian-Excalidraw canvas into a rapid brainstorming environment, allowing users to build complex, structured, and visually organized mind maps using primarily keyboard shortcuts.
|
||||
|
||||
The script balances **automation** (auto-layout, recursive grouping, and contrast-aware coloring) with **explicit flexibility** (node pinning and redirection logic), ensuring that the mind map stays organized even as it grows to hundreds of nodes. It leverages the Excalidraw Sidepanel API to provide a persistent control interface utilizing the Obsidian sidepanel, that can also be undocked into a floating modal.
|
||||
|
||||
> [!Tip]
|
||||
> 🚀 Become a MindMap Builder Pro with the Official [MindMap Builder Course](https://www.visual-thinking-workshop.com/mindmap)!
|
||||
|
||||
> [!Info]
|
||||
> Mindmap Builder is Minified and compressed to reduce size and improve performance. You can find the source here: [Mindmap Builder.js](https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Mindmap%20Builder.js)
|
||||
|
||||
## Show Your Love!
|
||||
|
||||
💖 **If you love MindMap Builder** say thank you, and [Buy me a Coffee](https://ko-fi.com/zsolt) 🍵
|
||||
|
||||
## The Script
|
||||
|
||||
\`\`\`js*/
|
||||
`;
|
||||
|
||||
const FOOTER = `
|
||||
const VERSION = "v${new Date().toISOString().slice(2, 10).replace(/-/g, ".")}";
|
||||
|
||||
if (!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.19.1")) {
|
||||
new Notice("Please update the Excalidraw Plugin to version 2.19.1 or higher.");
|
||||
return;
|
||||
}
|
||||
|
||||
const existingTab = ea.checkForActiveSidepanelTabForScript();
|
||||
if (existingTab) {
|
||||
const hostEA = existingTab.getHostEA();
|
||||
if (hostEA && hostEA !== ea) {
|
||||
hostEA.activateMindmap = true;
|
||||
hostEA.setView(ea.targetView);
|
||||
existingTab.open();
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
const mmbSource = \`
|
||||
`;
|
||||
|
||||
const FOOTER_TAIL = `\`;
|
||||
const script = ea.decompressFromBase64(mmbSource.replaceAll("\\n", "").trim())
|
||||
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
|
||||
await new AsyncFunction("ea", "utils", "VERSION", script)(ea, utils, VERSION);
|
||||
`;
|
||||
|
||||
function chunkString(input, size) {
|
||||
const chunks = [];
|
||||
for (let i = 0; i < input.length; i += size) {
|
||||
chunks.push(input.slice(i, i + size));
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
function stripHeader(source) {
|
||||
const idx = source.indexOf(NEEDLE);
|
||||
if (idx === -1) {
|
||||
throw new Error(`Marker "${NEEDLE}" not found in Mindmap Builder.js`);
|
||||
}
|
||||
return source.slice(idx);
|
||||
}
|
||||
|
||||
function wrapAsyncIIFE(body) {
|
||||
return `(async()=>{\n${body}\n})()`;
|
||||
}
|
||||
|
||||
function minifyCode(source) {
|
||||
const result = minify(source, {
|
||||
compress: { passes: 3 },
|
||||
mangle: true,
|
||||
output: { ascii_only: true }
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
throw result.error;
|
||||
}
|
||||
|
||||
return result.code;
|
||||
}
|
||||
|
||||
function unwrapAsyncIIFE(minified) {
|
||||
const match = minified.match(/^\(async\(\)=>\{([\s\S]*)\}\)\(\);?$/);
|
||||
if (!match) {
|
||||
throw new Error("Unable to strip async IIFE wrapper from minified output");
|
||||
}
|
||||
return match[1];
|
||||
}
|
||||
|
||||
function compressBase64(text) {
|
||||
return LZString.compressToBase64(text);
|
||||
}
|
||||
|
||||
function formatCompressed(compressed) {
|
||||
return chunkString(compressed, CHUNK_SIZE).join("\n\n");
|
||||
}
|
||||
|
||||
async function generate() {
|
||||
const raw = await fs.readFile(sourcePath, "utf8");
|
||||
const body = stripHeader(raw).trim();
|
||||
const wrapped = wrapAsyncIIFE(body);
|
||||
const minified = minifyCode(wrapped);
|
||||
const unwrapped = unwrapAsyncIIFE(minified);
|
||||
const compressed = compressBase64(unwrapped);
|
||||
const formatted = formatCompressed(compressed);
|
||||
|
||||
const output = `${HEADER}${FOOTER}${formatted}${FOOTER_TAIL}`;
|
||||
await fs.writeFile(outputPath, output, "utf8");
|
||||
console.log(`Mindmap Builder.md generated at ${outputPath}`);
|
||||
}
|
||||
|
||||
generate().catch((err) => {
|
||||
console.error(err);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -261,6 +261,8 @@ const TYPE_DEF_WHITELIST = [
|
||||
"lib/types/AIUtilTypes.d.ts",
|
||||
"node_modules/@zsviczian/excalidraw/types/element/src/types.d.ts",
|
||||
"node_modules/@zsviczian/excalidraw/types/excalidraw/types.d.ts",
|
||||
"node_modules/@zsviczian/excalidraw/types/element/src/bounds.d.ts",
|
||||
"node_modules/@zsviczian/excalidraw/types/excalidraw/components/App.d.ts",
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -552,8 +554,9 @@ function main() {
|
||||
.filter(
|
||||
(d) =>
|
||||
d.isFile() &&
|
||||
d.name.endsWith('.md') &&
|
||||
d.name.toLowerCase() !== 'index-new.md'
|
||||
(d.name.endsWith('.md') || d.name.toLowerCase() === "mindmap builder.js") &&
|
||||
d.name.toLowerCase() !== 'index-new.md' &&
|
||||
d.name.toLowerCase() !== 'mindmap builder.md'
|
||||
)
|
||||
.map((d) => d.name)
|
||||
.sort((a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' }));
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
export const TAG_PDFEXPORT = "PDFExport";
|
||||
export const TAG_MDREADINGMODE = "MDReadingMode";
|
||||
export const TAG_AUTOEXPORT = "Autoexport";
|
||||
export const TAG_AUTOEXPORT = "Autoexport";
|
||||
export const TAG_IMAGECACHE = "ResetImageCache";
|
||||
@@ -97,7 +97,7 @@ export let {
|
||||
exportToSvg,
|
||||
exportToBlob,
|
||||
mutateElement,
|
||||
restore,
|
||||
restoreElements,
|
||||
mermaidToExcalidraw,
|
||||
getFontFamilyString,
|
||||
getContainerElement,
|
||||
@@ -124,7 +124,7 @@ export function updateExcalidrawLib() {
|
||||
'getCommonBoundingBox',
|
||||
'measureText',
|
||||
'getLineHeight',
|
||||
'restore'
|
||||
'restoreElements'
|
||||
];
|
||||
|
||||
for (const fnName of requiredFunctions) {
|
||||
@@ -148,7 +148,7 @@ export function updateExcalidrawLib() {
|
||||
exportToSvg,
|
||||
exportToBlob,
|
||||
mutateElement,
|
||||
restore,
|
||||
restoreElements,
|
||||
mermaidToExcalidraw,
|
||||
getFontFamilyString,
|
||||
getContainerElement,
|
||||
@@ -214,7 +214,7 @@ export const ROUNDNESS = { //should at one point publish @zsviczian/excalidraw/t
|
||||
PROPORTIONAL_RADIUS: 2,
|
||||
ADAPTIVE_RADIUS: 3,
|
||||
} as const;
|
||||
export const THEME_FILTER = "invert(100%) hue-rotate(180deg) saturate(1.25)";
|
||||
export const THEME_FILTER = "invert(93%) hue-rotate(180deg) saturate(1.25)";
|
||||
export const GITHUB_RELEASES = "https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/";
|
||||
export const URLFETCHTIMEOUT = 3000;
|
||||
export const PLUGIN_ID = "obsidian-excalidraw-plugin";
|
||||
|
||||
@@ -773,6 +773,26 @@ export default class ExcalidrawPlugin extends Plugin {
|
||||
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 as TFile).basename}`);
|
||||
} catch (e) {
|
||||
new Notice(`Error installing script: ${fname}`);
|
||||
|
||||
@@ -8,6 +8,7 @@ import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { DEVICE, FRONTMATTER_KEYS, ICON_NAME, VIEW_TYPE_EXCALIDRAW } from "src/constants/constants";
|
||||
import ExcalidrawView from "src/view/ExcalidrawView";
|
||||
import { t } from "src/lang/helpers";
|
||||
import { setMobileNavbarPosition } from "src/utils/excalidrawViewUtils";
|
||||
|
||||
/**
|
||||
* Registers event listeners for the plugin
|
||||
@@ -234,22 +235,7 @@ export class EventManager {
|
||||
this.plugin.removeModalContainerObserver();
|
||||
}
|
||||
|
||||
//!Temporary hack
|
||||
//https://discord.com/channels/686053708261228577/817515900349448202/1031101635784613968
|
||||
if (DEVICE.isMobile && newActiveviewEV && !previouslyActiveEV) {
|
||||
const navbar = document.querySelector("body>.app-container>.mobile-navbar");
|
||||
if(navbar && navbar instanceof HTMLDivElement) {
|
||||
navbar.style.position="relative";
|
||||
}
|
||||
}
|
||||
|
||||
if (DEVICE.isMobile && !newActiveviewEV && previouslyActiveEV) {
|
||||
const navbar = document.querySelector("body>.app-container>.mobile-navbar");
|
||||
if(navbar && navbar instanceof HTMLDivElement) {
|
||||
navbar.style.position="";
|
||||
}
|
||||
}
|
||||
|
||||
setMobileNavbarPosition(newActiveviewEV && !previouslyActiveEV);
|
||||
//----------------------
|
||||
//----------------------
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ export class PackageManager {
|
||||
return (
|
||||
typeof lib === 'object' &&
|
||||
lib !== null &&
|
||||
typeof lib.restore === 'function' &&
|
||||
typeof lib.restoreElements === 'function' &&
|
||||
typeof lib.exportToSvg === 'function'
|
||||
);
|
||||
}
|
||||
|
||||
+72
-6
@@ -2,6 +2,7 @@ import {
|
||||
App,
|
||||
ButtonComponent,
|
||||
DropdownComponent,
|
||||
ExtraButtonComponent,
|
||||
getIcon,
|
||||
Modifier,
|
||||
normalizePath,
|
||||
@@ -10,7 +11,7 @@ import {
|
||||
TextComponent,
|
||||
TFile,
|
||||
} from "obsidian";
|
||||
import { GITHUB_RELEASES, setRootElementSize } from "src/constants/constants";
|
||||
import { GITHUB_RELEASES, setRootElementSize, THEME_FILTER } from "src/constants/constants";
|
||||
import { t } from "src/lang/helpers";
|
||||
import type ExcalidrawPlugin from "src/core/main";
|
||||
import { PenStyle } from "src/types/penTypes";
|
||||
@@ -38,7 +39,7 @@ import { ANNOTATED_PREFIX, CROPPED_PREFIX } from "src/utils/carveout";
|
||||
import { EDITOR_FADEOUT } from "src/core/editor/EditorHandler";
|
||||
import { setDebugging } from "src/utils/debugHelper";
|
||||
import { Rank } from "src/constants/actionIcons";
|
||||
import { TAG_AUTOEXPORT, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
|
||||
import { TAG_AUTOEXPORT, TAG_IMAGECACHE, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
|
||||
import { HotkeyEditor } from "src/shared/Dialogs/HotkeyEditor";
|
||||
import { getExcalidrawViews } from "src/utils/obsidianUtils";
|
||||
import { createSliderWithText } from "src/utils/sliderUtils";
|
||||
@@ -48,6 +49,9 @@ import { UIMode, UIModeSettingsComponent } from "src/shared/Dialogs/UIModeSettin
|
||||
import { ScriptSettingValue } from "src/types/excalidrawAutomateTypes";
|
||||
|
||||
export interface ExcalidrawSettings {
|
||||
invertSVGforDarkMode: boolean;
|
||||
invertBitmapforDarkMode: boolean;
|
||||
themeFilter: string;
|
||||
copyLinkToElemenetAnchorTo100: boolean;
|
||||
copyFrameLinkByName: boolean;
|
||||
disableDoubleClickTextEditing: boolean;
|
||||
@@ -239,6 +243,9 @@ export interface ExcalidrawSettings {
|
||||
declare const PLUGIN_VERSION:string;
|
||||
|
||||
export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
invertSVGforDarkMode: true,
|
||||
invertBitmapforDarkMode: false,
|
||||
themeFilter: THEME_FILTER,
|
||||
copyLinkToElemenetAnchorTo100: false,
|
||||
copyFrameLinkByName: false,
|
||||
disableDoubleClickTextEditing: false,
|
||||
@@ -429,10 +436,10 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
|
||||
startupScriptPath: "",
|
||||
aiEnabled: true,
|
||||
openAIAPIToken: "",
|
||||
openAIDefaultTextModel: "gpt-3.5-turbo-1106",
|
||||
openAIDefaultTextModel: "gpt-5-mini",
|
||||
openAIDefaultTextModelMaxTokens: 4096,
|
||||
openAIDefaultVisionModel: "gpt-4o",
|
||||
openAIDefaultImageGenerationModel: "dall-e-3",
|
||||
openAIDefaultVisionModel: "gpt-5-mini",
|
||||
openAIDefaultImageGenerationModel: "gpt-image-1",
|
||||
openAIURL: "https://api.openai.com/v1/chat/completions",
|
||||
openAIImageGenerationURL: "https://api.openai.com/v1/images/generations",
|
||||
openAIImageEditsURL: "https://api.openai.com/v1/images/edits",
|
||||
@@ -2223,7 +2230,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
}
|
||||
});
|
||||
|
||||
new Setting(detailsEl)
|
||||
const embedImageCacheSetting = new Setting(detailsEl)
|
||||
.setName(t("EMBED_IMAGE_CACHE_NAME"))
|
||||
.setDesc(fragWithHTML(t("EMBED_IMAGE_CACHE_DESC")))
|
||||
.addToggle((toggle) =>
|
||||
@@ -2234,6 +2241,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
this.applySettingsUpdate();
|
||||
})
|
||||
)
|
||||
embedImageCacheSetting.controlEl.setAttribute("id",TAG_IMAGECACHE);
|
||||
new Setting(detailsEl)
|
||||
.setName(t("SCENE_IMAGE_CACHE_NAME"))
|
||||
.setDesc(fragWithHTML(t("SCENE_IMAGE_CACHE_DESC")))
|
||||
@@ -2416,6 +2424,64 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
|
||||
this.applySettingsUpdate();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("EMBED_INVERT_SVG"))
|
||||
.setDesc(fragWithHTML(t("EMBED_INVERT_SVG_DESC")))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(this.plugin.settings.invertSVGforDarkMode)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.invertSVGforDarkMode = value;
|
||||
this.applySettingsUpdate();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(detailsEl)
|
||||
.setName(t("EMBED_INVERT_BITMAP"))
|
||||
.setDesc(fragWithHTML(t("EMBED_INVERT_BITMAP_DESC")))
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(this.plugin.settings.invertBitmapforDarkMode)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.invertBitmapforDarkMode = value;
|
||||
this.applySettingsUpdate();
|
||||
}),
|
||||
);
|
||||
|
||||
let themeFilterSettingText:TextComponent;
|
||||
let themeFilterResetButton:ExtraButtonComponent;
|
||||
new Setting(detailsEl)
|
||||
.setName(t("EMBED_THEME_FILTER_NAME"))
|
||||
.setDesc(fragWithHTML(t("EMBED_THEME_FILTER_DESC")))
|
||||
.addText((text) => {
|
||||
themeFilterSettingText = text;
|
||||
text
|
||||
.setPlaceholder("e.g.: brightness(0.9) contrast(1.2)")
|
||||
.setValue(this.plugin.settings.themeFilter)
|
||||
.onChange(async (value) => {
|
||||
this.plugin.settings.themeFilter = value;
|
||||
this.applySettingsUpdate();
|
||||
if (value !== THEME_FILTER) {
|
||||
themeFilterResetButton.extraSettingsEl.style.display = "";
|
||||
}
|
||||
})
|
||||
})
|
||||
.addExtraButton((btn) => {
|
||||
themeFilterResetButton = btn;
|
||||
btn
|
||||
.setIcon("rotate-ccw")
|
||||
.setTooltip(t("RESET")!)
|
||||
.onClick(() => {
|
||||
themeFilterSettingText.setValue(THEME_FILTER);
|
||||
this.plugin.settings.themeFilter = THEME_FILTER;
|
||||
themeFilterResetButton.extraSettingsEl.style.display = "none";
|
||||
this.applySettingsUpdate();
|
||||
})
|
||||
});
|
||||
if(this.plugin.settings.themeFilter === THEME_FILTER) {
|
||||
themeFilterResetButton.extraSettingsEl.style.display = "none";
|
||||
}
|
||||
|
||||
detailsEl = exportDetailsEl.createEl("details");
|
||||
detailsEl.createEl("summary", {
|
||||
|
||||
+12
-6
@@ -3,7 +3,7 @@ import {
|
||||
FRONTMATTER_KEYS,
|
||||
CJK_FONTS,
|
||||
} from "src/constants/constants";
|
||||
import { TAG_AUTOEXPORT, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
|
||||
import { TAG_AUTOEXPORT, TAG_IMAGECACHE, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
|
||||
import { labelALT, labelCTRL, labelMETA, labelSHIFT } from "src/utils/modifierkeyHelper";
|
||||
|
||||
declare const PLUGIN_VERSION:string;
|
||||
@@ -315,17 +315,16 @@ export default {
|
||||
AI_OPENAI_DEFAULT_MODEL_DESC:
|
||||
"The default AI model to use when generating text. This is a freetext field, so you can enter any valid OpenAI model name. " +
|
||||
"Find out more about the available models on the <a href='https://platform.openai.com/docs/models'>OpenAI website</a>.",
|
||||
AI_OPENAI_DEFAULT_MODEL_PLACEHOLDER: "Enter your default AI model here. e.g.: gpt-3.5-turbo-1106",
|
||||
AI_OPENAI_DEFAULT_MODEL_PLACEHOLDER: "Enter your default AI model here. e.g.: gpt-5-mini",
|
||||
AI_OPENAI_DEFAULT_MAX_TOKENS_NAME: "Max tokens",
|
||||
AI_OPENAI_DEFAULT_MAX_TOKENS_DESC:
|
||||
"Maximum number of tokens to generate in the API response. Set to 0 to omit the max_tokens field (useful for models that don't support this parameter, such as GPT-5).",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_NAME: "Default Image Generation AI model",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_DESC:
|
||||
"The default AI model to use when generating images. Image editing and variations are only supported by dall-e-2 at this time by OpenAI, " +
|
||||
"for this reason dall-e-2 will automatically be used in such cases regardless of this setting.<br>" +
|
||||
"The default AI model to use when generating images. Image editing and variations are only supported by dall-e-2 and gpt-image-1 at this time by OpenAI.<br>" +
|
||||
"This is a freetext field, so you can enter any valid OpenAI model name. " +
|
||||
"Find out more about the available models on the <a href='https://platform.openai.com/docs/models'>OpenAI website</a>.",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "Enter your default Image Generation AI model here e.g.: dall-e-3",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "Enter your default Image Generation AI model here e.g.: gpt-image-1",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_NAME: "Default AI vision model",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_DESC:
|
||||
"The default AI vision model to use when generating text from images. This is a freetext field, so you can enter any valid OpenAI model name. " +
|
||||
@@ -335,7 +334,7 @@ export default {
|
||||
"The default OpenAI API URL. This is a freetext field, so you can enter any valid OpenAI API compatible URL. " +
|
||||
"Excalidraw will use this URL when posting API requests to OpenAI. I am not doing any error handling on this field, so make sure you enter a valid URL and only change this if you know what you are doing. ",
|
||||
AI_OPENAI_DEFAULT_IMAGE_API_URL_NAME: "OpenAI Image Generation API URL",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_PLACEHOLDER: "Enter your default AI vision model here. e.g.: gpt-4o",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_PLACEHOLDER: "Enter your default AI vision model here. e.g.: gpt-5-mini",
|
||||
SAVING_HEAD: "Saving",
|
||||
SAVING_DESC: "In the 'Saving' section of Excalidraw Settings, you can configure how your drawings are saved. This includes options for compressing Excalidraw JSON in Markdown, setting autosave intervals for both desktop and mobile, defining filename formats, and choosing whether to use the .excalidraw.md or .md file extension. ",
|
||||
COMPRESS_NAME: "Compress Excalidraw JSON in Markdown",
|
||||
@@ -689,6 +688,13 @@ export default {
|
||||
EMBED_IMAGE_CACHE_NAME: "Cache images for embedding in markdown",
|
||||
EMBED_IMAGE_CACHE_DESC: "Cache images for embedding in markdown. This will speed up the embedding process, but in case you compose images of several sub-component drawings, " +
|
||||
"the embedded image in Markdown won't update until you open the drawing and save it to trigger an update of the cache.",
|
||||
EMBED_INVERT_SVG: "Invert embedded Excalidraw drawings and SVG images in dark mode",
|
||||
EMBED_INVERT_SVG_DESC: "The change will only take affect when you reopen your drawing. When changing this setting, you may need to clear the <a href='#"+TAG_IMAGECACHE+"'>image cache</a>. This is the default for all images; set colorMap.invertInDarkMode to override per image.",
|
||||
EMBED_INVERT_BITMAP: "Invert embedded bitmap images in dark mode",
|
||||
EMBED_INVERT_BITMAP_DESC: "The change will only take affect when you reopen your drawing. When changing this setting, you may need to clear the <a href='#"+TAG_IMAGECACHE+"'>image cache</a>. This is the default for all images; set colorMap.invertInDarkMode to override per image.",
|
||||
EMBED_THEME_FILTER_NAME: "Theme filter for color inversion",
|
||||
EMBED_THEME_FILTER_DESC: "Modify this only if you know what you are doing. The change will only take affect when you reopen your drawing. When changing this setting, you may need to clear the <a href='#"+TAG_IMAGECACHE+"'>image cache</a>.",
|
||||
RESET: "Reset to default",
|
||||
SCENE_IMAGE_CACHE_NAME: "Cache nested Excalidraws in Scene",
|
||||
SCENE_IMAGE_CACHE_DESC: "Cache nested Excalidraws in the Scene for faster scene rendering. This will speed up the rendering process, especially if you have deeply nested Excalidraws in your scene. " +
|
||||
"Excalidraw will try to intelligently identify if any children of a nested Excalidraw have changed and will update the cache accordingly. " +
|
||||
|
||||
+19
-13
@@ -3,7 +3,7 @@ import {
|
||||
FRONTMATTER_KEYS,
|
||||
CJK_FONTS,
|
||||
} from "src/constants/constants";
|
||||
import { TAG_AUTOEXPORT, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
|
||||
import { TAG_AUTOEXPORT, TAG_IMAGECACHE, TAG_MDREADINGMODE, TAG_PDFEXPORT } from "src/constants/constSettingsTags";
|
||||
import { labelALT, labelCTRL, labelMETA, labelSHIFT } from "src/utils/modifierkeyHelper";
|
||||
|
||||
declare const PLUGIN_VERSION:string;
|
||||
@@ -18,7 +18,7 @@ export default {
|
||||
ZIP_CURRENT_FILE: "压缩当前 Excalidraw 文件",
|
||||
PUBLISH_SVG_CHECK: "Obsidian Publish:搜索过期的 SVG 和 PNG 导出文件",
|
||||
EMBEDDABLE_PROPERTIES: "Embeddable 元素设置",
|
||||
EMBEDDABLE_RELATIVE_ZOOM: "使元素的缩放等级等于当前绘图的缩放等级",
|
||||
EMBEDDABLE_RELATIVE_ZOOM: "使元素的缩放级别等于当前绘图的缩放级别",
|
||||
OPEN_IMAGE_SOURCE: "打开 Excalidraw 绘图",
|
||||
INSTALL_SCRIPT: "安装此脚本",
|
||||
UPDATE_SCRIPT: "有可用更新 - 点击安装",
|
||||
@@ -30,7 +30,7 @@ export default {
|
||||
"脚本已是最新 - 点击重新安装",
|
||||
OPEN_AS_EXCALIDRAW: "打开为 Excalidraw 绘图",
|
||||
TOGGLE_MODE: "在 Excalidraw 和 Markdown 模式之间切换",
|
||||
DUPLICATE_IMAGE: "复制选定的图像,并分配一个不同的图像 ID",
|
||||
DUPLICATE_IMAGE: "复制所选图像,并分配一个不同的图像 ID",
|
||||
CONVERT_NOTE_TO_EXCALIDRAW: "转换:空白 Markdown 文档 => Excalidraw 绘图",
|
||||
CONVERT_EXCALIDRAW: "转换: *.excalidraw => *.md",
|
||||
CREATE_NEW: "新建绘图文件",
|
||||
@@ -298,7 +298,7 @@ export default {
|
||||
SCRIPT_FOLDER_DESC:
|
||||
"此文件夹用于存放 Excalidraw 自动化脚本。" +
|
||||
"您可以在 Obsidian 命令面板中执行这些脚本," +
|
||||
"还可以为喜欢的脚本分配快捷键,就像为其他 Obsidian 命令分配快捷键一样。<br>" +
|
||||
"还可以为喜欢的脚本分配热键,就像为其他 Obsidian 命令分配热键一样。<br>" +
|
||||
"该项不能设为仓库根目录。",
|
||||
AI_HEAD: "AI(实验性)",
|
||||
AI_DESC: `OpenAI GPT API 的设置。` +
|
||||
@@ -315,17 +315,16 @@ export default {
|
||||
AI_OPENAI_DEFAULT_MODEL_DESC:
|
||||
"使用哪个 AI 模型来生成文本。请填写有效的 OpenAI 模型名称。" +
|
||||
"您可访问 <a href='https://platform.openai.com/docs/models'>OpenAI 网站</a> 了解更多模型信息。",
|
||||
AI_OPENAI_DEFAULT_MODEL_PLACEHOLDER: "gpt-3.5-turbo-1106",
|
||||
AI_OPENAI_DEFAULT_MODEL_PLACEHOLDER: "gpt-5-mini",
|
||||
AI_OPENAI_DEFAULT_MAX_TOKENS_NAME: "最大 token 数",
|
||||
AI_OPENAI_DEFAULT_MAX_TOKENS_DESC:
|
||||
"API 响应中生成的最大 token 数。设置为 0 以忽略 max_tokens 字段(适用于不支持该参数的模型,如 GPT-5)。",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_NAME: "默认的图片 AI 模型",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_DESC:
|
||||
"使用哪个 AI 模型来生成图片。图生图会强制使用 dall-e-2 模型," +
|
||||
"因为目前只有该模型支持 Image editing and variations。" +
|
||||
"使用哪个 AI 模型来生成图片。图生图目前只有 dall-e-2 和 gpt-image-1 模型支持 Image editing and variations。" +
|
||||
"请填写有效的 OpenAI 模型名称。" +
|
||||
"您可访问 <a href='https://platform.openai.com/docs/models'>OpenAI 网站</a> 了解更多模型信息。",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "dall-e-3",
|
||||
AI_OPENAI_DEFAULT_IMAGE_MODEL_PLACEHOLDER: "gpt-image-1",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_NAME: "默认的 AI 视觉模型",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_DESC:
|
||||
"根据文本生成图片时,使用哪个 AI 视觉模型。请填写有效的 OpenAI 模型名称。" +
|
||||
@@ -335,7 +334,7 @@ export default {
|
||||
"默认的 OpenAI API URL。请填写有效的 OpenAI API URL。" +
|
||||
"Excalidraw 会通过该 URL 发送 API 请求给 OpenAI。我没有对该项做任何错误处理,请谨慎修改。",
|
||||
AI_OPENAI_DEFAULT_IMAGE_API_URL_NAME: "OpenAI 图片生成 API URL",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_PLACEHOLDER: "输入默认 AI 模型名称,如 gpt-4o",
|
||||
AI_OPENAI_DEFAULT_VISION_MODEL_PLACEHOLDER: "输入默认 AI 模型名称,如 gpt-5-mini",
|
||||
SAVING_HEAD: "保存",
|
||||
SAVING_DESC: "包括:压缩,自动保存的时间间隔,文件的命名格式和扩展名等。",
|
||||
COMPRESS_NAME: "压缩 Excalidraw JSON",
|
||||
@@ -688,7 +687,14 @@ export default {
|
||||
EMBED_THEME_BACKGROUND: "图像的主题和背景色",
|
||||
EMBED_IMAGE_CACHE_NAME: "为嵌入到 Markdown 文档中的绘图创建预览图缓存",
|
||||
EMBED_IMAGE_CACHE_DESC: "可提高下次嵌入的速度。" +
|
||||
"但如果绘图包含子绘图,(当子绘图改变时)您需要打开父绘图并手动保存,才能够更新预览图。",
|
||||
"但如果绘图包含子绘图,(当子绘图改变时)预览图不会更新,直到您打开绘图并手动保存。",
|
||||
EMBED_INVERT_SVG: "深色主题下反转嵌入的 Excalidraw 绘图和 SVG 图像",
|
||||
EMBED_INVERT_SVG_DESC: "重新打开绘图后生效。可能需要配合清除 <a href='#"+TAG_IMAGECACHE+"'>预览图缓存</a>。可为某个图像单独设置 colorMap.invertInDarkMode。",
|
||||
EMBED_INVERT_BITMAP: "深色主题下反转嵌入的位图图像",
|
||||
EMBED_INVERT_BITMAP_DESC: "重新打开绘图后生效。可能需要配合清除 <a href='#"+TAG_IMAGECACHE+"'>预览图缓存</a>。可为某个图像单独设置 colorMap.invertInDarkMode。",
|
||||
EMBED_THEME_FILTER_NAME: "用于颜色反转的主题滤镜",
|
||||
EMBED_THEME_FILTER_DESC: "谨慎修改。重新打开绘图后生效。可能需要配合清除 <a href='#"+TAG_IMAGECACHE+"'>预览图缓存</a>。",
|
||||
RESET: "恢复默认",
|
||||
SCENE_IMAGE_CACHE_NAME: "缓存场景中嵌套的绘图",
|
||||
SCENE_IMAGE_CACHE_DESC: "Excalidraw 将智能地尝试识别嵌套的绘图的子元素是否发生变化,并更新缓存。" +
|
||||
"这将加快渲染过程,特别是在您的场景中有深度嵌套的绘图时。<br>" +
|
||||
@@ -720,7 +726,7 @@ export default {
|
||||
EMBED_WIDTH_NAME: "预览图的默认宽度",
|
||||
EMBED_WIDTH_DESC:
|
||||
"嵌入到 Markdown 文档中的绘图的预览图的默认宽度。该项也适用于鼠标悬停时浮现的预览图。<br>" +
|
||||
"可为某个要嵌入到 Markdown 文档中的绘图文件单独设置," +
|
||||
"可为某个要嵌入到 Markdown 文档中的绘图单独设置," +
|
||||
"方法是修改相应的内部链接格式为如 <code>![[drawing.excalidraw|100]]</code> 或 <code>[[drawing.excalidraw|100x100]]</code>。",
|
||||
EMBED_HEIGHT_NAME: "预览图的默认高度",
|
||||
EMBED_HEIGHT_DESC:
|
||||
@@ -1026,7 +1032,7 @@ export default {
|
||||
ES_FILENAME_VISIBLE: "显示页内标题",
|
||||
ES_BACKGROUND_HEAD: "背景色",
|
||||
ES_BACKGROUND_DESC_INFO: "点击此处查看更多颜色信息",
|
||||
ES_BACKGROUND_DESC_DETAIL: "背景色仅影响预览模式的 MD-Embeddable。在编辑模式,它会根据场景(通过笔记属性设置)或插件设置,遵循 Obsidian 的深色/浅色主题。背景色有两层:元素背景色(下层颜色)和上层颜色。选择“匹配元素”表示两层都遵循元素背景色。选择“匹配绘图”或特定背景色不会改变元素背景色。设置不透明度(如 50%)会将绘图或选定的颜色与元素背景色混合。要移除元素背景色,可以在 Excalidraw 的元素属性编辑器中将元素背景色设置为透明,这样只有上层颜色生效。",
|
||||
ES_BACKGROUND_DESC_DETAIL: "背景色仅影响预览模式的 MD-Embeddable。在编辑模式,它会根据场景(通过笔记属性设置)或插件设置,遵循 Obsidian 的深色/浅色主题。背景色有两层:元素背景色(下层颜色)和上层颜色。选择“匹配元素”表示两层都遵循元素背景色。选择“匹配绘图”或特定背景色不会改变元素背景色。设置不透明度(如 50%)会将绘图或所选颜色与元素背景色混合。要移除元素背景色,可以在 Excalidraw 的元素属性编辑器中将元素背景色设置为透明,这样只有上层颜色生效。",
|
||||
ES_BACKGROUND_MATCH_ELEMENT: "匹配元素背景色",
|
||||
ES_BACKGROUND_MATCH_CANVAS: "匹配绘图背景色",
|
||||
ES_BACKGROUND_COLOR: "背景色",
|
||||
@@ -1037,7 +1043,7 @@ export default {
|
||||
ES_BORDER_OPACITY: "边框不透明度",
|
||||
ES_EMBEDDABLE_SETTINGS: "MD-Embeddable 设置",
|
||||
ES_USE_OBSIDIAN_DEFAULTS: "使用 Obsidian 默认设置",
|
||||
ES_ZOOM_100_RELATIVE_DESC: "使元素的缩放等级等于当前绘图的缩放等级",
|
||||
ES_ZOOM_100_RELATIVE_DESC: "使元素的缩放级别等于当前绘图的缩放级别",
|
||||
ES_ZOOM_100: "Relative 100%",
|
||||
|
||||
//Prompts.ts
|
||||
|
||||
@@ -16,6 +16,30 @@ export const RELEASE_NOTES: { [k: string]: string } = {
|
||||
I build this plugin in my free time, as a labor of love. Curious about the philosophy behind it? Check out [📕 Sketch Your Mind](https://sketch-your-mind.com). If you find it valuable, say THANK YOU or…
|
||||
|
||||
<div class="ex-coffee-div"><a href="https://ko-fi.com/zsolt"><img src="https://storage.ko-fi.com/cdn/kofi6.png?v=6" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
|
||||
`,
|
||||
"2.20.0":`
|
||||
## New
|
||||
- Dark theme from Excalidraw.com [#10578](https://github.com/excalidraw/excalidraw/pull/10578)
|
||||
- New setting in Excalidraw plugin settings under "Embedding Excalidraw/Export Settings/Image Theme". You can now choose to invert embedded SVG/Excalidraw and Bitmap images in dark mode.
|
||||
- New Easter Egg feature, by adding {"invertColors": true/false} after the embedded file in Excalidraw markdown view, you can control whether the embedded image inverts colors in dark mode or not, regardless of the global setting.
|
||||
- New from Excalidraw.com: chat-like interface for Mermaid TextToDiagrams (requires OpenAI API key set in Excalidraw plugin settings). [#10530](https://github.com/excalidraw/excalidraw/pull/10530)
|
||||
- Breaking change: the old force-SVG option for Mermaid diagrams is no longer supported. If a diagram can be rendered as Excalidraw it will be, else, an SVG will be used.
|
||||
|
||||
## Fixed
|
||||
- Full screen on phones left a large area at the top of the screen unused. Fixed issue with Obsidian Mobile Navigation bar floating on top of the Excalidraw toolbar.
|
||||
- Link indicator in top right corner remains visible even if element is set to transparent [#2625](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2625)
|
||||
|
||||
`,
|
||||
"2.19.2":`
|
||||
## Fixed
|
||||
- Minor fixes to the link autocomplete functionality:
|
||||
- Link suggester "eats up text" [#2603](https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2603)
|
||||
- "!" triggers the link suggester prematurely
|
||||
- "\[\[" will now be auto-completed to "\[\[]]". Note, this is not available in MindMap Builder currently.
|
||||
|
||||
## New
|
||||
- When a persistent Excalidraw script is updated via the script store, it will now automatically reload so the new script takes effect immediately.
|
||||
|
||||
`,
|
||||
"2.19.1":`
|
||||
## Fixed
|
||||
|
||||
@@ -422,7 +422,8 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
"Set scale to false if you want to embed the image at 100% of its original size. Default is true which will insert a scaled image.\n"+
|
||||
"anchor will only be evaluated if scale is false. anchor true will add |100% to the end of the filename, resulting in an image that will always pop back to 100% when the source file is updated or when the Excalidraw file is reopened.\n"+
|
||||
"colorMap is only used for SVG images and nested Excalidraw images. See the Shade Master script and the Deconstruct Selected Elements script for examples using colorMap.\n"+
|
||||
"type ColorMap = { [color: string]: string; }",
|
||||
"Set colorMap.invertInDarkMode to force or disable dark-mode inversion for that image.\n"+
|
||||
"type ColorMap = { [color: string]: string; invertInDarkMode?: boolean; }",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
@@ -450,7 +451,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
},
|
||||
{
|
||||
field: "addLaTex",
|
||||
code: "async addLaTex(topX: number, topY: number, tex: string, scaleX: number = 1, scaleY: number = 1): Promise<string>;",
|
||||
code: "async addLaTex(topX: number, topY: number, tex: string): Promise<string>;",
|
||||
desc: "This is an async function, you need to avait the results. Adds a LaTex element to the drawing. The tex string is the LaTex code. The function returns the id of the created element.",
|
||||
after: "",
|
||||
},
|
||||
@@ -561,7 +562,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
desc: 'Updates the color map of an SVG image element in the view. If a ColorMap is provided, it will be used directly. If an SVGColorInfo is provided, it will be converted to a ColorMap. The view will be marked as dirty (i.e. will be saved at next scheduled time) and the image will be reset using the color map.\n'+
|
||||
'See "Shade Master" scritp in Script Library for an example of using this function.\n\n' +
|
||||
'type SVGColorInfo = Map<string, { mappedTo: string; fill: boolean; stroke: boolean; }>\n' +
|
||||
'type ColorMap = { [color: string]: string; }',
|
||||
'type ColorMap = { [color: string]: string; invertInDarkMode?: boolean; }',
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
@@ -569,7 +570,7 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
code: "getColorMapForImageElement(el: ExcalidrawElement): ColorMap",
|
||||
desc: 'Retrieves the color map for an image element. The color map contains information about the mapping of colors used in the image. If the element already has a color map, it will be returned. The colorMap does not include all colors in the image, only those that have been mapped.\n' +
|
||||
'See "Shade Master" scritp in Script Library for an example of using this function.\n\n' +
|
||||
'type ColorMap = { [color: string]: string; }',
|
||||
'type ColorMap = { [color: string]: string; invertInDarkMode?: boolean; }',
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
FRONTMATTER_KEYS,
|
||||
getCSSFontDefinition,
|
||||
} from "../constants/constants";
|
||||
import { createSVG } from "src/utils/excalidrawAutomateUtils";
|
||||
import { createSVG, normalizeColorMap } from "src/utils/excalidrawAutomateUtils";
|
||||
import { ExcalidrawData, getTransclusion } from "./ExcalidrawData";
|
||||
import { t } from "../lang/helpers";
|
||||
import { tex2dataURL } from "./LaTeX";
|
||||
@@ -54,8 +54,6 @@ import { ExportSettings } from "src/types/exportUtilTypes";
|
||||
//and getObsidianImage is aborted if the file is already in the Watchdog stack
|
||||
const markdownRendererRecursionWatcthdog = new Set<TFile>();
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Function takes an SVG and replaces all fill and stroke colors with the ones in the colorMap
|
||||
* @param svg: SVGSVGElement
|
||||
@@ -63,13 +61,17 @@ const markdownRendererRecursionWatcthdog = new Set<TFile>();
|
||||
* @returns svg with colors replaced
|
||||
*/
|
||||
const replaceSVGColors = (svg: SVGSVGElement | string, colorMap: ColorMap | null): SVGSVGElement | string => {
|
||||
if(!colorMap) {
|
||||
const normalizedColorMap = normalizeColorMap(colorMap);
|
||||
if(!normalizedColorMap) {
|
||||
return svg;
|
||||
}
|
||||
|
||||
if(typeof svg === 'string') {
|
||||
// Replace colors in the SVG string
|
||||
for (const [oldColor, newColor] of Object.entries(colorMap)) {
|
||||
for (const [oldColor, newColor] of Object.entries(normalizedColorMap)) {
|
||||
if(typeof newColor !== "string" || oldColor === "invertInDarkMode") {
|
||||
continue;
|
||||
}
|
||||
if(oldColor === "stroke" || oldColor === "fill") {
|
||||
const [svgTag, prefix, suffix] = (svg.match(/(<svg[^>]*)(>)/i) || []) as string[];
|
||||
if (!svgTag) continue;
|
||||
@@ -102,11 +104,11 @@ const replaceSVGColors = (svg: SVGSVGElement | string, colorMap: ColorMap | null
|
||||
const oldFill = node.getAttribute('fill')?.toLocaleLowerCase();
|
||||
const oldStroke = node.getAttribute('stroke')?.toLocaleLowerCase();
|
||||
|
||||
if (oldFill && colorMap[oldFill]) {
|
||||
node.setAttribute('fill', colorMap[oldFill]);
|
||||
if (oldFill && typeof normalizedColorMap[oldFill] === "string") {
|
||||
node.setAttribute('fill', normalizedColorMap[oldFill] as string);
|
||||
}
|
||||
if (oldStroke && colorMap[oldStroke]) {
|
||||
node.setAttribute('stroke', colorMap[oldStroke]);
|
||||
if (oldStroke && typeof normalizedColorMap[oldStroke] === "string") {
|
||||
node.setAttribute('stroke', normalizedColorMap[oldStroke] as string);
|
||||
}
|
||||
}
|
||||
for(const child of node.childNodes) {
|
||||
@@ -114,8 +116,8 @@ const replaceSVGColors = (svg: SVGSVGElement | string, colorMap: ColorMap | null
|
||||
}
|
||||
}
|
||||
|
||||
if("fill" in colorMap) svg.setAttribute("fill", colorMap.fill);
|
||||
if("stroke" in colorMap) svg.setAttribute("stroke", colorMap.stroke);
|
||||
if(typeof normalizedColorMap.fill === "string") svg.setAttribute("fill", normalizedColorMap.fill);
|
||||
if(typeof normalizedColorMap.stroke === "string") svg.setAttribute("stroke", normalizedColorMap.stroke);
|
||||
for (const child of svg.childNodes) {
|
||||
childNodes(child);
|
||||
}
|
||||
@@ -123,6 +125,63 @@ const replaceSVGColors = (svg: SVGSVGElement | string, colorMap: ColorMap | null
|
||||
return svg;
|
||||
}
|
||||
|
||||
const getInvertPreference = (colorMap: ColorMap | null | undefined, fallback: boolean): boolean =>
|
||||
typeof colorMap?.invertInDarkMode === "boolean" ? colorMap.invertInDarkMode : fallback;
|
||||
|
||||
const applyThemeFilterToBitmapDataURL = async (
|
||||
dataURL: DataURL,
|
||||
mimeType: MimeType,
|
||||
themeFilter: string,
|
||||
): Promise<DataURL> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
try {
|
||||
const canvas = createEl("canvas");
|
||||
const ctx = canvas.getContext("2d");
|
||||
if(!ctx) {
|
||||
reject(new Error("Canvas 2D context unavailable"));
|
||||
return;
|
||||
}
|
||||
|
||||
canvas.width = img.naturalWidth || img.width;
|
||||
canvas.height = img.naturalHeight || img.height;
|
||||
ctx.filter = themeFilter || THEME_FILTER;
|
||||
ctx.drawImage(img, 0, 0);
|
||||
resolve(canvas.toDataURL(mimeType) as DataURL);
|
||||
} catch (e) {
|
||||
reject(e);
|
||||
}
|
||||
};
|
||||
img.onerror = (e) => reject(e);
|
||||
img.src = dataURL;
|
||||
});
|
||||
|
||||
const applyThemeFilterToSVGDataURL = (
|
||||
dataURL: DataURL,
|
||||
themeFilter: string,
|
||||
): DataURL => {
|
||||
const prefix = "data:image/svg+xml;base64,";
|
||||
if (!dataURL || !dataURL.startsWith(prefix)) {
|
||||
return dataURL;
|
||||
}
|
||||
try {
|
||||
const svgText = atob(dataURL.substring(prefix.length));
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(svgText, "image/svg+xml");
|
||||
const root = doc.documentElement;
|
||||
if (!(root instanceof SVGSVGElement)) {
|
||||
return dataURL;
|
||||
}
|
||||
const svg = root as SVGSVGElement;
|
||||
svg.setAttribute("filter", themeFilter || THEME_FILTER);
|
||||
const serialized = new XMLSerializer().serializeToString(doc);
|
||||
return svgToBase64(serialized) as DataURL;
|
||||
} catch (e) {
|
||||
return dataURL;
|
||||
}
|
||||
};
|
||||
|
||||
export class EmbeddedFile {
|
||||
public file: TFile = null;
|
||||
public isSVGwithBitmap: boolean = false;
|
||||
@@ -145,9 +204,10 @@ export class EmbeddedFile {
|
||||
constructor(plugin: ExcalidrawPlugin, hostPath: string, imgPath: string, colorMapJSON?: string) {
|
||||
this.plugin = plugin;
|
||||
this.resetImage(hostPath, imgPath);
|
||||
if(this.file && (this.plugin.isExcalidrawFile(this.file) || this.file.extension.toLowerCase() === "svg")) {
|
||||
if(this.file) { // && (this.plugin.isExcalidrawFile(this.file) || this.file.extension.toLowerCase() === "svg")) {
|
||||
try {
|
||||
this.colorMap = colorMapJSON ? JSON.parse(colorMapJSON.toLocaleLowerCase()) : null;
|
||||
const parsedColorMap = colorMapJSON ? JSON.parse(colorMapJSON) : null;
|
||||
this.colorMap = normalizeColorMap(parsedColorMap);
|
||||
} catch (error) {
|
||||
this.colorMap = null;
|
||||
}
|
||||
@@ -155,7 +215,17 @@ export class EmbeddedFile {
|
||||
}
|
||||
|
||||
get hasSeparateDarkAndLightVersion(): boolean {
|
||||
return this.isSVGwithBitmap || (this.file && this.file.extension.toLowerCase() === "pdf");
|
||||
const isPDF = this.file && this.file.extension.toLowerCase() === "pdf";
|
||||
const mime = this.mimeType?.toLowerCase?.();
|
||||
const isBitmap = mime?.startsWith("image/") && mime !== "image/svg+xml";
|
||||
const invertBitmapPref = getInvertPreference(this.colorMap, !!this.plugin?.settings?.invertBitmapforDarkMode);
|
||||
const invertSVGPref = getInvertPreference(this.colorMap, !!this.plugin?.settings?.invertSVGforDarkMode);
|
||||
const isSVG = mime === "image/svg+xml";
|
||||
|
||||
const needsBitmapOrPDFInversion = isPDF || (invertBitmapPref && isBitmap);
|
||||
const needsSVGInversion = invertSVGPref && isSVG;
|
||||
|
||||
return needsBitmapOrPDFInversion || needsSVGInversion || this.isSVGwithBitmap;
|
||||
}
|
||||
|
||||
public resetImage(hostPath: string, imgPath: string) {
|
||||
@@ -309,7 +379,11 @@ export class EmbeddedFilesLoader {
|
||||
this.pdfDocsMap.clear();
|
||||
}
|
||||
|
||||
public async getObsidianImage(inFile: TFile | EmbeddedFile, depth: number): Promise<{
|
||||
public async getObsidianImage(
|
||||
inFile: TFile | EmbeddedFile,
|
||||
depth: number,
|
||||
isDark?: boolean,
|
||||
): Promise<{
|
||||
mimeType: MimeType;
|
||||
fileId: FileId;
|
||||
dataURL: DataURL;
|
||||
@@ -318,7 +392,10 @@ export class EmbeddedFilesLoader {
|
||||
size: { height: number; width: number };
|
||||
pdfPageViewProps?: PDFPageViewProps;
|
||||
}> {
|
||||
const result = await this._getObsidianImage(inFile, depth);
|
||||
if (typeof isDark === "boolean") {
|
||||
this.isDark = isDark;
|
||||
}
|
||||
const result = await this._getObsidianImage(inFile, depth, isDark);
|
||||
this.emptyPDFDocsMap();
|
||||
return result;
|
||||
}
|
||||
@@ -352,7 +429,10 @@ export class EmbeddedFilesLoader {
|
||||
skipInliningFonts: false,
|
||||
};
|
||||
|
||||
const hasColorMap = Boolean(inFile instanceof EmbeddedFile ? inFile.colorMap : null);
|
||||
const colorMap = inFile instanceof EmbeddedFile ? inFile.colorMap : null;
|
||||
const invertBitmapInDarkMode = getInvertPreference(colorMap, this.plugin.settings.invertBitmapforDarkMode);
|
||||
const invertSVGInDarkMode = getInvertPreference(colorMap, this.plugin.settings.invertSVGforDarkMode);
|
||||
const hasColorMap = Boolean(colorMap);
|
||||
const shouldUseCache = !hasColorMap && this.plugin.settings.allowImageCacheInScene && file && imageCache.isReady();
|
||||
const hasFilenameParts = Boolean((inFile instanceof EmbeddedFile) && inFile.filenameparts);
|
||||
const filenameParts = hasFilenameParts ? (inFile as EmbeddedFile).filenameparts : null;
|
||||
@@ -409,7 +489,7 @@ export class EmbeddedFilesLoader {
|
||||
depth+1,
|
||||
getExportPadding(this.plugin, file),
|
||||
),
|
||||
inFile instanceof EmbeddedFile ? inFile.colorMap : null
|
||||
colorMap
|
||||
) as SVGSVGElement;
|
||||
|
||||
//https://stackoverflow.com/questions/51154171/remove-css-filter-on-child-elements
|
||||
@@ -420,14 +500,21 @@ export class EmbeddedFilesLoader {
|
||||
hasSVGwithBitmap = true;
|
||||
}
|
||||
|
||||
if (hasSVGwithBitmap && isDark && !Boolean(maybeSVG)) {
|
||||
if (isDark && invertSVGInDarkMode) {
|
||||
svg.setAttribute("filter", this.plugin.settings.themeFilter);
|
||||
}
|
||||
if (isDark && hasSVGwithBitmap && !Boolean(maybeSVG) && (
|
||||
(!invertBitmapInDarkMode && invertSVGInDarkMode) ||
|
||||
(invertBitmapInDarkMode && !invertSVGInDarkMode)
|
||||
)) {
|
||||
imageList.forEach((i) => {
|
||||
const id = i.parentElement?.id;
|
||||
svg.querySelectorAll(`use[href='#${id}']`).forEach((u) => {
|
||||
u.setAttribute("filter", THEME_FILTER);
|
||||
u.setAttribute("filter", this.plugin.settings.themeFilter);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (!hasSVGwithBitmap && svg.getAttribute("hasbitmap")) {
|
||||
hasSVGwithBitmap = true;
|
||||
}
|
||||
@@ -458,16 +545,34 @@ export class EmbeddedFilesLoader {
|
||||
return localPath;
|
||||
}
|
||||
|
||||
private async _getObsidianImage(inFile: TFile | EmbeddedFile, depth: number): Promise<ImgData> {
|
||||
private async _getObsidianImage(
|
||||
inFile: TFile | EmbeddedFile,
|
||||
depth: number,
|
||||
isDark?: boolean,
|
||||
): Promise<ImgData> {
|
||||
if (!this.plugin || !inFile) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const app = this.plugin.app;
|
||||
|
||||
const effectiveIsDark =
|
||||
typeof isDark === "boolean"
|
||||
? isDark
|
||||
: typeof this.isDark === "boolean"
|
||||
? this.isDark
|
||||
: undefined;
|
||||
if (typeof effectiveIsDark === "boolean") {
|
||||
this.isDark = effectiveIsDark;
|
||||
}
|
||||
|
||||
const isHyperLink = inFile instanceof EmbeddedFile ? inFile.isHyperLink : false;
|
||||
const isLocalLink = inFile instanceof EmbeddedFile ? inFile.isLocalLink : false;
|
||||
const hyperlink = inFile instanceof EmbeddedFile ? inFile.hyperlink : "";
|
||||
const normalizedColorMap = inFile instanceof EmbeddedFile ? normalizeColorMap(inFile.colorMap) : null;
|
||||
if (inFile instanceof EmbeddedFile) {
|
||||
inFile.colorMap = normalizedColorMap;
|
||||
}
|
||||
const file: TFile = inFile instanceof EmbeddedFile ? inFile.file : inFile;
|
||||
if(file && markdownRendererRecursionWatcthdog.has(file)) {
|
||||
new Notice(`Loading of ${file.path}. Please check if there is an inifinite loop of one file embedded in the other.`);
|
||||
@@ -492,6 +597,11 @@ export class EmbeddedFilesLoader {
|
||||
let hasSVGwithBitmap = false;
|
||||
const isExcalidrawFile = !isHyperLink && !isLocalLink && this.plugin.isExcalidrawFile(file);
|
||||
const isPDF = !isHyperLink && !isLocalLink && file.extension.toLowerCase() === "pdf";
|
||||
const invertBitmapInDarkMode = getInvertPreference(
|
||||
normalizedColorMap,
|
||||
isPDF || this.plugin.settings.invertBitmapforDarkMode,
|
||||
);
|
||||
const invertSVGInDarkMode = getInvertPreference(normalizedColorMap, this.plugin.settings.invertSVGforDarkMode);
|
||||
|
||||
if (
|
||||
!isHyperLink && !isPDF && !isLocalLink &&
|
||||
@@ -512,7 +622,7 @@ export class EmbeddedFilesLoader {
|
||||
let dURL: DataURL = null;
|
||||
if (isExcalidrawFile) {
|
||||
const res = await this.getExcalidrawSVG({
|
||||
isDark: this.isDark,
|
||||
isDark: effectiveIsDark ?? this.isDark,
|
||||
file,
|
||||
depth,
|
||||
inFile,
|
||||
@@ -548,7 +658,7 @@ export class EmbeddedFilesLoader {
|
||||
)
|
||||
: excalidrawSVG ?? pdfDataURL ??
|
||||
(file?.extension === "svg"
|
||||
? await getSVGData(app, file, inFile instanceof EmbeddedFile ? inFile.colorMap : null)
|
||||
? await getSVGData(app, file, normalizedColorMap)
|
||||
: file?.extension === "md"
|
||||
? null
|
||||
: await getDataURL(ab, mimeType));
|
||||
@@ -560,6 +670,36 @@ export class EmbeddedFilesLoader {
|
||||
dataURL = result.dataURL;
|
||||
hasSVGwithBitmap = result.hasSVGwithBitmap;
|
||||
}
|
||||
|
||||
if (
|
||||
(effectiveIsDark ?? this.isDark) &&
|
||||
invertSVGInDarkMode &&
|
||||
dataURL &&
|
||||
mimeType === "image/svg+xml"
|
||||
) {
|
||||
dataURL = applyThemeFilterToSVGDataURL(
|
||||
dataURL,
|
||||
this.plugin.settings.themeFilter,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
(effectiveIsDark ?? this.isDark) &&
|
||||
invertBitmapInDarkMode &&
|
||||
dataURL &&
|
||||
mimeType?.startsWith("image/") &&
|
||||
mimeType !== "image/svg+xml"
|
||||
) {
|
||||
try {
|
||||
dataURL = await applyThemeFilterToBitmapDataURL(
|
||||
dataURL,
|
||||
mimeType,
|
||||
this.plugin.settings.themeFilter,
|
||||
);
|
||||
} catch (error) {
|
||||
errorlog({ where: "EmbeddedFileLoader._getObsidianImage", error });
|
||||
}
|
||||
}
|
||||
try{
|
||||
const size = isPDF ? pdfSize : await getImageSize(dataURL);
|
||||
return {
|
||||
@@ -599,7 +739,9 @@ export class EmbeddedFilesLoader {
|
||||
}
|
||||
const entries = excalidrawData.getFileEntries();
|
||||
//debug({where:"EmbeddedFileLoader.loadSceneFiles",uid:this.uid,isDark:this.isDark,sceneTheme:excalidrawData.scene.appState.theme});
|
||||
if (this.isDark === undefined) {
|
||||
if (isThemeChange) {
|
||||
this.isDark = excalidrawData?.scene?.appState?.theme === "dark";
|
||||
} else if (this.isDark === undefined) {
|
||||
this.isDark = excalidrawData?.scene?.appState?.theme === "dark";
|
||||
}
|
||||
let entry: IteratorResult<[FileId, EmbeddedFile]>;
|
||||
@@ -659,9 +801,19 @@ export class EmbeddedFilesLoader {
|
||||
if (this.terminate) {
|
||||
return;
|
||||
}
|
||||
if (!excalidrawData.getEquation(id).isLoaded) {
|
||||
const invertPreference = getInvertPreference(equation?.colorMap, this.plugin.settings.invertSVGforDarkMode);
|
||||
const shouldReloadForTheme = isThemeChange && invertPreference;
|
||||
if (!excalidrawData.getEquation(id).isLoaded || shouldReloadForTheme) {
|
||||
const latex = equation.latex;
|
||||
const data = await tex2dataURL(latex, 4, this.plugin);
|
||||
const data = await tex2dataURL(
|
||||
latex,
|
||||
4,
|
||||
this.plugin,
|
||||
{
|
||||
applyThemeFilter: this.isDark && this.plugin.settings.invertSVGforDarkMode,
|
||||
themeFilter: this.plugin.settings.themeFilter,
|
||||
},
|
||||
);
|
||||
if (data) {
|
||||
const fileData = {
|
||||
mimeType: data.mimeType,
|
||||
@@ -670,7 +822,7 @@ export class EmbeddedFilesLoader {
|
||||
created: data.created,
|
||||
size: data.size,
|
||||
hasSVGwithBitmap: false,
|
||||
shouldScale: true
|
||||
shouldScale: true,
|
||||
};
|
||||
files[batch].push(fileData);
|
||||
}
|
||||
@@ -688,8 +840,7 @@ export class EmbeddedFilesLoader {
|
||||
const data = getMermaidText(element);
|
||||
const result = await mermaidToExcalidraw(
|
||||
data,
|
||||
{ themeVariables: { fontSize: "20" } },
|
||||
true
|
||||
{ themeVariables: { fontSize: "20" } }
|
||||
);
|
||||
if(!result) {
|
||||
return;
|
||||
@@ -890,26 +1041,6 @@ export class EmbeddedFilesLoader {
|
||||
|
||||
const canvas = await renderPage(pageNum);
|
||||
if(canvas) {
|
||||
// NEW: invert colors for dark theme (keep alpha unchanged)
|
||||
if (this.isDark) {
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (ctx) {
|
||||
try {
|
||||
const img = ctx.getImageData(0, 0, canvas.width, canvas.height);
|
||||
const data = img.data;
|
||||
for (let i = 0; i < data.length; i += 4) {
|
||||
data[i] = 255 - data[i]; // R
|
||||
data[i + 1] = 255 - data[i+1]; // G
|
||||
data[i + 2] = 255 - data[i+2]; // B
|
||||
// alpha channel (data[i+3]) remains unchanged
|
||||
}
|
||||
ctx.putImageData(img, 0, 0);
|
||||
} catch (e) {
|
||||
// If reading pixel data fails, silently fallback to non-inverted
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result: [DataURL,Size, PDFPageViewProps] = [`data:image/png;base64,${await new Promise((resolve, reject) => {
|
||||
canvas.toBlob(async (blob) => {
|
||||
const dataURL = await blobToBase64(blob);
|
||||
@@ -1078,7 +1209,7 @@ export class EmbeddedFilesLoader {
|
||||
const ef = new EmbeddedFile(plugin,file.path,src);
|
||||
//const f = app.metadataCache.getFirstLinkpathDest(src.split("#")[0],file.path);
|
||||
if(!ef.file) continue;
|
||||
const embeddedFile = await this._getObsidianImage(ef,1);
|
||||
const embeddedFile = await this._getObsidianImage(ef,1,this.isDark);
|
||||
const img = createEl("img");
|
||||
if(width) img.setAttribute("width", width);
|
||||
if(height) img.setAttribute("height", height);
|
||||
@@ -1153,7 +1284,11 @@ export class EmbeddedFilesLoader {
|
||||
if (imageList.length > 0) {
|
||||
hasSVGwithBitmap = true;
|
||||
}
|
||||
if (hasSVGwithBitmap && this.isDark) {
|
||||
|
||||
if (this.isDark && hasSVGwithBitmap && (
|
||||
(!this.plugin.settings.invertBitmapforDarkMode && this.plugin.settings.invertSVGforDarkMode) ||
|
||||
(this.plugin.settings.invertBitmapforDarkMode && !this.plugin.settings.invertSVGforDarkMode)
|
||||
)) {
|
||||
imageList.forEach(img => {
|
||||
if(img instanceof HTMLImageElement) {
|
||||
img.style.filter = THEME_FILTER;
|
||||
@@ -1161,15 +1296,29 @@ export class EmbeddedFilesLoader {
|
||||
});
|
||||
}
|
||||
|
||||
/*if (hasSVGwithBitmap && this.isDark) {
|
||||
imageList.forEach(img => {
|
||||
if(img instanceof HTMLImageElement) {
|
||||
img.style.filter = THEME_FILTER;
|
||||
}
|
||||
});
|
||||
}*/
|
||||
|
||||
const xml = new XMLSerializer().serializeToString(mdDIV);
|
||||
const finalSVG = svg(xml, '<div class="excalidraw-md-footer"></div>', style);
|
||||
plugin.ea.mostRecentMarkdownSVG = parser.parseFromString(
|
||||
finalSVG,
|
||||
"image/svg+xml",
|
||||
).firstElementChild as SVGSVGElement;
|
||||
|
||||
if (this.isDark && this.plugin.settings.invertSVGforDarkMode) {
|
||||
plugin.ea.mostRecentMarkdownSVG.setAttribute("filter", this.plugin.settings.themeFilter);
|
||||
}
|
||||
|
||||
return {
|
||||
dataURL: svgToBase64(finalSVG) as DataURL,
|
||||
hasSVGwithBitmap
|
||||
//dataURL: svgToBase64(finalSVG) as DataURL,
|
||||
dataURL: svgToBase64(plugin.ea.mostRecentMarkdownSVG.outerHTML) as DataURL,
|
||||
hasSVGwithBitmap: hasSVGwithBitmap || !!mdDIV.querySelector(".excalidraw-svg"),
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
DEVICE,
|
||||
mermaidToExcalidraw,
|
||||
refreshTextDimensions,
|
||||
getDefaultColorPalette,
|
||||
getFontFamilyString,
|
||||
} from "src/constants/constants";
|
||||
import { blobToBase64, checkAndCreateFolder, getDrawingFilename, getExcalidrawEmbeddedFilesFiletree, getListOfTemplateFiles, getNewUniqueFilepath, splitFolderAndFilename } from "src/utils/fileUtils";
|
||||
@@ -84,7 +85,7 @@ import { log } from "../utils/debugHelper";
|
||||
import { ExcalidrawLib } from "../types/excalidrawLib";
|
||||
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/src/types";
|
||||
import { AddImageOptions, ImageInfo, KeyBlocker, ScriptSettingValue, SVGColorInfo } from "src/types/excalidrawAutomateTypes";
|
||||
import { _measureText, cloneElement, createPNG, createSVG, ensureActiveScriptSettingsObject, errorMessage, filterColorMap, getEmbeddedFileForImageElment, getLastActiveExcalidrawView, getLineBox, getTemplate, isColorStringTransparent, isSVGColorInfo, mergeColorMapIntoSVGColorInfo, normalizeBindMode, normalizeFixedPoint, normalizeLinePoints, repositionElementsToCursor, svgColorInfoToColorMap, updateOrAddSVGColorInfo, verifyMinimumPluginVersion } from "src/utils/excalidrawAutomateUtils";
|
||||
import { _measureText, cloneElement, createPNG, createSVG, ensureActiveScriptSettingsObject, errorMessage, filterColorMap, getEmbeddedFileForImageElment, getLastActiveExcalidrawView, getLineBox, getTemplate, isColorStringTransparent, isSVGColorInfo, mergeColorMapIntoSVGColorInfo, normalizeBindMode, normalizeColorMap, normalizeFixedPoint, normalizeLinePoints, repositionElementsToCursor, svgColorInfoToColorMap, updateOrAddSVGColorInfo, verifyMinimumPluginVersion } from "src/utils/excalidrawAutomateUtils";
|
||||
import { exportToPDF, getMarginValue, getPageDimensions } from "src/utils/exportUtils";
|
||||
import { PageDimensions, PageOrientation, PageSize, PDFExportScale, PDFPageProperties, ExportSettings} from "src/types/exportUtilTypes";
|
||||
import { FrameRenderingOptions } from "src/types/utilTypes";
|
||||
@@ -97,7 +98,6 @@ import { patchMobileView } from "src/utils/customEmbeddableUtils";
|
||||
import { ObsidianCanvasNode } from "src/view/managers/CanvasNodeFactory";
|
||||
import { AIRequest } from "src/types/AIUtilTypes";
|
||||
import { getAspectRatio } from "src/utils/YoutTubeUtils";
|
||||
import { getPDFCropRect } from "src/utils/PDFUtils";
|
||||
|
||||
extendPlugins([
|
||||
HarmonyPlugin,
|
||||
@@ -708,6 +708,9 @@ export class ExcalidrawAutomate {
|
||||
*/
|
||||
public getAPI(view?:ExcalidrawView):ExcalidrawAutomate {
|
||||
const ea = new ExcalidrawAutomate(this.plugin, view);
|
||||
if(view && view.excalidrawAPI) {
|
||||
ea.canvas.theme = view.excalidrawAPI.getAppState().theme;
|
||||
}
|
||||
this.plugin.eaInstances.push(ea);
|
||||
return ea;
|
||||
}
|
||||
@@ -2176,7 +2179,7 @@ export class ExcalidrawAutomate {
|
||||
anchor: boolean = true, //only has effect if scale is false. If anchor is true the image path will include |100%, if false the image will be inserted at 100%, but if resized by the user it won't pop back to 100% the next time Excalidraw is opened.
|
||||
): Promise<string> {
|
||||
|
||||
let colorMap: ColorMap;
|
||||
let colorMap: ColorMap | null = null;
|
||||
let topX: number;
|
||||
if(typeof topXOrOpts === "number") {
|
||||
topX = topXOrOpts;
|
||||
@@ -2186,49 +2189,43 @@ export class ExcalidrawAutomate {
|
||||
imageFile = topXOrOpts.imageFile;
|
||||
scale = topXOrOpts.scale ?? true;
|
||||
anchor = topXOrOpts.anchor ?? true;
|
||||
colorMap = topXOrOpts.colorMap;
|
||||
colorMap = normalizeColorMap(topXOrOpts.colorMap);
|
||||
}
|
||||
|
||||
const pdfLinkRegex = /^[^#]*#page=\d*(&\w*=[^&]+){0,}&rect=\d*,\d*,\d*,\d*/;
|
||||
const originalLink = typeof imageFile === "string" ? imageFile : null;
|
||||
const imageFileForLoader = originalLink && pdfLinkRegex.test(originalLink)
|
||||
? originalLink.split("&rect=")[0]
|
||||
: imageFile;
|
||||
|
||||
const id = nanoid();
|
||||
const loader = new EmbeddedFilesLoader(
|
||||
this.plugin,
|
||||
this.canvas.theme === "dark",
|
||||
);
|
||||
const image = (typeof imageFileForLoader === "string")
|
||||
? await loader.getObsidianImage(new EmbeddedFile(this.plugin, "", imageFileForLoader),0)
|
||||
: await loader.getObsidianImage(imageFileForLoader,0);
|
||||
const image = (typeof imageFile === "string")
|
||||
? await loader.getObsidianImage(new EmbeddedFile(this.plugin, "", imageFile),0, this.canvas.theme === "dark")
|
||||
: await loader.getObsidianImage(imageFile,0, this.canvas.theme === "dark");
|
||||
|
||||
if (!image) {
|
||||
return null;
|
||||
}
|
||||
const fileId = typeof imageFileForLoader === "string"
|
||||
const fileId = typeof imageFile === "string"
|
||||
? image.fileId
|
||||
: imageFileForLoader.extension === "md" || imageFileForLoader.extension.toLowerCase() === "pdf" ? fileid() as FileId : image.fileId;
|
||||
: imageFile.extension === "md" || imageFile.extension.toLowerCase() === "pdf" ? fileid() as FileId : image.fileId;
|
||||
this.imagesDict[fileId] = {
|
||||
mimeType: image.mimeType,
|
||||
id: fileId,
|
||||
dataURL: image.dataURL,
|
||||
created: image.created,
|
||||
isHyperLink: typeof imageFileForLoader === "string",
|
||||
hyperlink: typeof imageFileForLoader === "string"
|
||||
? imageFileForLoader
|
||||
isHyperLink: typeof imageFile === "string",
|
||||
hyperlink: typeof imageFile === "string"
|
||||
? imageFile
|
||||
: null,
|
||||
file: typeof imageFileForLoader === "string"
|
||||
file: typeof imageFile === "string"
|
||||
? null
|
||||
: imageFileForLoader.path + (scale || !anchor ? "":"|100%"),
|
||||
: imageFile.path + (scale || !anchor ? "":"|100%"),
|
||||
hasSVGwithBitmap: image.hasSVGwithBitmap,
|
||||
latex: null,
|
||||
size: { //must have the natural size here (e.g. for PDF cropping)
|
||||
height: image.size.height,
|
||||
width: image.size.width,
|
||||
},
|
||||
colorMap,
|
||||
colorMap: colorMap ?? undefined,
|
||||
pdfPageViewProps: image.pdfPageViewProps,
|
||||
};
|
||||
if (scale && (Math.max(image.size.width, image.size.height) > MAX_IMAGE_SIZE)) {
|
||||
@@ -2249,22 +2246,6 @@ export class ExcalidrawAutomate {
|
||||
newEl.fileId = fileId;
|
||||
newEl.scale = [1, 1];
|
||||
newEl.crop = null;
|
||||
if(originalLink && pdfLinkRegex.test(originalLink)) {
|
||||
const fd = this.imagesDict[fileId];
|
||||
newEl.crop = getPDFCropRect({
|
||||
scale: this.plugin.settings.pdfScale,
|
||||
link: originalLink,
|
||||
naturalHeight: fd.size.height,
|
||||
naturalWidth: fd.size.width,
|
||||
pdfPageViewProps: fd.pdfPageViewProps,
|
||||
});
|
||||
addAppendUpdateCustomData(newEl, {pdfPageViewProps: fd.pdfPageViewProps});
|
||||
if(newEl.crop) {
|
||||
newEl.width = newEl.crop.width/this.plugin.settings.pdfScale;
|
||||
newEl.height = newEl.crop.height/this.plugin.settings.pdfScale;
|
||||
}
|
||||
newEl.link = `[[${originalLink}]]`;
|
||||
}
|
||||
if(!scale && anchor) {
|
||||
newEl.customData = {isAnchored: true}
|
||||
};
|
||||
@@ -2276,16 +2257,24 @@ export class ExcalidrawAutomate {
|
||||
* @param {number} topX - The x-coordinate of the top-left corner.
|
||||
* @param {number} topY - The y-coordinate of the top-left corner.
|
||||
* @param {string} tex - The LaTeX equation string.
|
||||
* @param {number} [scaleX=1] - The x-scaling factor (post mathjax creation)
|
||||
* @param {number} [scaleY=1] - The y-scaling factor (post mathjax creation)
|
||||
* @returns {Promise<string>} Promise resolving to the ID of the added LaTeX image element.
|
||||
*/
|
||||
async addLaTex(topX: number, topY: number, tex: string, scaleX: number = 1, scaleY: number = 1): Promise<string> {
|
||||
if (!tex || !scaleX || !scaleY){
|
||||
async addLaTex(topX: number, topY: number, tex: string): Promise<string> {
|
||||
if (!tex){
|
||||
return null;
|
||||
}
|
||||
const currentTheme = this.targetView?.excalidrawAPI?.getAppState().theme ?? this.canvas.theme;
|
||||
const applyFilter = currentTheme === "dark" && this.plugin.settings.invertSVGforDarkMode;
|
||||
const id = nanoid();
|
||||
const image = await tex2dataURL(tex, 4, this.plugin);
|
||||
const image = await tex2dataURL(
|
||||
tex,
|
||||
4,
|
||||
this.plugin,
|
||||
{
|
||||
applyThemeFilter: applyFilter,
|
||||
themeFilter: this.plugin.settings.themeFilter,
|
||||
},
|
||||
);
|
||||
if (!image) {
|
||||
return null;
|
||||
}
|
||||
@@ -2303,12 +2292,12 @@ export class ExcalidrawAutomate {
|
||||
"image",
|
||||
topX,
|
||||
topY,
|
||||
image.size.width * Math.abs(scaleX),
|
||||
image.size.height * Math.abs(scaleY),
|
||||
image.size.width,
|
||||
image.size.height,
|
||||
);
|
||||
this.elementsDict[id].fileId = image.fileId;
|
||||
this.addAppendUpdateCustomData(id, {latex: tex});
|
||||
this.elementsDict[id].scale = [Math.sign(scaleX), Math.sign(scaleY)];
|
||||
this.elementsDict[id].scale = [1, 1];
|
||||
return id;
|
||||
};
|
||||
|
||||
@@ -2320,7 +2309,8 @@ export class ExcalidrawAutomate {
|
||||
*/
|
||||
async tex2dataURL(
|
||||
tex: string,
|
||||
scale: number = 4 // Default scale value, adjust as needed
|
||||
scale: number = 4, // Default scale value, adjust as needed
|
||||
options?: { applyThemeFilter?: boolean; themeFilter?: string },
|
||||
): Promise<{
|
||||
mimeType: MimeType;
|
||||
fileId: FileId;
|
||||
@@ -2328,7 +2318,12 @@ export class ExcalidrawAutomate {
|
||||
created: number;
|
||||
size: { height: number; width: number };
|
||||
}> {
|
||||
return await tex2dataURL(tex,scale, this.plugin);
|
||||
const currentTheme = this.targetView?.excalidrawAPI?.getAppState().theme ?? this.canvas.theme;
|
||||
const themeOptions = options ?? {
|
||||
applyThemeFilter: currentTheme === "dark" && this.plugin.settings.invertSVGforDarkMode,
|
||||
themeFilter: this.plugin.settings.themeFilter,
|
||||
};
|
||||
return await tex2dataURL(tex, scale, this.plugin, themeOptions);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -2600,6 +2595,9 @@ export class ExcalidrawAutomate {
|
||||
this.targetView.leaf,
|
||||
);
|
||||
}
|
||||
if (this.targetView && this.targetView.excalidrawAPI) {
|
||||
this.canvas.theme = this.targetView.excalidrawAPI.getAppState().theme;
|
||||
}
|
||||
return this.targetView;
|
||||
};
|
||||
|
||||
@@ -2708,10 +2706,11 @@ export class ExcalidrawAutomate {
|
||||
*/
|
||||
getColorMapForImageElement(el: ExcalidrawElement): ColorMap {
|
||||
const cm = getEmbeddedFileForImageElment(this,el)?.colorMap
|
||||
if(!cm) {
|
||||
const normalized = normalizeColorMap(cm);
|
||||
if(!normalized) {
|
||||
return {};
|
||||
}
|
||||
return cm;
|
||||
return normalized;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2749,7 +2748,9 @@ export class ExcalidrawAutomate {
|
||||
errorMessage("Must provide an image element and a colorMap as input", "updateViewSVGImageColorMap()");
|
||||
continue;
|
||||
}
|
||||
if (!colorMap || typeof colorMap !== 'object' || Object.keys(colorMap).length === 0) {
|
||||
const hasColorEntries = Object.keys(colorMap).some(key => key.toLocaleLowerCase() !== "invertindarkmode");
|
||||
const hasInvertPreference = typeof (colorMap as Record<string, unknown>).invertInDarkMode === "boolean";
|
||||
if (!colorMap || typeof colorMap !== 'object' || (!hasColorEntries && !hasInvertPreference)) {
|
||||
ef.colorMap = null;
|
||||
} else {
|
||||
ef.colorMap = colorMap;
|
||||
@@ -3816,7 +3817,6 @@ export class ExcalidrawAutomate {
|
||||
|
||||
/**
|
||||
* Moves the specified element to a specific position in the z-index.
|
||||
* * Operates directly on the Excalidraw Scene in targetView, not through ExcalidrawAutomate elements.
|
||||
* @param {number} elementId - The ID of the element to move.
|
||||
* @param {number} newZIndex - The new z-index position for the element.
|
||||
*/
|
||||
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
arrayToMap,
|
||||
compressAsync,
|
||||
} from "../utils/utils";
|
||||
import { ColorMap } from "../types/embeddedFileLoaderTypes";
|
||||
import { cleanBlockRef, cleanSectionHeading, getAttachmentsFolderAndFilePath, isObsidianThemeDark } from "../utils/obsidianUtils";
|
||||
import {
|
||||
ExcalidrawElement,
|
||||
@@ -146,6 +147,31 @@ export const REGEX_LINK = {
|
||||
},
|
||||
};
|
||||
|
||||
const COLOR_MAP_INVERT_KEY = "invertindarkmode";
|
||||
const isReservedColorMapKey = (key: string) => key.toLocaleLowerCase() === COLOR_MAP_INVERT_KEY;
|
||||
const normalizeColorMapLocal = (colorMap?: ColorMap | null): ColorMap | null => {
|
||||
if (!colorMap || typeof colorMap !== "object") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalized: ColorMap = {};
|
||||
const invert = (colorMap as Record<string, unknown>).invertInDarkMode ?? (colorMap as Record<string, unknown>)[COLOR_MAP_INVERT_KEY];
|
||||
if (typeof invert === "boolean") {
|
||||
normalized.invertInDarkMode = invert;
|
||||
}
|
||||
|
||||
for (const [key, value] of Object.entries(colorMap)) {
|
||||
if (isReservedColorMapKey(key) || typeof value !== "string") {
|
||||
continue;
|
||||
}
|
||||
const normalizedKey = key.toLocaleLowerCase();
|
||||
const normalizedValue = value.toLocaleLowerCase();
|
||||
normalized[normalizedKey] = normalizedValue;
|
||||
}
|
||||
|
||||
return normalized;
|
||||
};
|
||||
|
||||
//added \n at and of DRAWING_REG: https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/357
|
||||
const DRAWING_REG = /\n##? Drawing\n[^`]*(```json\n)([\s\S]*?)```\n/gm; //https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/182
|
||||
const DRAWING_REG_FALLBACK = /\n##? Drawing\n(```json\n)?(.*)(```)?(%%)?/gm;
|
||||
@@ -1497,7 +1523,8 @@ export class ExcalidrawData {
|
||||
const path = ef.file
|
||||
? ef.linkParts.original.replace(PATHREG,this.app.metadataCache.fileToLinktext(ef.file,this.file.path))
|
||||
: ef.linkParts.original;
|
||||
const colorMap = ef.colorMap ? " " + JSON.stringify(ef.colorMap) : "";
|
||||
const normalizedColorMap = normalizeColorMapLocal(ef.colorMap);
|
||||
const colorMap = normalizedColorMap ? " " + JSON.stringify(normalizedColorMap) : "";
|
||||
outString += `${key}: [[${path}]]${colorMap}\n\n`;
|
||||
}
|
||||
}
|
||||
@@ -2014,6 +2041,7 @@ export class ExcalidrawData {
|
||||
}
|
||||
|
||||
const parts = data.linkParts.original.split("#");
|
||||
const normalizedColorMap = normalizeColorMapLocal(data.colorMap);
|
||||
this.plugin.filesMaster.set(fileId, {
|
||||
isHyperLink: false,
|
||||
isLocalLink: false,
|
||||
@@ -2022,7 +2050,7 @@ export class ExcalidrawData {
|
||||
? null
|
||||
: parts[1],
|
||||
hasSVGwithBitmap: data.isSVGwithBitmap,
|
||||
colorMapJSON: data.colorMap ? JSON.stringify(data.colorMap) : null,
|
||||
colorMapJSON: normalizedColorMap ? JSON.stringify(normalizedColorMap) : null,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -53,6 +53,7 @@ export async function tex2dataURL(
|
||||
tex: string,
|
||||
scale: number = 4,
|
||||
plugin: ExcalidrawPlugin,
|
||||
options?: { applyThemeFilter?: boolean; themeFilter?: string },
|
||||
): Promise<{
|
||||
mimeType: MimeType;
|
||||
fileId: FileId;
|
||||
@@ -61,7 +62,7 @@ export async function tex2dataURL(
|
||||
size: { height: number; width: number };
|
||||
}> {
|
||||
await loadMathJax();
|
||||
return tex2dataURLExternal(tex, scale, plugin);
|
||||
return tex2dataURLExternal(tex, scale, plugin, options);
|
||||
}
|
||||
|
||||
export const clearMathJaxVariables = () => {
|
||||
|
||||
@@ -42,6 +42,7 @@ export class InlineLinkSuggester extends SuggestionModal<InlineSuggestion> imple
|
||||
private readonly plugin: ExcalidrawPlugin;
|
||||
private readonly widthHost: HTMLElement;
|
||||
private readonly hasCustomWidthHost: boolean;
|
||||
private readonly handleBracketKeyDown: (event: KeyboardEvent) => void;
|
||||
private block = false;
|
||||
private activeOpen = -1;
|
||||
private activeClose = -1;
|
||||
@@ -68,18 +69,46 @@ export class InlineLinkSuggester extends SuggestionModal<InlineSuggestion> imple
|
||||
this.getSourcePath = getSourcePath;
|
||||
this.widthHost = widthWrapper ?? inputEl;
|
||||
this.hasCustomWidthHost = Boolean(widthWrapper);
|
||||
this.handleBracketKeyDown = (event: KeyboardEvent) => this.onBracketKeyDown(event);
|
||||
this.limit = 20;
|
||||
if (!surpessPlaceholder) {
|
||||
this.setPlaceholder(t("INLINE_HINT"));
|
||||
}
|
||||
this.emptyStateText = "No match";
|
||||
this.syncWidth();
|
||||
this.inputEl.addEventListener("keydown", this.handleBracketKeyDown);
|
||||
}
|
||||
|
||||
public isBlockingKeys() {
|
||||
return this.block;
|
||||
}
|
||||
|
||||
private onBracketKeyDown(event: KeyboardEvent) {
|
||||
if (event.key !== "[" || event.metaKey || event.ctrlKey || event.defaultPrevented || event.isComposing) {
|
||||
return;
|
||||
}
|
||||
|
||||
const selectionStart = this.inputEl.selectionStart;
|
||||
const selectionEnd = this.inputEl.selectionEnd;
|
||||
if (selectionStart === null || selectionEnd === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const hasSelection = selectionStart !== selectionEnd;
|
||||
const value = this.inputEl.value;
|
||||
const before = value.substring(0, selectionStart);
|
||||
const selected = value.substring(selectionStart, selectionEnd);
|
||||
const after = value.substring(selectionEnd);
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
const insertion = hasSelection ? `[${selected}]` : "[]";
|
||||
const cursorPos = selectionStart + 1 + (hasSelection ? selected.length : 0);
|
||||
this.inputEl.value = `${before}${insertion}${after}`;
|
||||
this.inputEl.setSelectionRange(cursorPos, cursorPos);
|
||||
this.dispatchInputChange();
|
||||
}
|
||||
|
||||
getItems(): InlineSuggestion[] {
|
||||
return getLinkSuggestionsFiltered(this.app) as InlineSuggestion[];
|
||||
}
|
||||
@@ -299,13 +328,21 @@ export class InlineLinkSuggester extends SuggestionModal<InlineSuggestion> imple
|
||||
if (start === -1) {
|
||||
return;
|
||||
}
|
||||
const closeIndex = this.activeClose >= 0 ? this.activeClose : this.inputEl.value.indexOf("]]", start + 2);
|
||||
const end = closeIndex >= 0 ? closeIndex + 2 : cursor;
|
||||
|
||||
const nextOpen = this.inputEl.value.indexOf("[[", start + 2);
|
||||
const fallbackClose = this.inputEl.value.indexOf("]]", start + 2);
|
||||
const closeBelongsToLink = this.activeClose >= 0
|
||||
? true
|
||||
: fallbackClose !== -1 && (nextOpen === -1 || fallbackClose < nextOpen);
|
||||
const effectiveClose = this.activeClose >= 0 ? this.activeClose : closeBelongsToLink ? fallbackClose : -1;
|
||||
// If no valid closing brackets are present for this link (e.g. another [[ appears first),
|
||||
// only replace up to the current cursor to avoid swallowing subsequent text.
|
||||
const end = effectiveClose >= 0 ? effectiveClose + 2 : cursor;
|
||||
|
||||
const prefix = this.inputEl.value.substring(0, start);
|
||||
const suffix = this.inputEl.value.substring(end);
|
||||
this.inputEl.value = prefix + link + suffix;
|
||||
this.inputEl.dispatchEvent(new Event("input"));
|
||||
this.dispatchInputChange();
|
||||
const newPos = start + link.length;
|
||||
this.inputEl.setSelectionRange(newPos, newPos);
|
||||
this.close();
|
||||
@@ -450,12 +487,22 @@ export class InlineLinkSuggester extends SuggestionModal<InlineSuggestion> imple
|
||||
while (true) {
|
||||
const open = value.indexOf("[[", searchFrom);
|
||||
if (open === -1 || open > pos) break;
|
||||
const close = value.indexOf("]]", open + 2);
|
||||
if (close === -1 || pos <= close) {
|
||||
const nextOpen = value.indexOf("[[", open + 2);
|
||||
const closeCandidate = value.indexOf("]]", open + 2);
|
||||
const closeBelongsToLink = closeCandidate !== -1 && (nextOpen === -1 || closeCandidate < nextOpen);
|
||||
const close = closeBelongsToLink ? closeCandidate : -1;
|
||||
const caretInsideBrackets = pos > open + 1 && (close === -1 || pos <= close);
|
||||
if (caretInsideBrackets) {
|
||||
candidate = { open, close };
|
||||
break;
|
||||
}
|
||||
searchFrom = close + 2;
|
||||
if (close !== -1) {
|
||||
searchFrom = close + 2;
|
||||
} else if (nextOpen !== -1) {
|
||||
searchFrom = nextOpen + 2;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
@@ -475,4 +522,14 @@ export class InlineLinkSuggester extends SuggestionModal<InlineSuggestion> imple
|
||||
|
||||
return { alias, inAlias, searchTerm };
|
||||
}
|
||||
|
||||
private dispatchInputChange() {
|
||||
const eventInit = { bubbles: true, composed: true, cancelable: true };
|
||||
const inputEvt = typeof InputEvent !== "undefined"
|
||||
? new InputEvent("input", eventInit as InputEventInit)
|
||||
: new Event("input", eventInit);
|
||||
this.inputEl.dispatchEvent(inputEvt);
|
||||
const changeEvt = new Event("change", eventInit);
|
||||
this.inputEl.dispatchEvent(changeEvt);
|
||||
}
|
||||
}
|
||||
@@ -48,5 +48,6 @@ export type Size = {
|
||||
};
|
||||
|
||||
export interface ColorMap {
|
||||
[color: string]: string;
|
||||
invertInDarkMode?: boolean;
|
||||
[color: string]: string | boolean | undefined;
|
||||
};
|
||||
Vendored
+20
-13
@@ -1,8 +1,8 @@
|
||||
import { RestoredDataState } from "@zsviczian/excalidraw/types/excalidraw/data/restore";
|
||||
import { ImportedDataState } from "@zsviczian/excalidraw/types/excalidraw/data/types";
|
||||
import { BoundingBox } from "@zsviczian/excalidraw/types/element/src";
|
||||
import { ElementsMap, ExcalidrawBindableElement, ExcalidrawElement, ExcalidrawFrameElement, ExcalidrawFrameLikeElement, ExcalidrawTextContainer, ExcalidrawTextElement, FontFamilyValues, FontString, NonDeleted, NonDeletedExcalidrawElement, OrderedExcalidrawElement, Theme } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { FontMetadata } from "@zsviczian/excalidraw/types/common/src";
|
||||
import { ElementsMap, ElementsMapOrArray, ExcalidrawBindableElement, ExcalidrawElement, ExcalidrawFrameElement, ExcalidrawFrameLikeElement, ExcalidrawTextContainer, ExcalidrawTextElement, FontFamilyValues, FontString, NonDeleted, NonDeletedExcalidrawElement, OrderedExcalidrawElement, Theme } from "@zsviczian/excalidraw/types/element/src/types";
|
||||
import { CombineBrandsIfNeeded, FontMetadata } from "@zsviczian/excalidraw/types/common/src";
|
||||
import { AppState, BinaryFiles, DataURL, GenerateDiagramToCode, Zoom } from "@zsviczian/excalidraw/types/excalidraw/types";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { GlobalPoint } from "@zsviczian/excalidraw/types/math/src/types";
|
||||
@@ -67,12 +67,18 @@ declare namespace ExcalidrawLib {
|
||||
) => { width: number; height: number; scale?: number };
|
||||
};
|
||||
|
||||
function restore(
|
||||
data: Pick<ImportedDataState, "appState" | "elements" | "files"> | null,
|
||||
localAppState: Partial<AppState> | null | undefined,
|
||||
localElements: readonly ExcalidrawElement[] | null | undefined,
|
||||
elementsConfig?: { refreshDimensions?: boolean; repairBindings?: boolean },
|
||||
): RestoredDataState;
|
||||
function restoreElements <T extends ExcalidrawElement>(
|
||||
targetElements: readonly T[] | undefined | null,
|
||||
/** used for additional context (e.g. repairing arrow bindings) */
|
||||
existingElements: Readonly<ElementsMapOrArray> | null | undefined,
|
||||
opts?:
|
||||
| {
|
||||
refreshDimensions?: boolean;
|
||||
repairBindings?: boolean;
|
||||
deleteInvisibleElements?: boolean;
|
||||
}
|
||||
| undefined,
|
||||
) : CombineBrandsIfNeeded<T, OrderedExcalidrawElement>;
|
||||
|
||||
function exportToSvg(opts: Omit<ExportOpts, "getDimensions"> & {
|
||||
elements: ExcalidrawElement[];
|
||||
@@ -191,22 +197,23 @@ declare namespace ExcalidrawLib {
|
||||
|
||||
function getEmbedLink (link: string | null | undefined): EmbeddedLink;
|
||||
|
||||
function mermaidToExcalidraw(
|
||||
const mermaidToExcalidraw: typeof import("@zsviczian/excalidraw/types/excalidraw/components/TTDDialog/MermaidToExcalidrawLib").mermaidToExcalidraw;
|
||||
|
||||
/*function mermaidToExcalidraw(
|
||||
mermaidDefinition: string,
|
||||
opts: MermaidConfig,
|
||||
forceSVG?: boolean,
|
||||
): Promise<{
|
||||
elements?: ExcalidrawElement[];
|
||||
files?: any;
|
||||
error?: string;
|
||||
} | undefined>;
|
||||
} | undefined>;*/
|
||||
|
||||
var getSceneVersion: any;
|
||||
var Excalidraw: any;
|
||||
var MainMenu: any;
|
||||
var WelcomeScreen: any;
|
||||
var TTDDialogTrigger: any;
|
||||
var TTDDialog: any;
|
||||
var TTDDialogTrigger: typeof import("@zsviczian/excalidraw").TTDDialogTrigger;
|
||||
var TTDDialog: typeof import("@zsviczian/excalidraw").TTDDialog;
|
||||
var DiagramToCodePlugin: (props: {
|
||||
generate: GenerateDiagramToCode;
|
||||
}) => any;
|
||||
|
||||
@@ -67,4 +67,5 @@ export interface ViewSemaphores {
|
||||
saving: boolean;
|
||||
hoverSleep: boolean; //flag with timer to prevent hover preview from being triggered dozens of times
|
||||
wheelTimeout:number; //used to avoid hover preview while zooming
|
||||
shouldSaveImportedImage: boolean; //forceSave after image import via the Excalidraw Image Tool or by way of paste
|
||||
}
|
||||
@@ -7,11 +7,12 @@ const handleImageEditPrompt = async (request: AIRequest) : Promise<RequestUrlRes
|
||||
const {
|
||||
openAIAPIToken,
|
||||
openAIImageEditsURL,
|
||||
openAIDefaultImageGenerationModel,
|
||||
} = plugin.settings;
|
||||
const { image, text, imageGenerationProperties} = request;
|
||||
|
||||
const body = new FormData();
|
||||
body.append("model", "dall-e-2");
|
||||
body.append("model", openAIDefaultImageGenerationModel);
|
||||
text.trim() !== "" && body.append("prompt", text);
|
||||
|
||||
if (image) {
|
||||
@@ -21,7 +22,7 @@ const handleImageEditPrompt = async (request: AIRequest) : Promise<RequestUrlRes
|
||||
|
||||
if (imageGenerationProperties.mask) {
|
||||
const maskBlob = await fetch(imageGenerationProperties.mask).then((res) => res.blob());
|
||||
body.append('mask', maskBlob, 'masik.png');
|
||||
body.append('mask', maskBlob, 'mask.png');
|
||||
}
|
||||
|
||||
imageGenerationProperties.size && body.append("size", imageGenerationProperties.size);
|
||||
|
||||
@@ -13,7 +13,7 @@ import ExcalidrawView, { getTextMode } from "src/view/ExcalidrawView";
|
||||
import {
|
||||
GITHUB_RELEASES,
|
||||
getCommonBoundingBox,
|
||||
restore,
|
||||
restoreElements,
|
||||
REG_LINKINDEX_INVALIDCHARS,
|
||||
THEME_FILTER,
|
||||
EXCALIDRAW_PLUGIN,
|
||||
@@ -59,15 +59,48 @@ export function isSVGColorInfo(obj: ColorMap | SVGColorInfo): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
const COLOR_MAP_INVERT_KEY = "invertindarkmode";
|
||||
const isReservedColorMapKey = (key: string) => key.toLocaleLowerCase() === COLOR_MAP_INVERT_KEY;
|
||||
|
||||
//Normalize color maps and lift the invertInDarkMode flag out of color entries
|
||||
export function normalizeColorMap(colorMap?: ColorMap | null): ColorMap | null {
|
||||
if (!colorMap || typeof colorMap !== "object") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalized: ColorMap = {};
|
||||
const invert = (colorMap as Record<string, unknown>).invertInDarkMode ?? (colorMap as Record<string, unknown>)[COLOR_MAP_INVERT_KEY];
|
||||
if (typeof invert === "boolean") {
|
||||
normalized.invertInDarkMode = invert;
|
||||
}
|
||||
|
||||
for (const [key, value] of Object.entries(colorMap)) {
|
||||
if (isReservedColorMapKey(key) || typeof value !== "string") {
|
||||
continue;
|
||||
}
|
||||
const normalizedKey = key.toLocaleLowerCase();
|
||||
const normalizedValue = value.toLocaleLowerCase();
|
||||
normalized[normalizedKey] = normalizedValue;
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function mergeColorMapIntoSVGColorInfo(
|
||||
colorMap: ColorMap,
|
||||
svgColorInfo: SVGColorInfo
|
||||
): SVGColorInfo {
|
||||
if(colorMap) {
|
||||
for(const key of Object.keys(colorMap)) {
|
||||
if(svgColorInfo.has(key)) {
|
||||
svgColorInfo.get(key).mappedTo = colorMap[key];
|
||||
const normalized = normalizeColorMap(colorMap);
|
||||
if(normalized) {
|
||||
for(const key of Object.keys(normalized)) {
|
||||
if(isReservedColorMapKey(key)) {
|
||||
continue;
|
||||
}
|
||||
const mappedTo = normalized[key];
|
||||
if(!svgColorInfo.has(key) || typeof mappedTo !== "string") {
|
||||
continue;
|
||||
}
|
||||
svgColorInfo.get(key).mappedTo = mappedTo;
|
||||
}
|
||||
}
|
||||
return svgColorInfo;
|
||||
@@ -84,9 +117,23 @@ export function svgColorInfoToColorMap(svgColorInfo: SVGColorInfo): ColorMap {
|
||||
|
||||
//Remove identical key-value pairs from a ColorMap
|
||||
export function filterColorMap(colorMap: ColorMap): ColorMap {
|
||||
return Object.fromEntries(
|
||||
Object.entries(colorMap).filter(([key, value]) => key.toLocaleLowerCase() !== value?.toLocaleLowerCase())
|
||||
);
|
||||
const normalized = normalizeColorMap(colorMap) ?? {};
|
||||
const filtered: ColorMap = {};
|
||||
|
||||
if (typeof normalized.invertInDarkMode === "boolean") {
|
||||
filtered.invertInDarkMode = normalized.invertInDarkMode;
|
||||
}
|
||||
|
||||
Object.entries(normalized).forEach(([key, value]) => {
|
||||
if (isReservedColorMapKey(key) || typeof value !== "string") {
|
||||
return;
|
||||
}
|
||||
if (key.toLocaleLowerCase() !== value.toLocaleLowerCase()) {
|
||||
filtered[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
return filtered;
|
||||
}
|
||||
|
||||
export function updateOrAddSVGColorInfo(
|
||||
@@ -647,7 +694,7 @@ export function repositionElementsToCursor(
|
||||
element.y = element.y + offsetY;
|
||||
});
|
||||
|
||||
return restore({elements}, null, null).elements;
|
||||
return restoreElements(elements, null, {refreshDimensions: true, repairBindings: true});
|
||||
}
|
||||
|
||||
export const insertLaTeXToView = (view: ExcalidrawView, center: boolean = false) => {
|
||||
@@ -667,24 +714,8 @@ export const insertLaTeXToView = (view: ExcalidrawView, center: boolean = false)
|
||||
3
|
||||
)
|
||||
).then(async (formula: string) => {
|
||||
const lastLatexEl = ea.getViewElements()
|
||||
.filter((el) => el.type === "image" && view.excalidrawData.hasEquation(el.fileId))
|
||||
.reduce(
|
||||
(maxel, curr) => (!maxel || curr.updated > maxel.updated) ? curr : maxel,
|
||||
undefined
|
||||
) as ExcalidrawImageElement;
|
||||
let scaleX = 1;
|
||||
let scaleY = 1;
|
||||
if (lastLatexEl) {
|
||||
const equation = view.excalidrawData.getEquation(lastLatexEl.fileId);
|
||||
const dataurl = await ea.tex2dataURL(equation.latex);
|
||||
if (dataurl.size.width > 0 && dataurl.size.height > 0) {
|
||||
scaleX = lastLatexEl.width/dataurl.size.width;
|
||||
scaleY = lastLatexEl.height/dataurl.size.height;
|
||||
}
|
||||
}
|
||||
if (formula) {
|
||||
const id = await ea.addLaTex(0, 0, formula, scaleX, scaleY);
|
||||
const id = await ea.addLaTex(0, 0, formula);
|
||||
if(center) {
|
||||
const el = ea.getElement(id);
|
||||
let {width, height} = el;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
|
||||
import { MAX_IMAGE_SIZE, IMAGE_TYPES, ANIMATED_IMAGE_TYPES, MD_EX_SECTIONS, AUDIO_TYPES, CARD_WIDTH, CARD_HEIGHT, getDefaultColorPalette } from "src/constants/constants";
|
||||
import { MAX_IMAGE_SIZE, IMAGE_TYPES, ANIMATED_IMAGE_TYPES, MD_EX_SECTIONS, AUDIO_TYPES, CARD_WIDTH, CARD_HEIGHT, getDefaultColorPalette, DEVICE } from "src/constants/constants";
|
||||
import { App, Modal, Notice, TFile } from "obsidian";
|
||||
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
|
||||
import { REGEX_LINK, REG_LINKINDEX_HYPERLINK, getExcalidrawMarkdownHeaderSection, REGEX_TAGS, getExcalidrawMarkdownHeader } from "../shared/ExcalidrawData";
|
||||
@@ -624,3 +624,14 @@ export function getViewColorPalette(
|
||||
|
||||
return [...groups, ...sortedExtras];
|
||||
}
|
||||
|
||||
//!Temporary hack
|
||||
//https://discord.com/channels/686053708261228577/817515900349448202/1031101635784613968
|
||||
export const setMobileNavbarPosition = (dock:boolean) => {
|
||||
if (DEVICE.isMobile && dock) {
|
||||
const navbar = document.querySelector("body>.app-container>.mobile-navbar");
|
||||
if(navbar && navbar instanceof HTMLDivElement) {
|
||||
navbar.style.position= dock ? "relative" : "";
|
||||
}
|
||||
}
|
||||
}
|
||||
+155
-57
@@ -46,10 +46,11 @@ import {
|
||||
EXPORT_IMG_ICON_NAME,
|
||||
viewportCoordsToSceneCoords,
|
||||
ERROR_IFRAME_CONVERSION_CANCELED,
|
||||
restore,
|
||||
restoreElements,
|
||||
obsidianToExcalidrawMap,
|
||||
MAX_IMAGE_SIZE,
|
||||
fileid,
|
||||
sceneCoordsToViewportCoords,
|
||||
MD_EX_SECTIONS,
|
||||
refreshTextDimensions,
|
||||
getContainerElement,
|
||||
@@ -117,7 +118,7 @@ import {
|
||||
import { cleanBlockRef, cleanSectionHeading, closeLeafView, getAttachmentsFolderAndFilePath, getExcalidraAndMarkdowViewsForFile, getLeaf, getParentOfClass, obsidianPDFQuoteWithRef, openLeaf, setExcalidrawView } from "../utils/obsidianUtils";
|
||||
import { splitFolderAndFilename } from "../utils/fileUtils";
|
||||
import { GenericInputPrompt, LaTexPrompt, MultiOptionConfirmationPrompt, NewFileActions, Prompt, linkPrompt } from "../shared/Dialogs/Prompt";
|
||||
import { ClipboardData } from "@zsviczian/excalidraw/types/excalidraw/clipboard";
|
||||
import { ClipboardData, ParsedDataTransferFile } from "@zsviczian/excalidraw/types/excalidraw/clipboard";
|
||||
import { updateEquation } from "../shared/LaTeX";
|
||||
import {
|
||||
EmbeddedFile,
|
||||
@@ -135,7 +136,7 @@ import { getEA } from "src/core"
|
||||
import { anyModifierKeysPressed, emulateKeysForLinkClick, isWinALTorMacOPT, isWinCTRLorMacCMD, isWinMETAorMacCTRL, isSHIFT, linkClickModifierType, ModifierKeys } from "../utils/modifierkeyHelper";
|
||||
import { setDynamicStyle } from "../utils/dynamicStyling";
|
||||
import { CustomEmbeddable, renderWebView } from "./components/CustomEmbeddable";
|
||||
import { addBackOfTheNoteCard, deleteAppStateKeys, getExcalidrawFileForwardLinks, getFrameBasedOnFrameNameOrId, getLinkTextFromLink, insertEmbeddableToView, insertImageToView, isTextImageTransclusion, onLoadMessages, openExternalLink, parseObsidianLink, renderContextMenuAction, sceneRemoveInternalLinks, tmpBruteForceCleanup, toggleImageAnchoring } from "../utils/excalidrawViewUtils";
|
||||
import { addBackOfTheNoteCard, deleteAppStateKeys, getExcalidrawFileForwardLinks, getFrameBasedOnFrameNameOrId, getLinkTextFromLink, insertEmbeddableToView, insertImageToView, isTextImageTransclusion, onLoadMessages, openExternalLink, parseObsidianLink, renderContextMenuAction, sceneRemoveInternalLinks, setMobileNavbarPosition, tmpBruteForceCleanup, toggleImageAnchoring } from "../utils/excalidrawViewUtils";
|
||||
import { imageCache } from "../shared/ImageCache";
|
||||
import { CanvasNodeFactory, ObsidianCanvasNode } from "./managers/CanvasNodeFactory";
|
||||
import { EmbeddableMenu } from "./components/menu/EmbeddableActionsMenu";
|
||||
@@ -144,13 +145,14 @@ import { UniversalInsertFileModal } from "../shared/Dialogs/UniversalInsertFileM
|
||||
import { getMermaidText, shouldRenderMermaid } from "../utils/mermaidUtils";
|
||||
import { nanoid } from "nanoid";
|
||||
import { CustomMutationObserver, DEBUGGING, debug, log} from "../utils/debugHelper";
|
||||
import { errorHTML, extractCodeBlocks, postOpenAI } from "../utils/AIUtils";
|
||||
import { errorHTML, extractCodeBlocks } from "../utils/AIUtils";
|
||||
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
|
||||
import { SelectCard } from "../shared/Dialogs/SelectCard";
|
||||
import { Packages } from "../types/types";
|
||||
import React from "react";
|
||||
import { diagramToHTML } from "../utils/matic";
|
||||
import { IS_WORKER_SUPPORTED } from "../shared/Workers/compression-worker";
|
||||
import { getPDFCropRect } from "../utils/PDFUtils";
|
||||
import { AutoexportConfig, Position, ViewSemaphores } from "../types/excalidrawViewTypes";
|
||||
import { DropManager } from "./managers/DropManager";
|
||||
import { ImageInfo } from "src/types/excalidrawAutomateTypes";
|
||||
@@ -328,6 +330,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
forceSaving: false,
|
||||
hoverSleep: false,
|
||||
wheelTimeout: null,
|
||||
shouldSaveImportedImage: false,
|
||||
};
|
||||
|
||||
public _plugin: ExcalidrawPlugin;
|
||||
@@ -1077,12 +1080,6 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
const ea = getEA(this) as ExcalidrawAutomate;
|
||||
ea.copyViewElementsToEAforEditing([el]);
|
||||
ea.addAppendUpdateCustomData(el.id, {latex: formula});
|
||||
const dataurl = await ea.tex2dataURL(equation);
|
||||
if (dataurl && dataurl.size.height > 0 && dataurl.size.width > 0) {
|
||||
ea.addAppendUpdateCustomData(el.id, {
|
||||
latexscale: {scaleX: el.width/dataurl.size.width, scaleY: el.height/dataurl.size.height}
|
||||
});
|
||||
}
|
||||
await ea.addElementsToView(false, false, false, false);
|
||||
await this.save(false);
|
||||
await updateEquation(
|
||||
@@ -1185,6 +1182,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
}
|
||||
|
||||
const hide = (el:HTMLElement) => {
|
||||
el.style.marginTop = "0px";
|
||||
let tmpEl = el;
|
||||
while(tmpEl && !tmpEl.hasClass("workspace-split")) {
|
||||
el.addClass(SHOW);
|
||||
@@ -1236,6 +1234,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
const doc = this.ownerDocument;
|
||||
doc.querySelectorAll(".excalidraw-hidden").forEach(el=>el.removeClass(HIDE));
|
||||
doc.querySelectorAll(".excalidraw-visible").forEach(el=>el.removeClass(SHOW));
|
||||
this.contentEl.style.marginTop = "";
|
||||
}
|
||||
|
||||
removeLinkTooltip() {
|
||||
@@ -1429,7 +1428,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
let file = null;
|
||||
let subpath: string = null;
|
||||
let {linkText, selectedElement, isLinearElement} = this.getLinkTextForElement(selectedText, selectedElementWithLink, allowLinearElementClick);
|
||||
|
||||
|
||||
//if (selectedText?.id || selectedElementWithLink?.id) {
|
||||
if (selectedElement) {
|
||||
if (!allowLinearElementClick && linkText && isLinearElement) {
|
||||
@@ -1755,6 +1754,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
await(sleep(50));
|
||||
if(!this?.plugin) return;
|
||||
}
|
||||
setMobileNavbarPosition(true);
|
||||
if(!Boolean(this?.plugin?.activeLeafChangeEventHandler)) return;
|
||||
if (Boolean(this.plugin.activeLeafChangeEventHandler) && (this?.app?.workspace?.activeLeaf === this.leaf)) {
|
||||
this.plugin.activeLeafChangeEventHandler(this.leaf);
|
||||
@@ -2201,9 +2201,14 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
super.onunload();
|
||||
this.destroyers.forEach((destroyer) => destroyer());
|
||||
this.restoreMobileLeaves();
|
||||
setMobileNavbarPosition(false);
|
||||
this.semaphores.viewunload = true;
|
||||
this.semaphores.popoutUnload = (this.ownerDocument !== document) && (this.ownerDocument.body.querySelectorAll(".workspace-tab-header").length === 0);
|
||||
|
||||
if(this.shouldSaveImportedImageTimer) {
|
||||
window.clearTimeout(this.shouldSaveImportedImageTimer);
|
||||
}
|
||||
|
||||
if(this.getHookServer().onViewUnloadHook) {
|
||||
try {
|
||||
this.getHookServer().onViewUnloadHook(this);
|
||||
@@ -2638,7 +2643,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
if(imageCache.isReady() && this.excalidrawData.scene && this.excalidrawData.scene.elements && this.excalidrawData.scene.elements.length === 0) {
|
||||
const backup = await imageCache.getBAKFromCache(this.file.path);
|
||||
if(backup && backup.length > data.length) {
|
||||
setTimeout(async () => {
|
||||
window.setTimeout(async () => {
|
||||
const confirmationPrompt = new MultiOptionConfirmationPrompt(
|
||||
this.plugin,
|
||||
t("BACKUP_SAVE_AS_FILE"),
|
||||
@@ -4153,7 +4158,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
//dobule click
|
||||
const now = Date.now();
|
||||
if ((now - this.doubleClickTimestamp) < 600 && (now - this.doubleClickTimestamp) > 40) {
|
||||
this.identifyElementClicked();
|
||||
this.identifyElementClicked();
|
||||
}
|
||||
this.doubleClickTimestamp = now;
|
||||
}
|
||||
@@ -4232,21 +4237,22 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
}
|
||||
}
|
||||
|
||||
private shouldSaveImportedImage: boolean = false;
|
||||
private onChange (et: ExcalidrawElement[], st: AppState) {
|
||||
private onChange (et: ExcalidrawElement[], st: AppState, files: BinaryFileData[]) {
|
||||
if(st.activeTool?.type) {
|
||||
if(st.activeTool.type === "image") {
|
||||
if(st.selectedElementIds && Object.keys(st.selectedElementIds).length === 1) {
|
||||
const selectedElement = et.filter(el=>el.id === Object.keys(st.selectedElementIds)[0])[0];
|
||||
if(selectedElement && selectedElement.type === "image") {
|
||||
this.shouldSaveImportedImage = true;
|
||||
this.setShouldSaveImportedImageFlag();
|
||||
}
|
||||
}
|
||||
}
|
||||
if(st.activeTool.type === "selection" && this.shouldSaveImportedImage) {
|
||||
this.shouldSaveImportedImage = false;
|
||||
setTimeout(()=>this.save(true, true),100); //image is being added to the scene
|
||||
}
|
||||
}
|
||||
if(
|
||||
this.semaphores.shouldSaveImportedImage &&
|
||||
Object.values(files).some(file=> !file.hasOwnProperty("hasSVGwithBitmap"))
|
||||
) {
|
||||
window.setTimeout(()=>this.forceSave(true)); //image is being added to the scene
|
||||
}
|
||||
|
||||
if(st.newElement?.type === "freedraw") {
|
||||
@@ -4320,10 +4326,24 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
})();
|
||||
}
|
||||
|
||||
private onPaste (data: ClipboardData, event: ClipboardEvent | null) {
|
||||
private shouldSaveImportedImageTimer: number = null;
|
||||
private setShouldSaveImportedImageFlag() {
|
||||
this.semaphores.shouldSaveImportedImage = true;
|
||||
if(this.shouldSaveImportedImageTimer) {
|
||||
window.clearTimeout(this.shouldSaveImportedImageTimer);
|
||||
}
|
||||
this.shouldSaveImportedImageTimer = window.setTimeout(()=>this.semaphores.shouldSaveImportedImage = false, 3000);
|
||||
}
|
||||
|
||||
private onPaste (data: ClipboardData, event: ClipboardEvent | null, files: ParsedDataTransferFile[]) {
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.onPaste, "ExcalidrawView.onPaste", data, event);
|
||||
const api = this.excalidrawAPI as ExcalidrawImperativeAPI;
|
||||
const ea = this.getHookServer();
|
||||
|
||||
if (files?.length || (data?.mixedContent && data.mixedContent.some(d=>d.type==="imageUrl"))) {
|
||||
this.setShouldSaveImportedImageFlag();
|
||||
}
|
||||
|
||||
if(data?.elements) {
|
||||
data.elements
|
||||
.filter(el=>el.type==="text" && !el.hasOwnProperty("rawText"))
|
||||
@@ -4388,18 +4408,32 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
}
|
||||
|
||||
if(isTextImageTransclusion(data.text,this, async (link, file)=>{
|
||||
const ea = getEA(this) as ExcalidrawAutomate;
|
||||
if(IMAGE_TYPES.contains(file.extension)) {
|
||||
const ea = getEA(this) as ExcalidrawAutomate;
|
||||
ea.selectElementsInView([await insertImageToView (ea, this.currentPosition, file)]);
|
||||
ea.destroy();
|
||||
} else if(file.extension !== "pdf") {
|
||||
const ea = getEA(this) as ExcalidrawAutomate;
|
||||
ea.selectElementsInView([await insertEmbeddableToView (ea, this.currentPosition, file, link)]);
|
||||
ea.destroy();
|
||||
} else {
|
||||
if(link.match(/^[^#]*#page=\d*(&\w*=[^&]+){0,}&rect=\d*,\d*,\d*,\d*/g)) {
|
||||
const ea = getEA(this) as ExcalidrawAutomate;
|
||||
await ea.addImage(this.currentPosition.x, this.currentPosition.y, link);
|
||||
const imgID = await ea.addImage(this.currentPosition.x, this.currentPosition.y,link.split("&rect=")[0]);
|
||||
const el = ea.getElement(imgID) as Mutable<ExcalidrawImageElement>;
|
||||
const fd = ea.imagesDict[el.fileId] as FileData;
|
||||
el.crop = getPDFCropRect({
|
||||
scale: this.plugin.settings.pdfScale,
|
||||
link,
|
||||
naturalHeight: fd.size.height,
|
||||
naturalWidth: fd.size.width,
|
||||
pdfPageViewProps: fd.pdfPageViewProps,
|
||||
});
|
||||
addAppendUpdateCustomData(el, {pdfPageViewProps: fd.pdfPageViewProps});
|
||||
if(el.crop) {
|
||||
el.width = el.crop.width/this.plugin.settings.pdfScale;
|
||||
el.height = el.crop.height/this.plugin.settings.pdfScale;
|
||||
}
|
||||
el.link = `[[${link}]]`;
|
||||
ea.addElementsToView(false,false).then(()=>ea.destroy());
|
||||
} else {
|
||||
const modal = new UniversalInsertFileModal(this.plugin, this);
|
||||
@@ -5218,9 +5252,9 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
() => {
|
||||
const markerEnabled = !(frameRendering.markerEnabled && frameRendering.enabled && frameRendering.outline);
|
||||
if(markerEnabled) {
|
||||
setTimeout(() => this.updateScene({appState: {frameRendering: {...frameRendering, enabled: true, outline: true, markerEnabled}}, captureUpdate: CaptureUpdateAction.NEVER}));
|
||||
window.setTimeout(() => this.updateScene({appState: {frameRendering: {...frameRendering, enabled: true, outline: true, markerEnabled}}, captureUpdate: CaptureUpdateAction.NEVER}));
|
||||
} else {
|
||||
setTimeout(() => this.updateScene({appState: {frameRendering: {...frameRendering, markerEnabled}}, captureUpdate: CaptureUpdateAction.NEVER}));
|
||||
window.setTimeout(() => this.updateScene({appState: {frameRendering: {...frameRendering, markerEnabled}}, captureUpdate: CaptureUpdateAction.NEVER}));
|
||||
}
|
||||
},
|
||||
onClose
|
||||
@@ -5234,7 +5268,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
? t("MARKER_FRAME_TITLE_HIDE")
|
||||
: t("MARKER_FRAME_TITLE_SHOW"),
|
||||
() => {
|
||||
setTimeout(() => this.updateScene({appState: {frameRendering: {...frameRendering, markerName: !frameRendering.markerName}}, captureUpdate: CaptureUpdateAction.NEVER}));
|
||||
window.setTimeout(() => this.updateScene({appState: {frameRendering: {...frameRendering, markerName: !frameRendering.markerName}}, captureUpdate: CaptureUpdateAction.NEVER}));
|
||||
},
|
||||
onClose
|
||||
),
|
||||
@@ -5281,56 +5315,120 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
};
|
||||
|
||||
private ttdDialog() {
|
||||
const systemPrompt = "The user will provide you with a text prompt. Your task is to generate a mermaid diagram based on the prompt. Use the graph, sequenceDiagram, flowchart or classDiagram types based on what best fits the request. Return a single message containing only the mermaid diagram in a codeblock. Avoid the use of `()` parenthesis in the mermaid script.";
|
||||
const instruction = "Return a single message containing only the mermaid diagram in a codeblock.";
|
||||
|
||||
return this.packages.react.createElement(
|
||||
this.packages.excalidrawLib.TTDDialog,
|
||||
{
|
||||
onTextSubmit: async (input:string) => {
|
||||
onTextSubmit: async (props: any) => {
|
||||
const { messages = [], onChunk, onStreamCreated, signal } = props ?? {};
|
||||
const {
|
||||
openAIAPIToken,
|
||||
openAIDefaultTextModel,
|
||||
openAIDefaultTextModelMaxTokens,
|
||||
openAIURL,
|
||||
} = this.plugin.settings;
|
||||
|
||||
if (!openAIAPIToken) {
|
||||
return {
|
||||
error: new Error("OpenAI API Token is not set. Please set it in plugin settings."),
|
||||
};
|
||||
}
|
||||
|
||||
const requestMessages = [
|
||||
{ role: "system", content: systemPrompt },
|
||||
...messages,
|
||||
{ role: "user", content: instruction },
|
||||
];
|
||||
|
||||
// Determine which token limit parameter to use based on model
|
||||
// Newer models (gpt-4o, gpt-5, o1, o3) use max_completion_tokens
|
||||
// Older models use max_tokens
|
||||
const useMaxCompletionTokens = openAIDefaultTextModel &&
|
||||
(openAIDefaultTextModel.includes("gpt-4o") ||
|
||||
openAIDefaultTextModel.includes("gpt-5") ||
|
||||
openAIDefaultTextModel.includes("o1") ||
|
||||
openAIDefaultTextModel.includes("o3"));
|
||||
|
||||
const tokenLimitParam = openAIDefaultTextModelMaxTokens > 0
|
||||
? (useMaxCompletionTokens
|
||||
? { max_completion_tokens: openAIDefaultTextModelMaxTokens }
|
||||
: { max_tokens: openAIDefaultTextModelMaxTokens })
|
||||
: {};
|
||||
|
||||
try {
|
||||
const response = await postOpenAI({
|
||||
systemPrompt: "The user will provide you with a text prompt. Your task is to generate a mermaid diagram based on the prompt. Use the graph, sequenceDiagram, flowchart or classDiagram types based on what best fits the request. Return a single message containing only the mermaid diagram in a codeblock. Avoid the use of `()` parenthesis in the mermaid script.",
|
||||
text: input,
|
||||
instruction: "Return a single message containing only the mermaid diagram in a codeblock.",
|
||||
})
|
||||
const resp = await fetch(openAIURL, {
|
||||
method: "post",
|
||||
body: JSON.stringify({
|
||||
model: openAIDefaultTextModel,
|
||||
...tokenLimitParam,
|
||||
messages: requestMessages,
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${openAIAPIToken}`,
|
||||
},
|
||||
signal,
|
||||
});
|
||||
|
||||
if(!response) {
|
||||
onStreamCreated?.();
|
||||
|
||||
if (!resp) {
|
||||
return { error: new Error("Request failed") };
|
||||
}
|
||||
|
||||
const rateLimitHeader = resp.headers.get("x-ratelimit-limit");
|
||||
const rateLimitRemainingHeader = resp.headers.get("x-ratelimit-remaining");
|
||||
const rateLimit = rateLimitHeader && !Number.isNaN(Number(rateLimitHeader)) ? Number(rateLimitHeader) : null;
|
||||
const rateLimitRemaining = rateLimitRemainingHeader && !Number.isNaN(Number(rateLimitRemainingHeader)) ? Number(rateLimitRemainingHeader) : null;
|
||||
|
||||
const json = await resp.json();
|
||||
(process.env.NODE_ENV === "development") && DEBUGGING && debug(this.ttdDialog, `ExcalidrawView.ttdDialog > onTextSubmit, openAI response`, json);
|
||||
|
||||
if (!resp.ok || json?.error) {
|
||||
log(json);
|
||||
return {
|
||||
error: new Error("Request failed"),
|
||||
error: new Error(json?.error?.message ?? `Request failed with status ${resp.status}`),
|
||||
rateLimit,
|
||||
rateLimitRemaining,
|
||||
};
|
||||
}
|
||||
|
||||
const json = response.json;
|
||||
(process.env.NODE_ENV === 'development') && DEBUGGING && debug(this.ttdDialog, `ExcalidrawView.ttdDialog > onTextSubmit, openAI response`, response);
|
||||
|
||||
if (json?.error) {
|
||||
log(response);
|
||||
return {
|
||||
error: new Error(json.error.message),
|
||||
};
|
||||
}
|
||||
|
||||
if(!json?.choices?.[0]?.message?.content) {
|
||||
log(response);
|
||||
const content = json?.choices?.[0]?.message?.content;
|
||||
if (!content) {
|
||||
log(json);
|
||||
return {
|
||||
error: new Error("Generation failed... see console log for details"),
|
||||
rateLimit,
|
||||
rateLimitRemaining,
|
||||
};
|
||||
}
|
||||
|
||||
let generatedResponse = extractCodeBlocks(json.choices[0]?.message?.content)[0]?.data;
|
||||
let generatedResponse = extractCodeBlocks(content)[0]?.data ?? content.trim();
|
||||
|
||||
if(!generatedResponse) {
|
||||
log(response);
|
||||
if (!generatedResponse) {
|
||||
log(json);
|
||||
return {
|
||||
error: new Error("Generation failed... see console log for details"),
|
||||
rateLimit,
|
||||
rateLimitRemaining,
|
||||
};
|
||||
}
|
||||
|
||||
if(generatedResponse.startsWith("mermaid")) {
|
||||
generatedResponse = generatedResponse.replace(/^mermaid/,"").trim();
|
||||
if (generatedResponse.startsWith("mermaid")) {
|
||||
generatedResponse = generatedResponse.replace(/^mermaid/, "").trim();
|
||||
}
|
||||
|
||||
return { generatedResponse, rateLimit:100, rateLimitRemaining:100 };
|
||||
|
||||
onChunk?.(generatedResponse);
|
||||
|
||||
return { generatedResponse, rateLimit, rateLimitRemaining };
|
||||
} catch (err: any) {
|
||||
throw new Error("Request failed");
|
||||
if (err?.name === "AbortError") {
|
||||
return { error: new Error("Request aborted") };
|
||||
}
|
||||
console.log(err);
|
||||
return { error: new Error("Request failed") };
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -6236,7 +6334,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
}
|
||||
const shouldRestoreElements = scene.elements && shouldRestore;
|
||||
if (shouldRestoreElements) {
|
||||
scene.elements = restore(scene, null, null).elements;
|
||||
scene.elements = restoreElements(scene.elements, null, {refreshDimensions: true, repairBindings: true});
|
||||
}
|
||||
if(Boolean(scene.appState)) {
|
||||
//@ts-ignore
|
||||
@@ -6258,7 +6356,7 @@ export default class ExcalidrawView extends TextFileView implements HoverParent{
|
||||
if (!shouldRestoreElements) {
|
||||
//second attempt
|
||||
try {
|
||||
scene.elements = restore(scene, null, null).elements;
|
||||
scene.elements = restoreElements(scene.elements, null, {refreshDimensions: true, repairBindings: true});
|
||||
api.updateScene(scene);
|
||||
} catch (e) {
|
||||
errorlog({
|
||||
|
||||
@@ -380,6 +380,39 @@ export class ExcalidrawSidepanelView extends ItemView {
|
||||
return this.restorePromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-runs the script backing an existing tab, typically after the script file was updated.
|
||||
*/
|
||||
public async restartTabForScript(scriptName: string): Promise<void> {
|
||||
await this.waitUntilReady();
|
||||
if (!scriptName) {
|
||||
return;
|
||||
}
|
||||
const tab = this.getTabByScript(scriptName);
|
||||
if (!tab) {
|
||||
return;
|
||||
}
|
||||
|
||||
const title = tab.title;
|
||||
const wasPersisted = this.persistedScripts.has(scriptName);
|
||||
|
||||
// Fully terminate the existing tab and its EA host before rerunning the script
|
||||
// to avoid scripts early-exiting when they detect an already active tab.
|
||||
this.removeTab(tab);
|
||||
|
||||
const previousSilent = ExcalidrawSidepanelView.restoreSilent;
|
||||
ExcalidrawSidepanelView.restoreSilent = true;
|
||||
try {
|
||||
await this.runScriptByName(scriptName, title);
|
||||
const restarted = this.getTabByScript(scriptName);
|
||||
if (wasPersisted && restarted) {
|
||||
this.markTabPersistent(restarted);
|
||||
}
|
||||
} finally {
|
||||
ExcalidrawSidepanelView.restoreSilent = previousSilent;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a script by name to reconstruct its sidepanel tab, updating title if needed.
|
||||
*/
|
||||
|
||||
Reference in new issue
Block a user