Compare commits

..
Author SHA1 Message Date
zsviczian 0320307324 updated package-lock 2026-06-26 19:30:17 +02:00
zsviczian 90928f9905 update release and codespaces to node 22 2026-06-26 19:23:37 +02:00
zsviczian f4668f2b35 2.25.0-beta.0, 0.18.108 (new freedraw tool) 2026-06-26 19:07:35 +02:00
zsviczian 1d8b5d9942 added halo options to comicbook callout editor 2026-06-26 18:54:49 +02:00
zsviczian 4f880120b7 added extraThin line width 2026-06-26 12:29:06 +02:00
zsviczian 4269c78fc3 new freedraw pen, 0.18.107 2026-06-25 23:24:59 +02:00
zsviczian d82c558daf fix replace in scene button 2026-06-23 21:18:37 +02:00
zsviczian a6009a5c49 fix 2813, 2810 2026-06-22 19:19:33 +02:00
zsviczian 0b1fb8a443 Update mtime for Comicbook Callout Editor.md 2026-06-22 12:00:33 +02:00
zsviczian fde2f117d3 migrated to the sidepanel 2026-06-22 11:59:40 +02:00
zsviczian 106340efc5 refactor comicbook callout editor 2026-06-21 20:56:39 +02:00
zsviczian ab9463c0a5 callout editor updated 2026-06-21 08:12:36 +02:00
zsviczian 288cfe6013 spelling 2026-06-20 15:23:42 +02:00
zsviczian 33acdb5d29 Publishing Comicbook callout editor 2026-06-20 15:15:26 +02:00
zsviczian 620e397947 Comic Callouts 1.0 2026-06-20 12:07:45 +02:00
zsviczian 9fa9394592 updated settings UI, added font config 2026-06-20 11:46:30 +02:00
zsviczian e989e64fd6 comic callouts update 2026-06-19 23:00:20 +02:00
zsviczian 779e413ed8 comic callout editor initial commit 2026-06-19 20:18:38 +02:00
zsviczian 73a90fda05 fixed messages :( 2026-06-17 22:03:01 +02:00
zsviczian 8d9efe1e38 2.24.2, 0.18.106 2026-06-17 21:50:56 +02:00
zsviczian 1136ebc88a move to mjs (maybe that will fix the node.fs warning ?? 2026-06-17 21:46:12 +02:00
zsviczian 40a0694a0f Merge pull request #2811 from zsviczian/lock-embeedable-reading-mode
Lock embeedable reading mode, polybool, popout freeze
2026-06-17 21:30:04 +02:00
zsviczian 123cac8e00 0.18.106, fix exitFullScreen freezing obsidian when popout window is closed after moving an embeddable element. attempted fix for polybool 2026-06-17 21:28:37 +02:00
zsviczian c140f24473 2 issues remaining (stuck semaphore, embeddActionMenu change) 2026-06-17 20:35:03 +02:00
zsviczian f2a911c47c first implementation, not yet working 2026-06-17 12:13:17 +00:00
zsviczian 30eb992484 Merge pull request #2809 from Lumintian/fix/i18n-expose-deflate-helper
fix(i18n): expose unpackBase64Deflate on window for locale loading
2026-06-17 11:46:27 +02:00
Lumintian bb3eb684c0 fix(i18n): expose unpackBase64Deflate on window for locale loading
The Rollup banner defines unpackBase64Deflate locally but never assigns it
to window. src/lang/helpers.ts (loadLocale) reads window.unpackBase64Deflate
to decompress PLUGIN_LANGUAGES entries; because it is undefined, loadLocale()
returns the English locale for every non-English language. This leaves the
entire Excalidraw settings UI in English even when Obsidian itself is set to
another language (reproduced with Simplified Chinese on 2.24.1).

Window.unpackBase64Deflate is already declared in src/types/types.d.ts, so
exposing the helper in the banner matches the intended runtime contract and
is the minimal fix.
2026-06-17 09:57:35 +08:00
zsviczian 11a5c06190 2.24.1 2026-06-15 22:58:41 +02:00
zsviczian 168d0e5fa6 Merge pull request #2806 from zsviczian/260615
2.24.0
2026-06-15 20:58:40 +02:00
zsviczian 30b20ebaf0 2.24.0 2026-06-15 20:57:18 +02:00
zsviczian 841db04f75 renderComponent 2026-06-15 20:51:09 +02:00
zsviczian d61131e321 getLeaf(), Excalidraw Loading... 2026-06-15 20:20:50 +02:00
zsviczian f45a9ebd66 activeLeaf, isUnwantedLeaf 2026-06-15 19:00:28 +02:00
zsviczian 757147ad4b disabled wait for font, fixed few type issues 2026-06-15 11:15:29 +00:00
zsviczian a57db28e22 Merge pull request #2803 from zsviczian/260614
Mostly lint
2026-06-14 22:36:04 +02:00
zsviczian 64f105b11b 2.24.0-beta-4 2026-06-14 22:34:51 +02:00
zsviczian fccc325825 0.18.103 2026-06-14 20:48:25 +02:00
zsviczian 7843d9ce51 lint 2026-06-14 20:39:48 +02:00
zsviczian 894350739a eslint type error fixing 2026-06-14 20:39:15 +02:00
zsviczian 53eae64ed3 lint 2026-06-14 20:12:38 +02:00
zsviczian ec426ce5ea Mindmap Builder, lint errors, 2026-06-14 20:10:48 +02:00
zsviczian 97c4381f64 remove await for initializeFont, fix universalInsertFileModal capturing keyboard events 2026-06-14 16:58:50 +02:00
zsviczian 25220bb6fc Release notes for runtime pens 2026-06-14 07:42:50 +02:00
zsviczian c3c666e0c9 fixed main.ts type issues with MonkeyPatch implementation. 2026-06-14 06:49:10 +02:00
zsviczian ee479985f6 Merge remote-tracking branch 'origin/master' into 260614 2026-06-14 06:33:35 +02:00
zsviczian ab799ab836 Merge pull request #2801 from arias007/codex/custom-pens-independent-state
Keep custom pen runtime state independent
2026-06-14 06:32:00 +02:00
zsviczian 629763ed7a Move monkeypatch to MonkeyPatchManager 2026-06-14 06:25:05 +02:00
Murat e0f9326a8b Keep custom pen state independent 2026-06-14 01:55:00 +08:00
zsviczian 2fb2ffbc4c 2.24.0-beta-3 2026-06-13 14:31:15 +02:00
zsviczian 9fcabc2d94 fixed hasOwn(null) 2026-06-13 14:30:47 +02:00
zsviczian cc8af155c7 lint 2026-06-13 14:13:58 +02:00
zsviczian 33e8085161 Merge pull request #2797 from iwanhoogendoorn/update-color-scheme-manager-v3
Update Color Scheme Manager script
2026-06-13 13:36:27 +02:00
zsviczian 5af5844556 Merge pull request #2798 from zsviczian/260612
Type fixes
2026-06-13 13:35:26 +02:00
zsviczian d2ed7faefa 2.24.0-beta-2 2026-06-13 13:34:43 +02:00
zsviczian 44bb246572 mostly type fixes 2026-06-13 13:34:14 +02:00
zsviczian 0a7ec898d1 Object.hasOwn 2026-06-13 10:01:05 +02:00
zsviczian 84c77180e1 instanceOf typechecks, use fileManager.trashFile, unexpected lexical declaration 2026-06-13 09:26:04 +02:00
zsviczian 809c722855 activeLeaf to getMostRecentLeaf, Expected an assignment or function call and instead saw an expression. 2026-06-13 07:02:56 +02:00
iwanhoogendoorn e6c05292a7 Update Color Scheme Manager script
- Themable canvas background per scheme (defaults to white; CANVAS: import key)
- Stroke/fill/canvas palettes stratified like the default palette (strong / pastel / paper tints)
- Full colour editor on every pick: spectrum/sliders/eyedropper, HEX, RGB or native palette
- Top-pick rows: fixed anchors (black / transparent) + 4 editable slots, edits no longer dropped
- 'Expand theme -> picker': 55 swatches per picker, 5 lightness levels per accent, uniform neutrals row
- Multi-object selection: each object gets its own stroke+fill pair from the theme; re-click cycles the assignment
- Heals legacy auto-saved pickers that froze identical stroke/fill grids
2026-06-12 21:57:39 +02:00
zsviczian 4ad249db22 eslint configuration 2026-06-12 16:57:46 +02:00
zsviczian 46ac969f4e Merge pull request #2796 from zsviczian/fix-lint-issues
excalidraw extras fixes
2026-06-12 07:58:19 +02:00
zsviczian 573397868b verify min plugin version 2026-06-12 07:56:07 +02:00
zsviczian 278e6d9976 fixed mermaid load 2026-06-12 07:09:07 +02:00
zsviczian fb2b782bd4 Merge pull request #2794 from zsviczian/excalidraw-extras-initial
excalidraw extras 1.0 implementation
2026-06-10 21:48:38 +02:00
zsviczian 421f2ec21a remove update to toolspanel 2026-06-10 21:45:51 +02:00
zsviczian 1759cdffab mindmap builder update 2026-06-09 18:27:48 +02:00
zsviczian e7af4b62ac updated capture note 2026-06-09 08:26:07 +02:00
100 changed files with 18127 additions and 3885 deletions

No files matched your search

+4 -4
View File
@@ -1,9 +1,9 @@
{
"name": "Node.js 20",
"image": "mcr.microsoft.com/devcontainers/javascript-node:20",
"name": "Node.js 22",
"image": "mcr.microsoft.com/devcontainers/javascript-node:22",
"features": {
"ghcr.io/devcontainers/features/node:1": {
"version": "20"
"version": "22"
}
},
"postCreateCommand": "npm install",
@@ -14,4 +14,4 @@
]
}
}
}
}
-7
View File
@@ -1,7 +0,0 @@
{
"extends": ["@excalidraw/eslint-config"],
"rules": {
"import/no-anonymous-default-export": "off",
"no-restricted-globals": "off"
}
}
+2 -2
View File
@@ -20,11 +20,11 @@ jobs:
steps:
# 1. Pull down your repository code
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v5
# 2. Tell the server to install Node 22
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version: '22'
+4
View File
@@ -0,0 +1,4 @@
{
"tabWidth": 2,
"useTabs": false
}
+4 -1
View File
@@ -1,6 +1,6 @@
{
"typescript.tsdk": "node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true,
"typescript.enablePromptUseWorkspaceTsdk": true,
"typescript.tsserver.log": "off",
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
@@ -13,6 +13,9 @@
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"editor.tabSize": 2,
"editor.insertSpaces": true,
"editor.formatOnSave": true,
"eslint.validate": [
"javascript",
"javascriptreact",
+15
View File
@@ -0,0 +1,15 @@
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "lint",
"problemMatcher": "$eslint-stylish",
"group": {
"kind": "build",
"isDefault": true
},
"label": "Run Project Linting"
}
]
}
@@ -331,6 +331,7 @@ export declare class ExcalidrawAutomate {
startArrowHead: string;
endArrowHead: string;
};
setStyle(style: Partial<ExcalidrawAutomate["style"]>): void;
canvas: {
theme: string;
viewBackgroundColor: string;
@@ -1087,8 +1088,8 @@ export declare class ExcalidrawAutomate {
* @param {ExcalidrawElement[]} [scene.elements] - Array of elements in the scene.
* @param {AppState} [scene.appState] - The app state of the scene.
* @param {BinaryFiles} [scene.files] - The files in the scene.
* @param {boolean} [scene.commitToHistory] - Whether to commit the scene to history. @deprecated Use scene.storageOption instead
* @param {"capture" | "none" | "update"} [scene.storeAction] - The store action for the scene. @deprecated Use scene.storageOption instead
* @param {boolean} [scene.commitToHistory] - Deprecated: Use scene.storageOption instead.
* @param {"capture" | "none" | "update"} [scene.storeAction] - Deprecated: Use scene.storageOption instead
* @param {"IMMEDIATELY" | "NEVER" | "EVENTUALLY"} [scene.captureUpdate] - The capture update action for the scene.
* @param {boolean} [restore=false] - Whether to restore legacy elements in the scene.
*/
@@ -1808,6 +1809,26 @@ export interface FrameRenderingOptions {
clip: boolean;
}
export type PaneTarget = "active-pane" | "new-pane" | "popout-window" | "new-tab" | "md-properties";
export interface NestedFileNode {
file: TFile;
/**
* All distinct dependency paths from the root file down to this embedded file.
* Each path is an ordered array of TFile objects starting with the `rootFile` at index 0.
*
* @example
* If Root -> A -> B2.2 and Root -> B -> B2 -> B2.2
* The paths for B2.2 will be:
* [
* [Root, A, B2.2],
* [Root, B, B2, B2.2]
* ]
*
* Usage: To find which top-level embeds to reload if this file changes,
* you can map over `paths` and collect `path[1]`.
*/
paths: TFile[][];
}
export type NestedFileMap = Map<TFile, NestedFileNode>;
/* ************************************ */
/* lib/types/exportUtilTypes.d.ts */
@@ -1900,6 +1921,71 @@ export interface ExportSettings {
frameRendering?: FrameRenderingOptions;
skipInliningFonts?: boolean;
}
export interface PrintToPDFOptions {
includeName: boolean;
pageSize: string | {
width: number;
height: number;
};
landscape: boolean;
margins: {
top: number;
left: number;
right: number;
bottom: number;
};
scaleFactor: number;
scale: number;
open: boolean;
filepath: string;
preferCSSPageSize?: boolean;
pageRanges?: string | {
from: number;
to: number;
}[];
}
export interface SaveDialogOptions {
defaultPath: string;
filters: {
name: string;
extensions: string[];
}[];
properties: string[];
}
export interface SaveDialogReturnValue {
canceled: boolean;
filePath?: string;
}
type CaptureRect = {
x: number;
y: number;
width: number;
height: number;
};
type NativeImageLike = {
toPNG(): Uint8Array | Buffer;
};
interface ElectronWebContentsLike {
capturePage(rect: CaptureRect): Promise<NativeImageLike>;
getZoomFactor(): number;
setZoomFactor(factor: number): void;
}
interface ElectronWebUtilsLike {
getPathForFile(file: File): string;
}
export interface ElectronAPI {
ipcRenderer: {
send(channel: string, ...args: unknown[]): void;
once(channel: string, func: (...args: unknown[]) => void): void;
};
remote: {
dialog: {
showSaveDialog(options: SaveDialogOptions): Promise<SaveDialogReturnValue>;
};
getCurrentWebContents(): ElectronWebContentsLike;
};
webUtils: ElectronWebUtilsLike;
}
/* ************************************** */
/* lib/types/embeddedFileLoaderTypes.d.ts */
@@ -2906,6 +2992,7 @@ export type OnExportProgress = {
};
export interface ExcalidrawProps {
onChange?: (elements: readonly OrderedExcalidrawElement[], appState: AppState, files: BinaryFiles) => void;
onThemeChange?: (theme: Theme | "system") => void;
/**
* note: only subscribes if the props.onIncrement is defined on initial render
*/
@@ -2982,7 +3069,6 @@ export interface ExcalidrawProps {
nextLink: string;
};
generateIdForFile?: (file: File) => string | Promise<string>;
onThemeChange?: (newTheme: string) => void;
onViewModeChange?: (isViewModeEnabled: boolean) => void;
generateLinkForSelection?: (id: string, type: "element" | "group") => string;
onLinkOpen?: (element: NonDeletedExcalidrawElement, event: CustomEvent<{
@@ -3049,6 +3135,11 @@ export type CanvasActions = Partial<{
export: false | ExportOpts;
loadScene: boolean;
saveToActiveFile: boolean;
/**
* defaults to true if `props.theme` is omitted or `props.onThemeChange`
* is supplied (at which point the theme is considered as host-app controlled),
* else default to false
* */
toggleTheme: boolean | null;
saveAsImage: boolean;
}>;
@@ -3383,6 +3474,23 @@ export declare const pointInsideBounds: <P extends GlobalPoint | LocalPoint>(p:
export declare const pointInsideBoundsInclusive: <P extends GlobalPoint | LocalPoint>(p: P, bounds: Bounds) => boolean;
export declare const doBoundsIntersect: (bounds1: Bounds | null, bounds2: Bounds | null) => boolean;
export declare const boundsContainBounds: (outerBounds: Bounds, innerBounds: Bounds) => boolean;
/**
* High level helper to get elements overlapping a bounding box.
* It can be used to get elements overlapping a selection box, for example.
*
*/
export declare const elementsOverlappingBBox: ({ elements, elementsMap, bounds, type, excludeElementsInFrames, shouldIgnoreElementFromSelection, }: {
elements: readonly NonDeletedExcalidrawElement[];
elementsMap?: ElementsMap;
bounds: Bounds | ExcalidrawElement;
/**
* - overlap: elements overlapping or inside bounds
* - contain: elements inside bounds
**/
type: "contain" | "overlap";
excludeElementsInFrames?: boolean;
shouldIgnoreElementFromSelection?: (element: NonDeletedExcalidrawElement) => boolean;
}) => NonDeletedExcalidrawElement[];
export declare const elementCenterPoint: (element: ExcalidrawElement, elementsMap: ElementsMap, xOffset?: number, yOffset?: number) => GlobalPoint;
/* ************************************** */
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+100 -34
View File
@@ -682,7 +682,7 @@ async function prepareTargetExcalidrawView(noteBWorkspaceLeaf) {
}
// Injects the visual frame marker and template onto the target Note B
async function injectVisualFormat(target_ea, targetX, targetY, sectionRawText, todayDNPBasename, isCurrentDNP, preGeneratedFrameID, embeddedElementId, ontologyAction, originFilePath) {
async function injectVisualFormat(target_ea, targetX, targetY, sectionRawText, todayDNPBasename, isCurrentDNP, preGeneratedFrameID, embeddedElementId, ontologyAction, originFilePath, opt) {
const fWidth = parseInt(settings.frameWidth) || 1920;
const fHeight = parseInt(settings.frameHeight) || 1080;
@@ -715,9 +715,15 @@ async function injectVisualFormat(target_ea, targetX, targetY, sectionRawText, t
}
let clonedTemplateElementIds = [];
if (settings.visualTemplateJSON) {
// Resolve Visual Template details with fallback to global settings
const visualTemplateJSON = opt?.visualTemplateJSON || settings.visualTemplateJSON;
const visualTemplateHAlign = opt?.visualTemplateHAlign || settings.visualTemplateHAlign || "center";
const visualTemplateVAlign = opt?.visualTemplateVAlign || settings.visualTemplateVAlign || "middle";
if (visualTemplateJSON) {
try {
const parsed = JSON.parse(settings.visualTemplateJSON);
const parsed = JSON.parse(visualTemplateJSON);
if (parsed.elements && parsed.elements.length > 0) {
const clonedElements = ExcalidrawLib.restoreElements(
target_ea.cloneElements(parsed.elements,
@@ -735,17 +741,17 @@ async function injectVisualFormat(target_ea, targetX, targetY, sectionRawText, t
let offsetX = 0;
let offsetY = 0;
if (settings.visualTemplateHAlign === "left") {
if (visualTemplateHAlign === "left") {
offsetX = targetX - bounds[0] + FRAME_MARGIN;
} else if (settings.visualTemplateHAlign === "right") {
} else if (visualTemplateHAlign === "right") {
offsetX = targetX + fWidth - bounds[2] - FRAME_MARGIN;
} else {
offsetX = targetX + (fWidth - boundsWidth) / 2 - bounds[0];
}
if (settings.visualTemplateVAlign === "top") {
if (visualTemplateVAlign === "top") {
offsetY = targetY - bounds[1] + FRAME_MARGIN;
} else if (settings.visualTemplateVAlign === "bottom") {
} else if (visualTemplateVAlign === "bottom") {
offsetY = targetY + fHeight - bounds[3] - FRAME_MARGIN;
} else {
offsetY = targetY + (fHeight - boundsHeight) / 2 - bounds[1];
@@ -1131,6 +1137,11 @@ async function handleFinalActionFocus(actionType, originView, noteBWorkspaceLeaf
target_ea.viewZoomToElements(format !== "Visual", targetElements, 0.1);
}
}
// Set MMB view if Visual and mmAPI is available
if (format === "Visual" && window.MindMapBuilderAPI && target_ea.targetView) {
window.MindMapBuilderAPI.setView(target_ea.targetView);
}
}
}
@@ -1434,7 +1445,7 @@ async function start() {
// 11. Inject onto Target Note using preGeneratedFrameID
let clonedTemplateElementIds = [];
if (format === "Visual") {
const visualRes = await injectVisualFormat(target_ea, targetX, targetY, sectionRawText, todayDNPBasename, isCurrentDNP, preGeneratedFrameID, embeddedElementId, ontologyAction, originView.file.path);
const visualRes = await injectVisualFormat(target_ea, targetX, targetY, sectionRawText, todayDNPBasename, isCurrentDNP, preGeneratedFrameID, embeddedElementId, ontologyAction, originView.file.path, opt);
clonedTemplateElementIds = visualRes.clonedTemplateElementIds;
} else {
await injectMarkdownFormat(file, target_ea, targetX, targetY, sectionRawText, sectionWithBrackets, todayDNPBasename, isCurrentDNP, preGeneratedFrameID, embeddedElementId, ontologyAction, originView.file.path);
@@ -1601,28 +1612,49 @@ function buildCaptureSearchBox(contentEl, state, callbacks) {
return;
}
// Tokenize the query into individual words for partial matching
const q = query.toLowerCase().trim();
const searchTerms = q.split(/\s+/);
// Helper to escape regex special characters
const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const tokens = q.split(/\s+/);
// Create an ordered regex pattern (e.g. "my.*search.*term")
const fuzzyRegex = new RegExp(tokens.map(escapeRegex).join('.*'), 'i');
const uniqueItems = new Map();
const scoredItems = new Map();
state.searchItems.forEach(item => {
const searchableText = item.type === "alias" ? `${item.basename} ${item.alias}` : item.basename;
const searchableTextLower = searchableText.toLowerCase();
// Search against the full file path if available, otherwise fallback to basename
const searchableText = item.file
? item.file.path + (item.type === "alias" && item.alias ? " " + item.alias : "")
: item.basename;
// Ensure all partial words are found
const matches = searchTerms.every(term => searchableTextLower.includes(term));
if (matches) {
if (fuzzyRegex.test(searchableText)) {
// Evaluate if it's an exact match on either the basename or alias
const isExactBasename = item.basename.toLowerCase() === q;
const isExactAlias = item.type === "alias" && item.alias.toLowerCase() === q;
const isExact = isExactBasename || isExactAlias;
const mtime = item.file?.stat?.mtime || 0;
// Include file path to differentiate identical basenames
const pathSuffix = item.file ? `:${item.file.path}` : "";
const key = item.type === "alias" ? `alias:${item.basename}:${item.alias}${pathSuffix}` : `${item.type}:${item.basename}${pathSuffix}`;
if (!uniqueItems.has(key)) {
uniqueItems.set(key, item);
const current = scoredItems.get(key);
// Add to map if unique, or if it represents a higher scoring match instance
if (!current || isExact > current.isExact || (isExact === current.isExact && mtime > current.mtime)) {
scoredItems.set(key, { item, isExact, mtime });
}
}
});
matchedItems = Array.from(uniqueItems.values()).slice(0, 8);
// Sort exact matches to the top, then sort by most recently modified
matchedItems = Array.from(scoredItems.values())
.sort((a, b) => {
if (a.isExact !== b.isExact) return a.isExact ? -1 : 1;
return b.mtime - a.mtime;
})
.map(s => s.item)
.slice(0, 8);
if (matchedItems.length > 0) {
resultsDropdown.style.display = "block";
@@ -2108,11 +2140,11 @@ function buildVisualSizingSection(contentEl) {
.onChange(val => { settings.openNoteBBehavior = val; }));
}
async function refreshTemplatePreview(previewDiv, alignSettingsDiv, refreshCallback) {
async function refreshTemplatePreview(previewDiv, alignSettingsDiv, configObj, saveCallback, refreshCallback) {
previewDiv.empty();
alignSettingsDiv.empty();
if (!settings.visualTemplateJSON) {
if (!configObj.visualTemplateJSON) {
const pasteBtn = previewDiv.createEl("button", { text: "Paste Excalidraw Elements from Clipboard" });
pasteBtn.addEventListener("click", async () => {
try {
@@ -2123,8 +2155,16 @@ async function refreshTemplatePreview(previewDiv, alignSettingsDiv, refreshCallb
new Notice("Image elements are not supported in visual templates.");
return;
}
settings.visualTemplateJSON = text;
ea.setScriptSettings(settings);
// Run pasted elements through restoreElements
parsed.elements = window.ExcalidrawLib.restoreElements(
parsed.elements,
null,
{ refreshDimensions: true, repairBindings: true }
);
configObj.visualTemplateJSON = JSON.stringify(parsed);
saveCallback();
refreshCallback();
} else {
new Notice("Clipboard does not contain valid Excalidraw elements.");
@@ -2135,7 +2175,7 @@ async function refreshTemplatePreview(previewDiv, alignSettingsDiv, refreshCallb
});
} else {
try {
const parsed = JSON.parse(settings.visualTemplateJSON);
const parsed = JSON.parse(configObj.visualTemplateJSON);
const svg = await ea.createViewSVG({
elementsOverride: parsed.elements,
withBackground: false,
@@ -2152,8 +2192,8 @@ async function refreshTemplatePreview(previewDiv, alignSettingsDiv, refreshCallb
const delBtn = headerRow.createEl("button", { cls: "clickable-icon" });
delBtn.innerHTML = ea.obsidian.getIcon("trash-2").outerHTML;
delBtn.addEventListener("click", () => {
settings.visualTemplateJSON = "";
ea.setScriptSettings(settings);
configObj.visualTemplateJSON = "";
saveCallback();
refreshCallback();
});
@@ -2163,8 +2203,8 @@ async function refreshTemplatePreview(previewDiv, alignSettingsDiv, refreshCallb
.addOption("top", "Top")
.addOption("middle", "Middle")
.addOption("bottom", "Bottom")
.setValue(settings.visualTemplateVAlign || "middle")
.onChange(v => { settings.visualTemplateVAlign = v; ea.setScriptSettings(settings); })
.setValue(configObj.visualTemplateVAlign || "middle")
.onChange(v => { configObj.visualTemplateVAlign = v; saveCallback(); })
);
new ea.obsidian.Setting(alignSettingsDiv)
@@ -2173,12 +2213,12 @@ async function refreshTemplatePreview(previewDiv, alignSettingsDiv, refreshCallb
.addOption("left", "Left")
.addOption("center", "Center")
.addOption("right", "Right")
.setValue(settings.visualTemplateHAlign || "center")
.onChange(v => { settings.visualTemplateHAlign = v; ea.setScriptSettings(settings); })
.setValue(configObj.visualTemplateHAlign || "center")
.onChange(v => { configObj.visualTemplateHAlign = v; saveCallback(); })
);
} catch (e) {
settings.visualTemplateJSON = "";
ea.setScriptSettings(settings);
configObj.visualTemplateJSON = "";
saveCallback();
refreshCallback();
new Notice("Failed to load visual template preview.");
}
@@ -2192,7 +2232,13 @@ function buildVisualTemplateSection(contentEl) {
const previewDiv = templateSection.createDiv();
const alignSettingsDiv = templateSection.createDiv();
const refreshCallback = () => refreshTemplatePreview(previewDiv, alignSettingsDiv, refreshCallback);
const refreshCallback = () => refreshTemplatePreview(
previewDiv,
alignSettingsDiv,
settings,
() => ea.setScriptSettings(settings),
refreshCallback
);
refreshCallback();
}
@@ -2604,6 +2650,26 @@ function openEditNoteTypeModal(noteTypeKey, saveCallback) {
});
renderChips();
// Note Type Specific Visual Template Elements
const templateSection = contentEl.createEl("details", { cls: "setting-sub-section", attr: { style: "margin-top: 15px;" } });
templateSection.createEl("summary", { text: "Note Type Specific Visual Template Elements" });
templateSection.createEl("p", {
text: "If defined, these elements will override the global visual template.",
attr: { style: "color: var(--text-muted); font-size: 0.9em; margin-bottom: 10px;" }
});
const previewDiv = templateSection.createDiv();
const alignSettingsDiv = templateSection.createDiv();
const refreshVisualTemplateCallback = () => refreshTemplatePreview(
previewDiv,
alignSettingsDiv,
typeConfig,
() => {}, // Changes will be formally persisted when the modal "Save" button is clicked
refreshVisualTemplateCallback
);
refreshVisualTemplateCallback();
};
modal.onClose = () => {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-message-square-heart-icon lucide-message-square-heart"><path d="M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"/><path d="M7.5 9.5c0 .687.265 1.383.697 1.844l3.009 3.264a1.14 1.14 0 0 0 .407.314 1 1 0 0 0 .783-.004 1.14 1.14 0 0 0 .398-.31l3.008-3.264A2.77 2.77 0 0 0 16.5 9.5 2.5 2.5 0 0 0 12 8a2.5 2.5 0 0 0-4.5 1.5"/></svg>

After

Width:  |  Height:  |  Size: 597 B

+339 -76
View File
@@ -349,6 +349,34 @@ const STRINGS = {
MANUAL_JITTER_RANGE: "Manual-layout Jitter Range",
DESC_LAYOUT_MANUAL_JITTER: "Random position offset when adding nodes while Auto-Layout is disabled.",
CALENDAR_DATE_INDEX: "Date {index} of {total}",
CALENDAR_DATE_LABEL: "Date",
CALENDAR_DATE_TYPE: "Date Type",
CALENDAR_PRIORITY: "Priority",
CALENDAR_RECURRENCE: "Recurrence",
CALENDAR_RECURRENCE_PLACEHOLDER: "every day",
CALENDAR_RECURRENCE_DESC: "e.g., 'every day', 'every 2 weeks' <br><a href=\"https://publish.obsidian.md/tasks/Getting+Started/Recurring+Tasks\" target=\"_blank\" tabindex=\"-1\">Tasks recurrence docs</a>",
CALENDAR_INJECT_LINK: "Inject node link",
CALENDAR_INJECT_LINK_DESC: "Adds a link to the node at the end of the task.",
CALENDAR_ALIAS_PLACEHOLDER: "Alias",
CALENDAR_BTN_CANCEL: "Cancel",
CALENDAR_BTN_TASK_ONLY: "Task Only",
CALENDAR_BTN_ADD_DATE_TASK: "Add Date & Task",
CALENDAR_PRIORITY_HIGHEST: "Highest",
CALENDAR_PRIORITY_HIGH: "High",
CALENDAR_PRIORITY_MEDIUM: "Medium",
CALENDAR_PRIORITY_NORMAL: "Normal",
CALENDAR_PRIORITY_LOW: "Low",
CALENDAR_PRIORITY_LOWEST: "Lowest",
CALENDAR_DATETYPE_DUE: "Due",
CALENDAR_DATETYPE_START: "Start",
CALENDAR_DATETYPE_SCHEDULED: "Scheduled",
CALENDAR_DATETYPE_CREATED: "Created",
CALENDAR_DATETYPE_DONE: "Done",
CALENDAR_DATETYPE_CANCELLED: "Cancelled",
// Misc
INPUT_TITLE_PASTE_ROOT: "Mindmap Builder Paste",
INSTRUCTIONS: "> [!Tip]\n" +
@@ -598,6 +626,34 @@ addLocale("zh", {
MANUAL_JITTER_RANGE: "手动布局抖动范围",
DESC_LAYOUT_MANUAL_JITTER: "禁用自动布局时添加节点的随机位置偏移。",
CALENDAR_DATE_INDEX: "第 {index} 个日期,共 {total} 个",
CALENDAR_DATE_LABEL: "日期",
CALENDAR_DATE_TYPE: "日期类型",
CALENDAR_PRIORITY: "优先级",
CALENDAR_RECURRENCE: "重复",
CALENDAR_RECURRENCE_PLACEHOLDER: "每天",
CALENDAR_RECURRENCE_DESC: "例如,'every day'(每天),'every 2 weeks'(每两周)<br><a href=\"https://publish.obsidian.md/tasks/Getting+Started/Recurring+Tasks\" target=\"_blank\" tabindex=\"-1\">Tasks 插件重复任务文档</a>",
CALENDAR_INJECT_LINK: "插入节点链接",
CALENDAR_INJECT_LINK_DESC: "在任务末尾添加指向该节点的链接。",
CALENDAR_ALIAS_PLACEHOLDER: "别名",
CALENDAR_BTN_CANCEL: "取消",
CALENDAR_BTN_TASK_ONLY: "仅任务",
CALENDAR_BTN_ADD_DATE_TASK: "添加日期和任务",
CALENDAR_PRIORITY_HIGHEST: "最高",
CALENDAR_PRIORITY_HIGH: "高",
CALENDAR_PRIORITY_MEDIUM: "中",
CALENDAR_PRIORITY_NORMAL: "普通",
CALENDAR_PRIORITY_LOW: "低",
CALENDAR_PRIORITY_LOWEST: "最低",
CALENDAR_DATETYPE_DUE: "截止",
CALENDAR_DATETYPE_START: "开始",
CALENDAR_DATETYPE_SCHEDULED: "计划",
CALENDAR_DATETYPE_CREATED: "创建",
CALENDAR_DATETYPE_DONE: "完成",
CALENDAR_DATETYPE_CANCELLED: "取消",
// Misc
INPUT_TITLE_PASTE_ROOT: "MindMap Builder 粘贴",
INSTRUCTIONS: "> [!Tip]\n" +
@@ -838,6 +894,34 @@ addLocale("zh-tw", {
MANUAL_JITTER_RANGE: "手動佈局抖動範圍",
DESC_LAYOUT_MANUAL_JITTER: "停用自動佈局時新增節點的隨機位置偏移。",
CALENDAR_DATE_INDEX: "第 {index} 個日期,共 {total} 個",
CALENDAR_DATE_LABEL: "日期",
CALENDAR_DATE_TYPE: "日期類型",
CALENDAR_PRIORITY: "優先級",
CALENDAR_RECURRENCE: "重複",
CALENDAR_RECURRENCE_PLACEHOLDER: "每天",
CALENDAR_RECURRENCE_DESC: "例如,'every day'(每天),'every 2 weeks'(每兩週)<br><a href=\"https://publish.obsidian.md/tasks/Getting+Started/Recurring+Tasks\" target=\"_blank\" tabindex=\"-1\">Tasks 外掛重複任務文件</a>",
CALENDAR_INJECT_LINK: "插入節點連結",
CALENDAR_INJECT_LINK_DESC: "在任務末尾新增指向該節點的連結。",
CALENDAR_ALIAS_PLACEHOLDER: "別名",
CALENDAR_BTN_CANCEL: "取消",
CALENDAR_BTN_TASK_ONLY: "僅任務",
CALENDAR_BTN_ADD_DATE_TASK: "新增日期和任務",
CALENDAR_PRIORITY_HIGHEST: "最高",
CALENDAR_PRIORITY_HIGH: "高",
CALENDAR_PRIORITY_MEDIUM: "中",
CALENDAR_PRIORITY_NORMAL: "普通",
CALENDAR_PRIORITY_LOW: "低",
CALENDAR_PRIORITY_LOWEST: "最低",
CALENDAR_DATETYPE_DUE: "截止",
CALENDAR_DATETYPE_START: "開始",
CALENDAR_DATETYPE_SCHEDULED: "計畫",
CALENDAR_DATETYPE_CREATED: "建立",
CALENDAR_DATETYPE_DONE: "完成",
CALENDAR_DATETYPE_CANCELLED: "取消",
// Misc
INPUT_TITLE_PASTE_ROOT: "MindMap Builder 貼上",
INSTRUCTIONS: "> [!Tip]\n" +
@@ -941,6 +1025,17 @@ const K_PALETTE = "Custom Palette";
const K_LAYOUT = "Layout Config";
const K_ARROW_TYPE = "Arrow Type";
const K_FILL_SWEEP = "Fill Sweep";
const K_INJECT_LINK = "Inject Node Link";
const K_LINK_ALIAS = "Node Link Alias";
let injectNodeLink = getVal(K_INJECT_LINK, true);
let nodeLinkAlias = getVal(K_LINK_ALIAS, "(link)");
const isExcaliBrainView = () => {
if (!ea.targetView || !ea.targetView.file) return false;
const eb = app.plugins.plugins["excalibrain"];
return eb && eb.settings?.excalibrainFilepath === ea.targetView.file.path;
};
// ---------------------------------------------------------------------------
// Layout & Geometry Settings
@@ -5408,6 +5503,14 @@ const addNode = async (text, follow = false, skipFinalLayout = false, batchModeA
if (!isViewSet()) return;
if (!text || text.trim() === "") return;
const preGenTextId = ea.generateElementId();
if (text.includes("__NODE_LINK_PLACEHOLDER__")) {
const file = app.workspace.getActiveFile();
const fileName = file ? file.basename : "";
const linkStr = `[[${fileName}#^group=${preGenTextId}|${nodeLinkAlias}]]`;
text = text.replace("__NODE_LINK_PLACEHOLDER__", linkStr);
}
const st = getAppState();
const isBatchMode = batchModeAllElements !== null;
@@ -5480,6 +5583,30 @@ const addNode = async (text, follow = false, skipFinalLayout = false, batchModeA
nodeColor = parent.strokeColor;
}
}
const effectiveMulticolor = rootCfgForAdd?.multicolor ?? multicolor;
const effectiveIsSolidArrow = rootCfgForAdd?.isSolidArrow ?? isSolidArrow;
// If multicolor is disabled AND "Use scene stroke style" is enabled (!effectiveIsSolidArrow)
if (!effectiveMulticolor && !effectiveIsSolidArrow) {
const parentStrokeColor = (parent.strokeColor || "transparent").toLowerCase();
const isTransparent = parentStrokeColor === "transparent";
let isSameAsBg = false;
if (!isTransparent) {
const parentColorCM = ea.getCM(parent.strokeColor);
const bgColorCM = ea.getCM(st.viewBackgroundColor);
if (parentColorCM && bgColorCM && parentColorCM.stringHEX() === bgColorCM.stringHEX()) {
isSameAsBg = true;
}
}
// If the parent's stroke is transparent or matches the view background,
// invert the scene color for the new node and branch
if (isTransparent || isSameAsBg) {
nodeColor = ea.getCM(st.viewBackgroundColor).invert().stringHEX({ alpha: false });
}
}
}
const fontScale = getFontScale(rootCfgForAdd?.fontsizeScale ?? fontsizeScale);
@@ -5553,7 +5680,7 @@ const addNode = async (text, follow = false, skipFinalLayout = false, batchModeA
width: shouldWrap ? curMaxW : undefined,
height: shouldWrap ? curMaxH : undefined,
autoResize: !shouldWrap,
});
}, preGenTextId);
ea.style.backgroundColor = "transparent";
}
@@ -5721,7 +5848,7 @@ const addNode = async (text, follow = false, skipFinalLayout = false, batchModeA
width: shouldWrap ? curMaxW : undefined,
height: shouldWrap ? curMaxH : undefined,
autoResize: !shouldWrap,
});
}, preGenTextId);
}
if (depth === 1) {
@@ -8951,6 +9078,11 @@ const updateUI = (sel) => {
setButtonDisabled(focusBtn, false);
setButtonDisabled(floatingZoomBtn, false);
}
// Enable task buttons if there's text input
if (inputEl && inputEl.value.trim() !== "") {
if (toggleCheckboxBtn) setButtonDisabled(toggleCheckboxBtn, false);
if (calendarBtn) setButtonDisabled(calendarBtn, false);
}
}
};
@@ -9818,7 +9950,7 @@ const renderInput = (container, isFloating = false) => {
ignoreFocusChanges = true;
setTimeout(() => {
ignoreFocusChanges = false;
lastFocusedInput.focus();
if (lastFocusedInput) lastFocusedInput.focus();
}, 200);
container.empty();
@@ -9839,7 +9971,6 @@ const renderInput = (container, isFloating = false) => {
inputRow.controlEl.style.marginTop = "8px";
} else {
container.style.width = "85vw";
// Updated max width limit to fit up to 18 icons long as requested
container.style.maxWidth = "calc((var(--icon-size) + 2 * var(--size-2-3)) * 18)";
inputRow.settingEl.style.border = "none";
inputRow.settingEl.style.padding = "0";
@@ -9852,28 +9983,27 @@ const renderInput = (container, isFloating = false) => {
secondaryButtonContainer.style.flexWrap = "wrap";
secondaryButtonContainer.style.gap = "0px";
secondaryButtonContainer.style.marginTop = "6px";
secondaryButtonContainer.style.flexWrap = "wrap";
}
// Clear default control element to build custom two-input layout
inputRow.controlEl.empty();
const wrapper = inputRow.controlEl.createDiv("mindmap-input-wrapper");
// --- Ontology Input ---
ontologyEl = wrapper.createEl("input", {
type: "text",
cls: "mindmap-input-ontology",
placeholder: t("ONTOLOGY_PLACEHOLDER")
});
// --- Main Input ---
inputEl = wrapper.createEl("input", {
type: "text",
cls: "mindmap-input-main",
placeholder: t("INPUT_PLACEHOLDER")
});
inputEl.addEventListener("input", () => updateUI());
ontologyEl.addEventListener("input", () => updateUI());
const updateFocusState = (focusedElement) => {
if (ignoreFocusChanges) return;
isOntologyFocused = (focusedElement === ontologyEl);
@@ -9928,7 +10058,6 @@ const renderInput = (container, isFloating = false) => {
linkSuggester.modifyInput = (input) => input.replace(/\./g, " ");
}
// Accessibility / ARIA labels
const ariaHelp = [
`${getActionLabel(ACTION_ADD)} (Enter)`,
`${getActionLabel(ACTION_ADD_FOLLOW)} ${getActionHotkeyString(ACTION_ADD_FOLLOW)}`,
@@ -9988,7 +10117,6 @@ const renderInput = (container, isFloating = false) => {
btn.onClick(() => performAction(ACTION_TOGGLE_CHECKBOX));
}, true);
// Added calendar task date ontologies button
addButton((btn) => {
calendarBtn = btn;
btn.setIcon("calendar");
@@ -10862,6 +10990,34 @@ const registerStyles = () => {
".mindmap-input-main { flex: 17; transition: flex-grow 0.3s ease; min-width: 0; }",
".mindmap-input-ontology.is-focused { flex: 17; }",
".mindmap-input-main.is-shrunk { flex: 1; }",
// Drag Handle Styles
".excalidraw-mindmap-ui .mindmap-drag-handle {",
" position: absolute;",
" right: 0;",
" top: 0;",
" bottom: 0;",
" width: 20px;",
" cursor: grab;",
" display: flex;",
" align-items: center;",
" justify-content: center;",
" opacity: 0.4;",
" color: var(--text-muted);",
" transition: opacity 0.2s ease, color 0.2s ease;",
" background: var(--background-secondary);",
" border-left: 1px solid var(--background-modifier-border);",
" border-top-right-radius: 6px;",
" border-bottom-right-radius: 6px;",
"}",
".excalidraw-mindmap-ui:focus-within .mindmap-drag-handle,",
".excalidraw-mindmap-ui .mindmap-drag-handle:hover,",
".excalidraw-mindmap-ui .mindmap-drag-handle:active {",
" opacity: 1;",
" color: var(--text-normal);",
"}",
".excalidraw-mindmap-ui.is-dragging .mindmap-drag-handle {",
" cursor: grabbing;",
"}"
].join("\n");
document.head.appendChild(styleEl);
};
@@ -10970,12 +11126,61 @@ const toggleDock = async ({
headerEl.style.display = "none";
modalEl.style.opacity = `${FLOAT_MODAL_OPACITY}`;
modalEl.style.padding = "6px";
modalEl.style.paddingRight = "26px"; // Make room for the drag handle
modalEl.style.minHeight = "0px";
modalEl.style.width = "fit-content";
modalEl.style.height = "auto";
modalEl.style.maxHeight = FLOAT_MODAL_MAX_HEIGHT;
if (isExcaliBrainView()) {
modalEl.style.display = "none";
}
const container = floatingInputModal.contentEl.createDiv();
renderInput(container, true);
// Setup Drag Handle
const dragHandle = modalEl.createDiv("mindmap-drag-handle");
dragHandle.innerHTML = ea.obsidian.getIcon("grip-vertical").outerHTML;
let isDragging = false;
let startX, startY, initialLeft, initialTop;
dragHandle.addEventListener("pointerdown", (e) => {
isDragging = true;
startX = e.clientX;
startY = e.clientY;
const rect = modalEl.getBoundingClientRect();
initialLeft = rect.left;
initialTop = rect.top;
dragHandle.setPointerCapture(e.pointerId);
modalEl.classList.add("is-dragging");
e.preventDefault();
});
dragHandle.addEventListener("pointermove", (e) => {
if(!isDragging) return;
const dx = e.clientX - startX;
const dy = e.clientY - startY;
modalEl.style.left = `${initialLeft + dx}px`;
modalEl.style.top = `${initialTop + dy}px`;
});
dragHandle.addEventListener("pointerup", (e) => {
isDragging = false;
dragHandle.releasePointerCapture(e.pointerId);
modalEl.classList.remove("is-dragging");
});
dragHandle.addEventListener("dblclick", (e) => {
const { x, y } = ea.targetView.contentEl.getBoundingClientRect();
const desktopShift = !!ea.targetView.contentEl.querySelector(".App-bottom-bar .App-toolbar") ?
0 :
(ea.targetView.contentEl.clientWidth < 1200 ? 36 : 0);
modalEl.style.top = `${y + FLOAT_MODAL_OFFSET + desktopShift}px`;
modalEl.style.left = `${x + FLOAT_MODAL_OFFSET}px`;
});
setTimeout(() => {
//the modalEl is repositioned after a delay
//otherwise the event handlers in FloatingModal would override the move
@@ -11419,7 +11624,7 @@ const openCalendarModal = async () => {
};
leftNav.createSpan({
text: `Date ${activeDateIndex + 1} of ${dates.length}`
text: t("CALENDAR_DATE_INDEX", { index: activeDateIndex + 1, total: dates.length })
});
const nextBtn = leftNav.createEl("button");
@@ -11455,7 +11660,7 @@ const openCalendarModal = async () => {
// 1) Date picker input (Focus First)
new ea.obsidian.Setting(contentEl)
.setName("Date")
.setName(t("CALENDAR_DATE_LABEL"))
.addText(text => {
dateInputComp = text;
text.inputEl.type = "date";
@@ -11482,7 +11687,7 @@ const openCalendarModal = async () => {
// 2) Field type configuration selector matching active schema ontology
new ea.obsidian.Setting(contentEl)
.setName("Date Type")
.setName(t("CALENDAR_DATE_TYPE"))
.addDropdown(dropdown => {
typeDropdownComp = dropdown;
if (uiOpts.mode === 'dataview') {
@@ -11493,12 +11698,12 @@ const openCalendarModal = async () => {
dropdown.addOption("done", "✅ [done:: ]");
dropdown.addOption("cancelled", "❌ [cancelled:: ]");
} else {
dropdown.addOption("due", "📅 Due");
dropdown.addOption("start", "🛫 Start");
dropdown.addOption("scheduled", "⏳ Scheduled");
dropdown.addOption("created", "➕ Created");
dropdown.addOption("done", "✅ Done");
dropdown.addOption("cancelled", "❌ Cancelled");
dropdown.addOption("due", `📅 ${t("CALENDAR_DATETYPE_DUE")}`);
dropdown.addOption("start", `🛫 ${t("CALENDAR_DATETYPE_START")}`);
dropdown.addOption("scheduled", `⏳ ${t("CALENDAR_DATETYPE_SCHEDULED")}`);
dropdown.addOption("created", `➕ ${t("CALENDAR_DATETYPE_CREATED")}`);
dropdown.addOption("done", `✅ ${t("CALENDAR_DATETYPE_DONE")}`);
dropdown.addOption("cancelled", `❌ ${t("CALENDAR_DATETYPE_CANCELLED")}`);
}
dropdown.setValue(activeDateObj.type);
dropdown.onChange(val => {
@@ -11508,14 +11713,14 @@ const openCalendarModal = async () => {
// 3) Priority selector mapped to native Tasks emojis
new ea.obsidian.Setting(contentEl)
.setName("Priority")
.setName(t("CALENDAR_PRIORITY"))
.addDropdown(dropdown => {
dropdown.addOption("highest", "🔺 Highest");
dropdown.addOption("high", "⏫ High");
dropdown.addOption("medium", "🔼 Medium");
dropdown.addOption("normal", " Normal");
dropdown.addOption("low", "🔽 Low");
dropdown.addOption("lowest", "⏬ Lowest");
dropdown.addOption("highest", `🔺 ${t("CALENDAR_PRIORITY_HIGHEST")}`);
dropdown.addOption("high", `⏫ ${t("CALENDAR_PRIORITY_HIGH")}`);
dropdown.addOption("medium", `🔼 ${t("CALENDAR_PRIORITY_MEDIUM")}`);
dropdown.addOption("normal", ` ${t("CALENDAR_PRIORITY_NORMAL")}`);
dropdown.addOption("low", `🔽 ${t("CALENDAR_PRIORITY_LOW")}`);
dropdown.addOption("lowest", `⏬ ${t("CALENDAR_PRIORITY_LOWEST")}`);
dropdown.setValue(priority);
dropdown.onChange(val => {
priority = val;
@@ -11524,15 +11729,44 @@ const openCalendarModal = async () => {
// 4) Recurrence free text input
const recSetting = new ea.obsidian.Setting(contentEl)
.setName("Recurrence")
.setName(t("CALENDAR_RECURRENCE"))
.addText(text => {
text.setPlaceholder("every day")
text.setPlaceholder(t("CALENDAR_RECURRENCE_PLACEHOLDER"))
.setValue(recurrence)
.onChange(val => {
recurrence = val;
});
});
recSetting.descEl.innerHTML = `e.g., 'every day', 'every 2 weeks' <br><a href="https://publish.obsidian.md/tasks/Getting+Started/Recurring+Tasks" target="_blank" tabindex="-1">Tasks recurrence docs</a>`;
recSetting.descEl.innerHTML = t("CALENDAR_RECURRENCE_DESC");
// 5) Inject Node Link toggle
const linkSettingsRow = new ea.obsidian.Setting(contentEl)
.setName(t("CALENDAR_INJECT_LINK"))
.setDesc(t("CALENDAR_INJECT_LINK_DESC"));
let aliasTextComp;
linkSettingsRow.addToggle(toggle => {
toggle.setValue(injectNodeLink)
.onChange(val => {
injectNodeLink = val;
setVal(K_INJECT_LINK, val);
dirty = true;
aliasTextComp.inputEl.style.display = val ? "" : "none";
});
});
linkSettingsRow.addText(text => {
aliasTextComp = text;
text.setPlaceholder(t("CALENDAR_ALIAS_PLACEHOLDER"))
.setValue(nodeLinkAlias)
.onChange(val => {
nodeLinkAlias = val || "link";
setVal(K_LINK_ALIAS, nodeLinkAlias);
dirty = true;
});
text.inputEl.style.display = injectNodeLink ? "" : "none";
text.inputEl.style.width = "100px";
text.inputEl.style.marginLeft = "10px";
});
// Controls button block
const btnContainer = contentEl.createDiv({
@@ -11542,15 +11776,20 @@ const openCalendarModal = async () => {
});
const cancelBtn = btnContainer.createEl("button", {
text: "Cancel"
text: t("CALENDAR_BTN_CANCEL")
});
cancelBtn.onclick = () => modal.close();
const taskOnlyBtn = btnContainer.createEl("button", {
text: t("CALENDAR_BTN_TASK_ONLY")
});
taskOnlyBtn.onclick = () => handleSave(false);
const saveBtn = btnContainer.createEl("button", {
text: "Apply",
text: t("CALENDAR_BTN_ADD_DATE_TASK"),
cls: "mod-cta"
});
saveBtn.onclick = handleSave;
saveBtn.onclick = () => handleSave(true);
// Date picker auto-open / focus
setTimeout(() => {
@@ -11565,66 +11804,83 @@ const openCalendarModal = async () => {
}, 50);
};
const handleSave = async () => {
const handleSave = async (includeDate = true) => {
modal.close();
let tasksString = "";
const validDates = dates.filter(d => d.date);
if (uiOpts.mode === 'dataview') {
let priorityStr = "";
const priorityMap = {
'highest': '🔺',
'high': '⏫',
'medium': '🔼',
'normal': '',
'low': '🔽',
'lowest': '⏬'
};
if (priority !== 'normal') priorityStr = priorityMap[priority];
if (includeDate) {
const validDates = dates.filter(d => d.date);
if (uiOpts.mode === 'dataview') {
let priorityStr = "";
const priorityMap = {
'highest': '🔺',
'high': '⏫',
'medium': '🔼',
'normal': '',
'low': '🔽',
'lowest': '⏬'
};
if (priority !== 'normal') priorityStr = priorityMap[priority];
let dateStrs = validDates.map(d => `[${d.type}:: ${d.date}]`);
let recStr = recurrence ? `[recurrence:: ${recurrence}]` : "";
let dateStrs = validDates.map(d => `[${d.type}:: ${d.date}]`);
let recStr = recurrence ? `[recurrence:: ${recurrence}]` : "";
const parts = [priorityStr, ...dateStrs, recStr].filter(Boolean);
if (parts.length > 0) tasksString = " " + parts.join(" ");
} else {
let priorityStr = "";
const priorityMap = {
'highest': ' 🔺',
'high': ' ⏫',
'medium': ' 🔼',
'normal': '',
'low': ' 🔽',
'lowest': ' ⏬'
};
priorityStr = priorityMap[priority] || "";
const parts = [priorityStr, ...dateStrs, recStr].filter(Boolean);
if (parts.length > 0) tasksString = " " + parts.join(" ");
} else {
let priorityStr = "";
const priorityMap = {
'highest': ' 🔺',
'high': ' ⏫',
'medium': ' 🔼',
'normal': '',
'low': ' 🔽',
'lowest': ' ⏬'
};
priorityStr = priorityMap[priority] || "";
const emojiMap = {
'due': '📅',
'start': '🛫',
'scheduled': '⏳',
'created': '➕',
'done': '✅',
'cancelled': '❌'
};
let dateStrs = validDates.map(d => ` ${emojiMap[d.type]} ${d.date}`);
let recStr = recurrence ? ` 🔁 ${recurrence}` : "";
const emojiMap = {
'due': '📅',
'start': '🛫',
'scheduled': '⏳',
'created': '➕',
'done': '✅',
'cancelled': '❌'
};
let dateStrs = validDates.map(d => ` ${emojiMap[d.type]} ${d.date}`);
let recStr = recurrence ? ` 🔁 ${recurrence}` : "";
tasksString = `${priorityStr}${dateStrs.join("")}${recStr}`;
tasksString = `${priorityStr}${dateStrs.join("")}${recStr}`;
}
}
const taskRegex = /^- \[([ xX])\] (.*)/s;
const match = targetText.match(taskRegex);
let cleanText = cleanTasksString(match ? match[2] : targetText);
// Ensure we don't duplicate an existing auto-generated link at the end
const linkRegex = /\s*\(\[\[[^\]]+#\^group=[a-zA-Z0-9_-]+\|[^\]]+\]\]\)$/;
if (linkRegex.test(cleanText)) {
cleanText = cleanText.replace(linkRegex, "");
}
let finalPrefix = match ? `- [${match[1]}] ` : "- [ ] ";
let newText = `${finalPrefix}${cleanText}${tasksString}`;
if (injectNodeLink) {
if (isInputEl) {
newText += ` __NODE_LINK_PLACEHOLDER__`;
} else {
const file = app.workspace.getActiveFile();
const fileName = file ? file.basename : "";
newText += ` ([[${fileName}#^group=${textElId}|${nodeLinkAlias}]])`;
}
}
if (isInputEl) {
inputEl.value = newText;
debugger;
updateUI();
} else {
const all = ea.getViewElements();
@@ -11661,7 +11917,7 @@ const openCalendarModal = async () => {
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
e.stopPropagation();
handleSave();
handleSave(true);
}
// Prevent Escape from propagating to the underlying floating modal or canvas
if (e.key === "Escape") {
@@ -13148,6 +13404,7 @@ const handleCanvasPointerDown = (e) => {
}, 50);
};
/* --- Initialization Logic --- */
/* --- Initialization Logic --- */
ea.createSidepanelTab(t("DOCK_TITLE"), true, true).then((tab) => {
@@ -13279,9 +13536,15 @@ ea.createSidepanelTab(t("DOCK_TITLE"), true, true).then((tab) => {
const {
modalEl
} = floatingInputModal
if (modalEl.style.display === "none") {
modalEl.style.display = "";
if (isExcaliBrainView()) {
modalEl.style.display = "none";
} else {
if (modalEl.style.display === "none") {
modalEl.style.display = "";
}
}
if (ea.targetView && modalEl.ownerDocument !== ea.targetView.ownerDocument) {
ea.targetView.ownerDocument.body.appendChild(modalEl);
linkSuggester?.close();
File diff suppressed because it is too large. Load diff
+690 -1
View File
@@ -1 +1,690 @@
[{"fname":"Mindmap connector.md","mtime":1658686599427},{"fname":"Mindmap connector.svg","mtime":1658686599427},{"fname":"Add Connector Point.md","mtime":1735420748564},{"fname":"Add Connector Point.svg","mtime":1645944722000},{"fname":"Add Link to Existing File and Open.md","mtime":1647807918345},{"fname":"Add Link to Existing File and Open.svg","mtime":1645964261000},{"fname":"Add Link to New Page and Open.md","mtime":1654168862138},{"fname":"Add Link to New Page and Open.svg","mtime":1645960639000},{"fname":"Add Next Step in Process.md","mtime":1688304760357},{"fname":"Add Next Step in Process.svg","mtime":1645960639000},{"fname":"Box Each Selected Groups.md","mtime":1645305706000},{"fname":"Box Each Selected Groups.svg","mtime":1645967510000},{"fname":"Box Selected Elements.md","mtime":1645305706000},{"fname":"Box Selected Elements.svg","mtime":1645960639000},{"fname":"Change shape of selected elements.md","mtime":1652701169236},{"fname":"Change shape of selected elements.svg","mtime":1645960775000},{"fname":"Connect elements.md","mtime":1645305706000},{"fname":"Connect elements.svg","mtime":1645960639000},{"fname":"Convert freedraw to line.md","mtime":1645305706000},{"fname":"Convert freedraw to line.svg","mtime":1645960639000},{"fname":"Convert selected text elements to sticky notes.md","mtime":1670169501383},{"fname":"Convert selected text elements to sticky notes.svg","mtime":1645960639000},{"fname":"Convert text to link with folder and alias.md","mtime":1641639819000},{"fname":"Convert text to link with folder and alias.svg","mtime":1645960639000},{"fname":"Copy Selected Element Styles to Global.md","mtime":1642232088000},{"fname":"Copy Selected Element Styles to Global.svg","mtime":1645960639000},{"fname":"Create new markdown file and embed into active drawing.md","mtime":1640866935000},{"fname":"Create new markdown file and embed into active drawing.svg","mtime":1645960639000},{"fname":"Darken background color.md","mtime":1663059051059},{"fname":"Darken background color.svg","mtime":1645960639000},{"fname":"Elbow connectors.md","mtime":1671126911490},{"fname":"Elbow connectors.svg","mtime":1645960639000},{"fname":"Expand rectangles horizontally keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles horizontally keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles horizontally.md","mtime":1644950235000},{"fname":"Expand rectangles horizontally.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically keep text centered.md","mtime":1646563692000},{"fname":"Expand rectangles vertically keep text centered.svg","mtime":1645967510000},{"fname":"Expand rectangles vertically.md","mtime":1658686599427},{"fname":"Expand rectangles vertically.svg","mtime":1645967510000},{"fname":"Fixed horizontal distance between centers.md","mtime":1646743234000},{"fname":"Fixed horizontal distance between centers.svg","mtime":1645960639000},{"fname":"Fixed inner distance.md","mtime":1646743234000},{"fname":"Fixed inner distance.svg","mtime":1645960639000},{"fname":"Fixed spacing.md","mtime":1646743234000},{"fname":"Fixed spacing.svg","mtime":1645967510000},{"fname":"Fixed vertical distance between centers.md","mtime":1646743234000},{"fname":"Fixed vertical distance between centers.svg","mtime":1645967510000},{"fname":"Fixed vertical distance.md","mtime":1646743234000},{"fname":"Fixed vertical distance.svg","mtime":1645967510000},{"fname":"Lighten background color.md","mtime":1663059051059},{"fname":"Lighten background color.svg","mtime":1645959546000},{"fname":"Modify background color opacity.md","mtime":1644924415000},{"fname":"Modify background color opacity.svg","mtime":1645944722000},{"fname":"Normalize Selected Arrows.md","mtime":1670403743278},{"fname":"Normalize Selected Arrows.svg","mtime":1645960639000},{"fname":"Organic Line.md","mtime":1672920172531},{"fname":"Organic Line.svg","mtime":1645964261000},{"fname":"Organic Line Legacy.md","mtime":1690607372668},{"fname":"Organic Line Legacy.svg","mtime":1690607372668},{"fname":"README.md","mtime":1645175700000},{"fname":"Repeat Elements.md","mtime":1663059051059},{"fname":"Repeat Elements.svg","mtime":1645960639000},{"fname":"Reverse arrows.md","mtime":1645305706000},{"fname":"Reverse arrows.svg","mtime":1645960639000},{"fname":"Scribble Helper.md","mtime":1767536720161},{"fname":"Scribble Helper.svg","mtime":1645944722000},{"fname":"Select Elements of Type.md","mtime":1643464321000},{"fname":"Select Elements of Type.svg","mtime":1645960639000},{"fname":"Set Dimensions.md","mtime":1645305706000},{"fname":"Set Dimensions.svg","mtime":1645944722000},{"fname":"Set Font Family.md","mtime":1645305706000},{"fname":"Set Font Family.svg","mtime":1645944722000},{"fname":"Set Grid.md","mtime":1693725826368},{"fname":"Set Grid.svg","mtime":1645960639000},{"fname":"Set Link Alias.md","mtime":1645305706000},{"fname":"Set Link Alias.svg","mtime":1645960639000},{"fname":"Set Stroke Width of Selected Elements.md","mtime":1748189277Line truncated
[
{
"fname": "Mindmap connector.md",
"mtime": 1658686599427
},
{
"fname": "Mindmap connector.svg",
"mtime": 1658686599427
},
{
"fname": "Add Connector Point.md",
"mtime": 1735420748564
},
{
"fname": "Add Connector Point.svg",
"mtime": 1645944722000
},
{
"fname": "Add Link to Existing File and Open.md",
"mtime": 1647807918345
},
{
"fname": "Add Link to Existing File and Open.svg",
"mtime": 1645964261000
},
{
"fname": "Add Link to New Page and Open.md",
"mtime": 1654168862138
},
{
"fname": "Add Link to New Page and Open.svg",
"mtime": 1645960639000
},
{
"fname": "Add Next Step in Process.md",
"mtime": 1688304760357
},
{
"fname": "Add Next Step in Process.svg",
"mtime": 1645960639000
},
{
"fname": "Box Each Selected Groups.md",
"mtime": 1645305706000
},
{
"fname": "Box Each Selected Groups.svg",
"mtime": 1645967510000
},
{
"fname": "Box Selected Elements.md",
"mtime": 1645305706000
},
{
"fname": "Box Selected Elements.svg",
"mtime": 1645960639000
},
{
"fname": "Change shape of selected elements.md",
"mtime": 1652701169236
},
{
"fname": "Change shape of selected elements.svg",
"mtime": 1645960775000
},
{
"fname": "Connect elements.md",
"mtime": 1645305706000
},
{
"fname": "Connect elements.svg",
"mtime": 1645960639000
},
{
"fname": "Convert freedraw to line.md",
"mtime": 1645305706000
},
{
"fname": "Convert freedraw to line.svg",
"mtime": 1645960639000
},
{
"fname": "Convert selected text elements to sticky notes.md",
"mtime": 1670169501383
},
{
"fname": "Convert selected text elements to sticky notes.svg",
"mtime": 1645960639000
},
{
"fname": "Convert text to link with folder and alias.md",
"mtime": 1641639819000
},
{
"fname": "Convert text to link with folder and alias.svg",
"mtime": 1645960639000
},
{
"fname": "Copy Selected Element Styles to Global.md",
"mtime": 1642232088000
},
{
"fname": "Copy Selected Element Styles to Global.svg",
"mtime": 1645960639000
},
{
"fname": "Create new markdown file and embed into active drawing.md",
"mtime": 1640866935000
},
{
"fname": "Create new markdown file and embed into active drawing.svg",
"mtime": 1645960639000
},
{
"fname": "Darken background color.md",
"mtime": 1663059051059
},
{
"fname": "Darken background color.svg",
"mtime": 1645960639000
},
{
"fname": "Elbow connectors.md",
"mtime": 1671126911490
},
{
"fname": "Elbow connectors.svg",
"mtime": 1645960639000
},
{
"fname": "Expand rectangles horizontally keep text centered.md",
"mtime": 1646563692000
},
{
"fname": "Expand rectangles horizontally keep text centered.svg",
"mtime": 1645967510000
},
{
"fname": "Expand rectangles horizontally.md",
"mtime": 1644950235000
},
{
"fname": "Expand rectangles horizontally.svg",
"mtime": 1645967510000
},
{
"fname": "Expand rectangles vertically keep text centered.md",
"mtime": 1646563692000
},
{
"fname": "Expand rectangles vertically keep text centered.svg",
"mtime": 1645967510000
},
{
"fname": "Expand rectangles vertically.md",
"mtime": 1658686599427
},
{
"fname": "Expand rectangles vertically.svg",
"mtime": 1645967510000
},
{
"fname": "Fixed horizontal distance between centers.md",
"mtime": 1646743234000
},
{
"fname": "Fixed horizontal distance between centers.svg",
"mtime": 1645960639000
},
{
"fname": "Fixed inner distance.md",
"mtime": 1646743234000
},
{
"fname": "Fixed inner distance.svg",
"mtime": 1645960639000
},
{
"fname": "Fixed spacing.md",
"mtime": 1646743234000
},
{
"fname": "Fixed spacing.svg",
"mtime": 1645967510000
},
{
"fname": "Fixed vertical distance between centers.md",
"mtime": 1646743234000
},
{
"fname": "Fixed vertical distance between centers.svg",
"mtime": 1645967510000
},
{
"fname": "Fixed vertical distance.md",
"mtime": 1646743234000
},
{
"fname": "Fixed vertical distance.svg",
"mtime": 1645967510000
},
{
"fname": "Lighten background color.md",
"mtime": 1663059051059
},
{
"fname": "Lighten background color.svg",
"mtime": 1645959546000
},
{
"fname": "Modify background color opacity.md",
"mtime": 1644924415000
},
{
"fname": "Modify background color opacity.svg",
"mtime": 1645944722000
},
{
"fname": "Normalize Selected Arrows.md",
"mtime": 1670403743278
},
{
"fname": "Normalize Selected Arrows.svg",
"mtime": 1645960639000
},
{
"fname": "Organic Line.md",
"mtime": 1672920172531
},
{
"fname": "Organic Line.svg",
"mtime": 1645964261000
},
{
"fname": "Organic Line Legacy.md",
"mtime": 1690607372668
},
{
"fname": "Organic Line Legacy.svg",
"mtime": 1690607372668
},
{
"fname": "README.md",
"mtime": 1645175700000
},
{
"fname": "Repeat Elements.md",
"mtime": 1663059051059
},
{
"fname": "Repeat Elements.svg",
"mtime": 1645960639000
},
{
"fname": "Reverse arrows.md",
"mtime": 1645305706000
},
{
"fname": "Reverse arrows.svg",
"mtime": 1645960639000
},
{
"fname": "Scribble Helper.md",
"mtime": 1767536720161
},
{
"fname": "Scribble Helper.svg",
"mtime": 1645944722000
},
{
"fname": "Select Elements of Type.md",
"mtime": 1643464321000
},
{
"fname": "Select Elements of Type.svg",
"mtime": 1645960639000
},
{
"fname": "Set Dimensions.md",
"mtime": 1645305706000
},
{
"fname": "Set Dimensions.svg",
"mtime": 1645944722000
},
{
"fname": "Set Font Family.md",
"mtime": 1645305706000
},
{
"fname": "Set Font Family.svg",
"mtime": 1645944722000
},
{
"fname": "Set Grid.md",
"mtime": 1693725826368
},
{
"fname": "Set Grid.svg",
"mtime": 1645960639000
},
{
"fname": "Set Link Alias.md",
"mtime": 1645305706000
},
{
"fname": "Set Link Alias.svg",
"mtime": 1645960639000
},
{
"fname": "Set Stroke Width of Selected Elements.md",
"mtime": 1748189277103
},
{
"fname": "Set Stroke Width of Selected Elements.svg",
"mtime": 1645960639000
},
{
"fname": "Set Text Alignment.md",
"mtime": 1645305706000
},
{
"fname": "Set Text Alignment.svg",
"mtime": 1645960639000
},
{
"fname": "Set background color of unclosed line object by adding a shadow clone.md",
"mtime": 1681665030892
},
{
"fname": "Set background color of unclosed line object by adding a shadow clone.svg",
"mtime": 1645960639000
},
{
"fname": "Split text by lines.md",
"mtime": 1773076990493
},
{
"fname": "Split text by lines.svg",
"mtime": 1645944722000
},
{
"fname": "Zoom to Fit Selected Elements.md",
"mtime": 1640770602000
},
{
"fname": "Zoom to Fit Selected Elements.svg",
"mtime": 1645960639000
},
{
"fname": "directory-info.json",
"mtime": 1646583437000
},
{
"fname": "index-new.md",
"mtime": 1645986149000
},
{
"fname": "index.md",
"mtime": 1645175700000
},
{
"fname": "Grid Selected Images.md",
"mtime": 1701630797839
},
{
"fname": "Grid Selected Images.svg",
"mtime": 1649614401982
},
{
"fname": "Palette loader.md",
"mtime": 1686511890942
},
{
"fname": "Palette loader.svg",
"mtime": 1649614401982
},
{
"fname": "Rename Image.md",
"mtime": 1663678478785
},
{
"fname": "Rename Image.svg",
"mtime": 1663678478785
},
{
"fname": "Text to Path.md",
"mtime": 1775680971589
},
{
"fname": "Text to Path.svg",
"mtime": 1748193397572
},
{
"fname": "Deconstruct selected elements into new drawing.md",
"mtime": 1771009405621
},
{
"fname": "Deconstruct selected elements into new drawing.svg",
"mtime": 1668541145255
},
{
"fname": "Slideshow.md",
"mtime": 1764868375422
},
{
"fname": "Slideshow.svg",
"mtime": 1670017348333
},
{
"fname": "Auto Layout.md",
"mtime": 1670403743278
},
{
"fname": "Auto Layout.svg",
"mtime": 1670175947081
},
{
"fname": "Uniform size.md",
"mtime": 1670175947081
},
{
"fname": "Uniform size.svg",
"mtime": 1670175947081
},
{
"fname": "Mindmap format.md",
"mtime": 1684484694228
},
{
"fname": "Mindmap format.svg",
"mtime": 1674944958059
},
{
"fname": "Text to Sticky Notes.md",
"mtime": 1678537561724
},
{
"fname": "Text to Sticky Notes.svg",
"mtime": 1678537561724
},
{
"fname": "Folder Note Core - Make Current Drawing a Folder.md",
"mtime": 1678973697470
},
{
"fname": "Folder Note Core - Make Current Drawing a Folder.svg",
"mtime": 1678973697470
},
{
"fname": "Invert colors.md",
"mtime": 1761230648413
},
{
"fname": "Invert colors.svg",
"mtime": 1678973697470
},
{
"fname": "PDF Page Text to Clipboard.md",
"mtime": 1683984041712
},
{
"fname": "PDF Page Text to Clipboard.svg",
"mtime": 1680418321236
},
{
"fname": "Excalidraw Collaboration Frame.md",
"mtime": 1767536720161
},
{
"fname": "Excalidraw Collaboration Frame.svg",
"mtime": 1687881495985
},
{
"fname": "Create DrawIO file.md",
"mtime": 1688243858267
},
{
"fname": "Create DrawIO file.svg",
"mtime": 1688243858267
},
{
"fname": "Ellipse Selected Elements.md",
"mtime": 1690131476331
},
{
"fname": "Ellipse Selected Elements.svg",
"mtime": 1690131476331
},
{
"fname": "Select Similar Elements.md",
"mtime": 1736077716908
},
{
"fname": "Select Similar Elements.svg",
"mtime": 1691270949338
},
{
"fname": "Toggle Grid.md",
"mtime": 1692125382945
},
{
"fname": "Toggle Grid.svg",
"mtime": 1692124753386
},
{
"fname": "Split Ellipse.md",
"mtime": 1747585400113
},
{
"fname": "Split Ellipse.svg",
"mtime": 1693134104356
},
{
"fname": "Text Aura.md",
"mtime": 1693731979540
},
{
"fname": "Text Aura.svg",
"mtime": 1693731979540
},
{
"fname": "Boolean Operations.md",
"mtime": 1748278607255
},
{
"fname": "Boolean Operations.svg",
"mtime": 1695746839537
},
{
"fname": "Concatenate lines.md",
"mtime": 1736073478644
},
{
"fname": "Concatenate lines.svg",
"mtime": 1696175301525
},
{
"fname": "GPT-Draw-a-UI.md",
"mtime": 1703324727900
},
{
"fname": "GPT-Draw-a-UI.svg",
"mtime": 1700511998048
},
{
"fname": "ExcaliAI.md",
"mtime": 1779295681335
},
{
"fname": "ExcaliAI.svg",
"mtime": 1701011028767
},
{
"fname": "Repeat Texts.md",
"mtime": 1701969627758
},
{
"fname": "Repeat Texts.svg",
"mtime": 1701969627758
},
{
"fname": "Relative Font Size Cycle.md",
"mtime": 1701969627758
},
{
"fname": "Relative Font Size Cycle.svg",
"mtime": 1701969627758
},
{
"fname": "Golden Ratio.md",
"mtime": 1725174200469
},
{
"fname": "Golden Ratio.svg",
"mtime": 1702812404286
},
{
"fname": "Crop Vintage Mask.md",
"mtime": 1706565166174
},
{
"fname": "Crop Vintage Mask.svg",
"mtime": 1705836797730
},
{
"fname": "Custom Zoom.md",
"mtime": 1710424027192
},
{
"fname": "Custom Zoom.svg",
"mtime": 1710424027192
},
{
"fname": "Excalidraw Writing Machine.md",
"mtime": 1769960863134
},
{
"fname": "Excalidraw Writing Machine.svg",
"mtime": 1724356709706
},
{
"fname": "Reset LaTeX Size.md",
"mtime": 1725296010813
},
{
"fname": "Reset LaTeX Size.svg",
"mtime": 1725296010813
},
{
"fname": "Shade Master.md",
"mtime": 1779643017184
},
{
"fname": "Shade Master.svg",
"mtime": 1735252821829
},
{
"fname": "Image Occlusion.md",
"mtime": 1779555635845
},
{
"fname": "Image Occlusion.svg",
"mtime": 1735465948353
},
{
"fname": "Full-Year Calendar Generator.md",
"mtime": 1735465948353
},
{
"fname": "Full-Year Calendar Generator.svg",
"mtime": 1735465948353
},
{
"fname": "Printable Layout Wizard.md",
"mtime": 1755349206019
},
{
"fname": "Printable Layout Wizard.svg",
"mtime": 1753293096307
},
{
"fname": "Palm Guard.md",
"mtime": 1773670411373
},
{
"fname": "Palm Guard.svg",
"mtime": 1754718656757
},
{
"fname": "Mindmap Builder.md",
"mtime": 1781460603530
},
{
"fname": "Mindmap Builder.svg",
"mtime": 1766352440627
},
{
"fname": "Linear Calendar Generator.md",
"mtime": 1766386098306
},
{
"fname": "Linear Calendar Generator.svg",
"mtime": 1766386098306
},
{
"fname": "Capture Note.md",
"mtime": 1780986335837
},
{
"fname": "Capture Note.svg",
"mtime": 1780256122182
},
{
"fname": "Color Scheme Manager.md",
"mtime": 1781294249453
},
{
"fname": "Color Scheme Manager.svg",
"mtime": 1780595297314
},
{
"fname": "Comicbook Callout Editor.md",
"mtime": 1782492853631
},
{
"fname": "Comicbook Callout Editor.svg",
"mtime": 1781961241320
}
]
+9
View File
@@ -74,6 +74,7 @@ These are the scripts I use most often. I tried to order them by importance, but
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Crop%20Vintage%20Mask.svg"/></div>|[[#Crop Vintage Mask]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Mindmap%20Builder.svg"/></div>|[[#Mindmap Builder]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Capture%20Note.svg"/></div>|[[#Capture Note]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Comicbook%20Callout%20Editor.svg"/></div>|[[#Comicbook Callout Editor]]|
## Layout and Organization
**Keywords**: Design, Placement, Arrangement, Structure, Formatting, Alignment
@@ -118,6 +119,7 @@ These are the scripts I use most often. I tried to order them by importance, but
| | |
|----|-----|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Comicbook%20Callout%20Editor.svg"/></div>|[[#Comicbook Callout Editor]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Convert%20selected%20text%20elements%20to%20sticky%20notes.svg"/></div>|[[#Convert selected text elements to sticky notes]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Relative%20Font%20Size%20Cycle.svg"/></div>|[[#Relative Font Size Cycle]]|
|<div><img src="https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Scribble%20Helper.svg"/></div>|[[#Scribble Helper]]|
@@ -284,6 +286,13 @@ https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea
```
<table><tr valign='top'><td class="label">Author</td><td class="data"><a href='https://github.com/iwanhoogendoorn'>@iwanhoogendoorn</a></td></tr><tr valign='top'><td class="label">Source</td><td class="data"><a href='https://github.com/zsviczian/obsidian-excalidraw-plugin/blob/master/ea-scripts/Color%20Scheme%20Manager.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data">Swap the entire Stroke and Background/Fill colour palettes between named, categorized themes (Cloud Providers, Code Editors, Tech Brands, Design Systems, Nature, and more) from a docked side panel. Applying a theme recolours your selection (or sets the active colour) and repaints the native picker — both the quick-pick rows and the extended 3×5 grid with shades. Create your own schemes, import from a flat hex list, a labelled STROKE/FILL text format, or a raw appState colorPalette JSON (paste or .txt/.json file), hand-pick a custom picker, and export the current palette. When the MindMap Builder script is installed, an optional toggle recolours mind maps branch-by-branch. The canvas background is always left white.<br><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/color-scheme-manager.gif' style="width:560px;"></td></tr></table>
## Comicbook Callout Editor
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Comicbook%20Callout%20Editor.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/Comicbook%20Callout%20Editor.md'>File on GitHub</a></td></tr><tr valign='top'><td class="label">Description</td><td class="data"><img src='https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/images/scripts-comicbook-callout-editor.jpg'></td></tr></table>
## Concatenate lines
```excalidraw-script-install
https://raw.githubusercontent.com/zsviczian/obsidian-excalidraw-plugin/master/ea-scripts/Concatenate%20lines.md
-122
View File
@@ -1,122 +0,0 @@
const { FlatCompat } = require("@eslint/eslintrc");
const compat = new FlatCompat({
baseDirectory: __dirname,
});
const legacyConfig = require("./.eslintrc.json");
module.exports = (async () => {
const { default: obsidianmd } = await import("eslint-plugin-obsidianmd");
const tsRulesOffForJs = Object.fromEntries(
[
"@typescript-eslint/await-thenable",
"@typescript-eslint/ban-ts-comment",
"@typescript-eslint/no-array-constructor",
"@typescript-eslint/no-array-delete",
"@typescript-eslint/no-base-to-string",
"@typescript-eslint/no-deprecated",
"@typescript-eslint/no-duplicate-enum-values",
"@typescript-eslint/no-duplicate-type-constituents",
"@typescript-eslint/no-empty-object-type",
"@typescript-eslint/no-explicit-any",
"@typescript-eslint/no-extra-non-null-assertion",
"@typescript-eslint/no-floating-promises",
"@typescript-eslint/no-for-in-array",
"@typescript-eslint/no-implied-eval",
"@typescript-eslint/no-misused-new",
"@typescript-eslint/no-misused-promises",
"@typescript-eslint/no-namespace",
"@typescript-eslint/no-non-null-asserted-optional-chain",
"@typescript-eslint/no-redundant-type-constituents",
"@typescript-eslint/no-require-imports",
"@typescript-eslint/no-this-alias",
"@typescript-eslint/no-unnecessary-type-assertion",
"@typescript-eslint/no-unnecessary-type-constraint",
"@typescript-eslint/no-unsafe-argument",
"@typescript-eslint/no-unsafe-assignment",
"@typescript-eslint/no-unsafe-call",
"@typescript-eslint/no-unsafe-declaration-merging",
"@typescript-eslint/no-unsafe-enum-comparison",
"@typescript-eslint/no-unsafe-function-type",
"@typescript-eslint/no-unsafe-member-access",
"@typescript-eslint/no-unsafe-return",
"@typescript-eslint/no-unsafe-unary-minus",
"@typescript-eslint/no-unused-expressions",
"@typescript-eslint/no-unused-vars",
"@typescript-eslint/no-wrapper-object-types",
"@typescript-eslint/only-throw-error",
"@typescript-eslint/prefer-as-const",
"@typescript-eslint/prefer-namespace-keyword",
"@typescript-eslint/prefer-promise-reject-errors",
"@typescript-eslint/require-await",
"@typescript-eslint/restrict-plus-operands",
"@typescript-eslint/restrict-template-expressions",
"@typescript-eslint/triple-slash-reference",
"@typescript-eslint/unbound-method",
].map((rule) => [rule, "off"]),
);
const obsidianTypedRulesOffForJs = {
"obsidianmd/no-plugin-as-component": "off",
"obsidianmd/no-view-references-in-plugin": "off",
"obsidianmd/no-unsupported-api": "off",
"obsidianmd/prefer-file-manager-trash-file": "off",
"obsidianmd/prefer-instanceof": "off",
};
return [
{
ignores: [
"lib/**",
"dist/**",
"node_modules/**",
".github/**",
"MathjaxToSVG/**",
"docs/**",
"ea-scripts/**",
"images/**",
"test-data/**",
],
},
...compat.config(legacyConfig),
...obsidianmd.configs.recommended,
{
files: ["**/*.{js,jsx}"],
rules: {
...tsRulesOffForJs,
...obsidianTypedRulesOffForJs,
},
},
{
files: ["**/*.{ts,tsx}"],
languageOptions: {
parser: require("@typescript-eslint/parser"),
parserOptions: {
project: "./tsconfig.json",
tsconfigRootDir: __dirname,
},
},
rules: {
"obsidianmd/prefer-instanceof": "off",
},
},
{
files: ["**/*.{ts,tsx,js,jsx}"],
rules: {
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{
args: "after-used",
argsIgnorePattern: "^_",
varsIgnorePattern: "^_",
ignoreRestSiblings: true,
caughtErrors: "all",
caughtErrorsIgnorePattern: "^_",
},
],
"no-useless-escape": "error",
},
},
];
})();
+43
View File
@@ -0,0 +1,43 @@
import tseslint from 'typescript-eslint';
import obsidianmd from 'eslint-plugin-obsidianmd';
import globals from 'globals';
import { globalIgnores } from 'eslint/config';
export default tseslint.config(
globalIgnores([
'node_modules',
'dist',
'esbuild.config.mjs',
'rollup.config.mjs',
'version-bump.mjs',
'versions.json',
'main.js',
'package.json',
'package-lock.json',
'tsconfig.json',
'tsconfig.api.json',
'api',
"scripts",
"ea-scripts",
"docs",
"lib",
"images",
"assets",
]),
{
languageOptions: {
globals: {
...globals.browser,
},
parserOptions: {
projectService: {
allowDefaultProject: ['eslint.config.mts', 'manifest.json'],
},
tsconfigRootDir: import.meta.dirname,
extraFileExtensions: ['.json'],
},
},
},
...obsidianmd.configs.recommended,
);
Binary file not shown.

After

Width:  |  Height:  |  Size: 564 KiB

+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.23.12",
"version": "2.25.0-beta.0",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.23.12",
"version": "2.24.2",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+54 -26
View File
@@ -9,19 +9,21 @@
"version": "2.2.5",
"license": "MIT",
"dependencies": {
"@lezer/lr": "^1.4.10",
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.101-beta.1",
"@zsviczian/excalidraw": "0.18.108",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
"gl-matrix": "^3.4.3",
"lz-string": "^1.5.0",
"mathjax-full": "^3.2.2",
"monkey-around": "^2.3.0",
"nanoid": "^5.1.11",
"opentype.js": "^1.3.4",
"pako": "^2.1.0",
"points-on-path": "^0.2.1",
"polybooljs": "^1.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
@@ -38,8 +40,6 @@
"@codemirror/search": "6.5.11",
"@codemirror/state": "6.5.0",
"@codemirror/view": "6.38.6",
"@eslint/eslintrc": "^3.1.0",
"@excalidraw/eslint-config": "^1.0.3",
"@excalidraw/prettier-config": "^1.0.2",
"@rollup/plugin-babel": "^6.0.3",
"@rollup/plugin-commonjs": "^26.0.1",
@@ -58,10 +58,11 @@
"@zsviczian/rollup-plugin-postprocess": "^1.0.3",
"cross-env": "^7.0.3",
"cssnano": "^6.0.2",
"eslint": "^9.27.0",
"eslint": "^9.39.4",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-obsidianmd": "^0.3.0",
"eslint-plugin-prettier": "^5.0.0",
"jiti": "^2.6.1",
"jsesc": "^3.0.2",
"obsidian": "1.8.7",
"postcss": "^8.4.31",
@@ -1986,21 +1987,6 @@
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
}
},
"node_modules/@excalidraw/eslint-config": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@excalidraw/eslint-config/-/eslint-config-1.0.3.tgz",
"integrity": "sha512-GemHNF5Z6ga0BWBSX7GJaNBUchLu6RwTcAB84eX1MeckRNhNasAsPCdelDlFalz27iS4RuYEQh0bPE8SRxJgbQ==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"@typescript-eslint/eslint-plugin": ">=4",
"@typescript-eslint/parser": ">=4",
"eslint": ">=7",
"eslint-config-prettier": ">=7",
"eslint-plugin-prettier": ">=3",
"prettier": ">=2"
}
},
"node_modules/@excalidraw/laser-pointer": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/@excalidraw/laser-pointer/-/laser-pointer-1.3.1.tgz",
@@ -2406,9 +2392,9 @@
}
},
"node_modules/@radix-ui/number": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",
"integrity": "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==",
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.2.tgz",
"integrity": "sha512-ceTwaxc4I5IOi97DgCotl3pqiyRGvffcc0oOsE2dQYaJOFIDsDt4VWG6xEbg1QePv9QWausCEIppud/tJ1wNig==",
"license": "MIT"
},
"node_modules/@radix-ui/primitive": {
@@ -3105,6 +3091,12 @@
}
}
},
"node_modules/@radix-ui/react-one-time-password-field/node_modules/@radix-ui/number": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",
"integrity": "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==",
"license": "MIT"
},
"node_modules/@radix-ui/react-password-toggle-field": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-password-toggle-field/-/react-password-toggle-field-0.1.3.tgz",
@@ -3393,6 +3385,12 @@
}
}
},
"node_modules/@radix-ui/react-scroll-area/node_modules/@radix-ui/number": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",
"integrity": "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==",
"license": "MIT"
},
"node_modules/@radix-ui/react-select": {
"version": "2.2.6",
"resolved": "https://registry.npmjs.org/@radix-ui/react-select/-/react-select-2.2.6.tgz",
@@ -3436,6 +3434,12 @@
}
}
},
"node_modules/@radix-ui/react-select/node_modules/@radix-ui/number": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",
"integrity": "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==",
"license": "MIT"
},
"node_modules/@radix-ui/react-separator": {
"version": "1.1.7",
"resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.1.7.tgz",
@@ -3492,6 +3496,12 @@
}
}
},
"node_modules/@radix-ui/react-slider/node_modules/@radix-ui/number": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/@radix-ui/number/-/number-1.1.1.tgz",
"integrity": "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==",
"license": "MIT"
},
"node_modules/@radix-ui/react-slot": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.3.tgz",
@@ -5209,6 +5219,7 @@
"version": "0.9.10",
"resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.9.10.tgz",
"integrity": "sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14.6"
@@ -5221,9 +5232,9 @@
"license": "MIT"
},
"node_modules/@zsviczian/excalidraw": {
"version": "0.18.101-beta.1",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.101-beta.1.tgz",
"integrity": "sha512-cHX23OtCWiNqtgBBM0wKrpXhSy7RVwCI3eClRsItl96wJ2aDUpWxB3BBexGZl+8LTSSfol8JOuHNyGcE95Uy9w==",
"version": "0.18.108",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.108.tgz",
"integrity": "sha512-vSBbcC4m3PcEb9sfgCdqRDYHU8gkR4S34VEAsfQi4M6aMvoMHw95IJMP8DtSIvETakesQ24XEQXnnRDUjx+44g==",
"license": "MIT",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
@@ -8229,6 +8240,7 @@
"version": "3.2.25",
"resolved": "https://registry.npmjs.org/esm/-/esm-3.2.25.tgz",
"integrity": "sha512-U1suiZ2oDVWv4zPO56S0NcR5QriEahGtdN2OR6FiOG4WJvcjBVFB0qI4+eKoWFH483PKGuLuu6V8Z4T5g63UVA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -9658,6 +9670,16 @@
"@pkgjs/parseargs": "^0.11.0"
}
},
"node_modules/jiti": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz",
"integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==",
"dev": true,
"license": "MIT",
"bin": {
"jiti": "lib/jiti-cli.mjs"
}
},
"node_modules/jotai": {
"version": "2.11.0",
"resolved": "https://registry.npmjs.org/jotai/-/jotai-2.11.0.tgz",
@@ -10094,6 +10116,7 @@
"resolved": "https://registry.npmjs.org/mathjax-full/-/mathjax-full-3.2.2.tgz",
"integrity": "sha512-+LfG9Fik+OuI8SLwsiR02IVdjcnRCy5MufYLi0C3TdMT56L/pjB0alMVGgoWJF8pN9Rc7FESycZB9BMNWIid5w==",
"deprecated": "Version 4 replaces this package with the scoped package @mathjax/src",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"esm": "^3.2.25",
@@ -10177,6 +10200,7 @@
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/mhchemparser/-/mhchemparser-4.2.1.tgz",
"integrity": "sha512-kYmyrCirqJf3zZ9t/0wGgRZ4/ZJw//VwaRVGA75C4nhE60vtnIzhl9J9ndkX/h6hxSN7pjg/cE0VxbnNM+bnDQ==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/micromatch": {
@@ -10243,6 +10267,7 @@
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/mj-context-menu/-/mj-context-menu-0.6.1.tgz",
"integrity": "sha512-7NO5s6n10TIV96d4g2uDpG7ZDpIhMh0QNfGdJw/W47JswFcosz457wqz/b5sAKvl12sxINGFCn80NZHKwxQEXA==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/module-replacements": {
@@ -12348,6 +12373,7 @@
"version": "4.1.4",
"resolved": "https://registry.npmjs.org/speech-rule-engine/-/speech-rule-engine-4.1.4.tgz",
"integrity": "sha512-i/VCLG1fvRc95pMHRqG4aQNscv+9aIsqA2oI7ZQS51sTdUcDHYX6cpT8/tqZ+enjs1tKVwbRBWgxut9SWn+f9g==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@xmldom/xmldom": "0.9.10",
@@ -12362,6 +12388,7 @@
"version": "13.1.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-13.1.0.tgz",
"integrity": "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
@@ -13402,6 +13429,7 @@
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/wicked-good-xpath/-/wicked-good-xpath-1.3.0.tgz",
"integrity": "sha512-Gd9+TUn5nXdwj/hFsPVx5cuHHiF5Bwuc30jZ4+ronF1qHK5O7HD0sgmXWSEgwKquT3ClLoKPVbO6qGwVwLzvAw==",
"dev": true,
"license": "MIT"
},
"node_modules/woff2sfnt-sfnt2woff": {
+12 -9
View File
@@ -16,26 +16,30 @@
"code:unused": "eslint --max-warnings=0 --ext .ts,.tsx ./src --quiet --format json | node -e \"let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{const r=JSON.parse(d);for(const f of r){for(const m of f.messages||[]){if(m.ruleId==='@typescript-eslint/no-unused-vars'||m.ruleId==='no-unused-vars'){console.log(f.filePath+':'+m.line+':'+m.column+' '+m.ruleId+' '+m.message);}}}})\"",
"code:escape": "eslint --max-warnings=0 --ext .ts,.tsx ./src --quiet --format json | node -e \"let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{const r=JSON.parse(d);for(const f of r){for(const m of f.messages||[]){if(m.ruleId==='no-useless-escape'){console.log(f.filePath+':'+m.line+':'+m.column+' '+m.ruleId+' '+m.message);}}}})\"",
"madge": "madge --circular .",
"doc": "npm run lib && node scripts/generate-script-library.js",
"mindmap": "node scripts/deploy-mindmap-builder.js"
"doc": "npm run lib && node scripts/generate-script-library.mjs",
"mindmap": "node scripts/deploy-mindmap-builder.mjs",
"lint": "eslint .",
"lint:fix": "npx prettier --write \"src/**/*.{ts,tsx}\" && eslint --max-warnings=0 --ext .ts,.tsx ./src --fix"
},
"keywords": [],
"author": "",
"license": "MIT",
"dependencies": {
"lz-string": "^1.5.0",
"@lezer/lr": "^1.4.10",
"@popperjs/core": "^2.11.8",
"@radix-ui/number": "^1.1.2",
"@zsviczian/colormaster": "^1.2.2",
"@zsviczian/excalidraw": "0.18.101-beta.1",
"@zsviczian/excalidraw": "0.18.108",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
"gl-matrix": "^3.4.3",
"mathjax-full": "^3.2.2",
"lz-string": "^1.5.0",
"monkey-around": "^2.3.0",
"nanoid": "^5.1.11",
"opentype.js": "^1.3.4",
"pako": "^2.1.0",
"points-on-path": "^0.2.1",
"polybooljs": "^1.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
@@ -52,8 +56,6 @@
"@codemirror/search": "6.5.11",
"@codemirror/state": "6.5.0",
"@codemirror/view": "6.38.6",
"@eslint/eslintrc": "^3.1.0",
"@excalidraw/eslint-config": "^1.0.3",
"@excalidraw/prettier-config": "^1.0.2",
"@rollup/plugin-babel": "^6.0.3",
"@rollup/plugin-commonjs": "^26.0.1",
@@ -72,10 +74,11 @@
"@zsviczian/rollup-plugin-postprocess": "^1.0.3",
"cross-env": "^7.0.3",
"cssnano": "^6.0.2",
"eslint": "^9.27.0",
"eslint": "^9.39.4",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-obsidianmd": "^0.3.0",
"eslint-plugin-prettier": "^5.0.0",
"jiti": "^2.6.1",
"jsesc": "^3.0.2",
"obsidian": "1.8.7",
"postcss": "^8.4.31",
@@ -101,4 +104,4 @@
"node": ">=22.0.0",
"npm": ">=10.0.0"
}
}
}
+1
View File
@@ -151,6 +151,7 @@ const packageString = isLib
' for (let i = 0; i < len; i++) bytes[i] = binStr.charCodeAt(i);\n' +
' return new TextDecoder().decode(pako.inflate(bytes));\n' +
'};\n' +
'window.unpackBase64Deflate = unpackBase64Deflate;\n' +
'const unpackExcalidraw = () => unpackBase64Deflate("' + compressDeflateBase64(excalidraw_pkg) + '");\n' +
'let {react, reactDOM } = new Function(`${REACT_PACKAGES}; return {react: React, reactDOM: ReactDOM};`)();\n' +
'let excalidrawLib = {};\n' +
-63
View File
@@ -1,63 +0,0 @@
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import { execSync } from 'node:child_process';
const mathjaxDir = path.resolve('MathjaxToSVG');
const distDir = path.join(mathjaxDir, 'dist');
const distFile = path.join(distDir, 'index.js');
const hashFile = path.join(distDir, '.build-hash');
const nodeModulesDir = path.join(mathjaxDir, 'node_modules');
// Recursively generates an MD5 hash of all source files in a directory
function hashDirectory(dir) {
const files = fs.readdirSync(dir, { withFileTypes: true });
const hash = crypto.createHash('md5');
// Sort to ensure consistent hashing across different operating systems
for (const file of files.sort((a, b) => a.name.localeCompare(b.name))) {
// Ignore build outputs, dependencies, and hidden files (like .git, .DS_Store)
if (file.name === 'node_modules' || file.name === 'dist' || file.name.startsWith('.')) {
continue;
}
const fullPath = path.join(dir, file.name);
if (file.isDirectory()) {
hash.update(hashDirectory(fullPath));
} else {
hash.update(fs.readFileSync(fullPath));
}
}
return hash.digest('hex');
}
const currentHash = hashDirectory(mathjaxDir);
let previousHash = '';
if (fs.existsSync(hashFile)) {
previousHash = fs.readFileSync(hashFile, 'utf8');
}
// Rebuild if the output file is missing, or if the source files have changed
if (!fs.existsSync(distFile) || currentHash !== previousHash) {
console.log('🔄 MathjaxToSVG changes detected (or missing build). Rebuilding...');
// Run npm install if node_modules is missing or if we know things changed
if (!fs.existsSync(nodeModulesDir) || currentHash !== previousHash) {
console.log('📦 Installing MathjaxToSVG dependencies...');
execSync('npm install', { stdio: 'inherit', cwd: mathjaxDir });
}
console.log('🔨 Building MathjaxToSVG...');
execSync('npm run build', { stdio: 'inherit', cwd: mathjaxDir });
// Save the new hash for next time
if (!fs.existsSync(distDir)) {
fs.mkdirSync(distDir, { recursive: true });
}
fs.writeFileSync(hashFile, currentHash);
console.log('✅ MathjaxToSVG build complete.\n');
} else {
console.log('⚡ MathjaxToSVG is up to date. Skipping build.\n');
}
@@ -1,7 +1,12 @@
const path = require("path");
const fs = require("fs/promises");
const { minify } = require("terser");
const LZString = require("lz-string");
import path from "path";
import fs from "fs/promises";
import { minify } from "terser";
import LZString from "lz-string";
import { fileURLToPath } from "url";
// Construct __dirname for ES Modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const CHUNK_SIZE = 256;
const NEEDLE = "const removeKeydownHandlers";
@@ -1,5 +1,5 @@
const fs = require('fs');
const { execSync } = require('child_process');
import fs from 'fs';
import { execSync } from 'child_process';
const content = fs.readFileSync('src/lang/locale/en.ts', 'utf8');
const lines = content.split('\n');
@@ -29,4 +29,4 @@ for (const key of keys) {
}
unusedKeys.sort().forEach(k => console.log(k));
console.log('Total: ' + unusedKeys.length);
console.log('Total: ' + unusedKeys.length);
@@ -1,7 +1,12 @@
/* eslint-disable no-console */
// to run: npm run doc
const fs = require('fs');
const path = require('path');
// to run: node generate-script-library.mjs
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
// Reconstruct __dirname for ES Modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT = path.resolve(__dirname, '..');
const EA_SCRIPTS_DIR = path.join(ROOT, 'ea-scripts');
@@ -617,17 +622,17 @@ function main() {
const combined =
(AI_TRAINING_INTRO +
'\n---\n\n' +
typeDefContent.trim() +
'\n\n---\n\n' +
excalidrawLibFunctionsSection +
'\n---\n\n' +
scriptLibContent.trim() +
startupSection +
'\n')
.replaceAll("https://youtu.be/", "YouTube: ")
.replaceAll("https://www.youtube.com/watch?v=", "YouTube: ")
.replaceAll("https://www.youtube.com/", "YouTube: "); // prevent accidental link triggering
'\n---\n\n' +
typeDefContent.trim() +
'\n\n---\n\n' +
excalidrawLibFunctionsSection +
'\n---\n\n' +
scriptLibContent.trim() +
startupSection +
'\n')
.replaceAll("https://youtu.be/", "YouTube: ")
.replaceAll("https://www.youtube.com/watch?v=", "YouTube: ")
.replaceAll("https://www.youtube.com/", "YouTube: "); // prevent accidental link triggering
fs.writeFileSync(AI_TRAINING_OUT, combined, 'utf8');
console.log('[script-library] Wrote:', AI_TRAINING_OUT);
@@ -638,11 +643,12 @@ function main() {
console.log('[script-library] Done.');
}
if (require.main === module) {
// ESM equivalent of `if (require.main === module)`
if (process.argv[1] === fileURLToPath(import.meta.url)) {
try {
main();
} catch (e) {
console.error('[script-library] Failed:', e);
process.exit(1);
}
}
}
+4 -1
View File
@@ -2,6 +2,7 @@ import { getIcon, sanitizeHTMLToDom } from "obsidian";
import { PenStyle } from "src/types/penTypes";
import React from "react";
import { mainDocument } from "./constants";
import { isInstanceOfSVGSVGElement } from "src/utils/typechecks";
const BLOCKED_SVG_TAGS = new Set([
"script",
@@ -68,7 +69,7 @@ const sanitizeSvgTree = (svg: SVGSVGElement) => {
const sanitizeSvgFromString = (svgMarkup: string): SVGSVGElement | null => {
const fragment = sanitizeHTMLToDom(svgMarkup ?? "");
const svg = fragment.querySelector("svg");
if (!(svg instanceof SVGSVGElement)) {
if (!isInstanceOfSVGSVGElement(svg)) {
return null;
}
const clone = svg.cloneNode(true) as SVGSVGElement;
@@ -212,6 +213,8 @@ export const ICONS = {
</text>
</svg>
),
Edit: getIconAsJSX("pen-line"),
Read: getIconAsJSX("book-open"),
Learn: getIconAsJSX("graduation-cap"),
Github: getIconAsJSX("github"),
YouTube: getIconAsJSX("youtube"),
+4 -1
View File
@@ -9,6 +9,7 @@ import { setStyle } from "src/utils/styleUtils";
//This is only for backward compatibility because an early version of obsidian included an encoding to avoid fantom links from littering Obsidian graph view
declare const PLUGIN_VERSION: string;
export let EXCALIDRAW_PLUGIN: ExcalidrawPlugin = null;
// eslint-disable-next-line obsidianmd/prefer-active-doc
export const mainDocument = document; //signals deliberate use of main document instead of activeDocument
export const setExcalidrawPlugin = (plugin: ExcalidrawPlugin) => {
EXCALIDRAW_PLUGIN = plugin;
@@ -175,7 +176,9 @@ export function updateExcalidrawLib() {
getDefaultColorPalette,
} = excalidrawLib);
} catch (error) {
errorHandler.handleError(error, "updateExcalidrawLib", true);
if (error instanceof Error || typeof error === "string") {
errorHandler.handleError(error, "updateExcalidrawLib", true);
}
// Don't throw here - we'll try to continue with potentially stale functions
// but at least we won't crash
}
+6 -1
View File
@@ -1,5 +1,6 @@
import "obsidian";
import type { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { errorlog } from "src/utils/coreUtils";
import type ExcalidrawView from "src/view/ExcalidrawView";
//import { ExcalidrawAutomate } from "./ExcalidrawAutomate";
//export ExcalidrawAutomate from "./ExcalidrawAutomate";
@@ -17,7 +18,11 @@ export const getEA = (view?: ExcalidrawView): ExcalidrawAutomate | null => {
try {
return window.ExcalidrawAutomate.getAPI(view);
} catch (error) {
console.log({ message: "Excalidraw not available", fn: getEA, error });
errorlog({
message: "Excalidraw not available",
fn: getEA,
error: error as unknown,
});
return null;
}
};
+33 -159
View File
@@ -12,7 +12,6 @@ import {
ViewStateResult,
Notice,
MetadataCache,
Workspace,
TAbstractFile,
FrontMatterCache,
} from "obsidian";
@@ -36,7 +35,6 @@ import {
DEVICE,
FONTS_STYLE_ID,
CJK_STYLE_ID,
loadMermaid,
setRootElementSize,
mainDocument,
} from "../constants/constants";
@@ -50,11 +48,7 @@ import {
KNOWN_AI_IMAGE_MODEL_CONFIGS,
} from "./settings";
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
import {
initExcalidrawAutomate,
insertLaTeXToView,
} from "src/utils/excalidrawAutomateUtils";
import { around, dedupe } from "monkey-around";
import { initExcalidrawAutomate } from "src/utils/excalidrawAutomateUtils";
import { t } from "../lang/helpers";
import {
createOrOverwriteFile,
@@ -65,9 +59,7 @@ import {
import {
getFontDataURL,
errorlog,
sleep,
isVersionNewerThanOther,
isCallerFromTemplaterPlugin,
versionUpdateCheckTimer,
getFontMetrics,
calculateUIModeValue,
@@ -110,10 +102,10 @@ import {
ExcalidrawLoading,
switchToExcalidraw,
} from "../view/ExcalidrawLoading";
import { clearMathJaxVariables } from "../shared/LaTeX";
import { PluginFileManager } from "./managers/FileManager";
import { ObserverManager } from "./managers/ObserverManager";
import { PackageManager } from "./managers/PackageManager";
import { MonkeyPatchManager } from "./managers/MonkeyPatchManager";
import ExcalidrawView from "../view/ExcalidrawView";
import { ExcalidrawSidepanelView } from "../view/sidepanel/Sidepanel";
import { CommandManager } from "./managers/CommandManager";
@@ -128,9 +120,10 @@ import {
decryptPersistedAPIKeys,
encryptPersistedAPIKeys,
} from "src/utils/settingsKeyObfuscation";
import { URLs } from "src/constants/safeUrls";
import { hideElement, setButtonBgColor } from "src/utils/styleUtils";
import { installButton } from "src/utils/scriptLibraryUtils";
import { isInstanceOfHTMLStyleElement } from "src/utils/typechecks";
import { insertLaTeXToView } from "src/utils/excalidrawViewHelpers";
declare const PLUGIN_VERSION: string;
declare const INITIAL_TIMESTAMP: number;
@@ -587,6 +580,7 @@ export default class ExcalidrawPlugin extends Plugin {
private fileManager: PluginFileManager;
private observerManager: ObserverManager;
private packageManager: PackageManager;
private monkeyPatchManager: MonkeyPatchManager;
private commandManager: CommandManager;
private eventManager: EventManager;
public eaInstances = new WeakArray<ExcalidrawAutomate>();
@@ -620,6 +614,7 @@ export default class ExcalidrawPlugin extends Plugin {
public loadTimestamp: number;
private isLocalCJKFontAvailabe: boolean = undefined;
public isReady = false;
private fontsReady = true; //setting this to true allows for a race condition during startup loading fonts and rendering Excalidraw
private startupAnalytics: string[] = [];
private lastLogTimestamp: number;
private settingsReady: boolean = false;
@@ -664,7 +659,7 @@ export default class ExcalidrawPlugin extends Plugin {
}
public printStarupBreakdown() {
console.log(
log(
`Excalidraw ${PLUGIN_VERSION} startup breakdown:\n${this.startupAnalytics.join(
"\n",
)}`,
@@ -805,15 +800,13 @@ export default class ExcalidrawPlugin extends Plugin {
addIcon(ICON_NAME, EXCALIDRAW_ICON);
addIcon(SCRIPTENGINE_ICON_NAME, SCRIPTENGINE_ICON);
addIcon(EXPORT_IMG_ICON_NAME, EXPORT_IMG_ICON);
this.addRibbonIcon(
ICON_NAME,
t("CREATE_NEW"),
this.actionRibbonClick.bind(this),
this.addRibbonIcon(ICON_NAME, t("CREATE_NEW"), (e) =>
this.actionRibbonClick(e),
);
try {
void this.loadSettings({ reEnableAutosave: true }).then(
this.onloadCheckForOnceOffSettingsUpdates.bind(this),
void this.loadSettings({ reEnableAutosave: true }).then(() =>
this.onloadCheckForOnceOffSettingsUpdates(),
);
} catch (e) {
new Notice("Error loading plugin settings", 6000);
@@ -825,7 +818,7 @@ export default class ExcalidrawPlugin extends Plugin {
// need it her for ExcaliBrain
this.ea = initExcalidrawAutomate(this);
} catch (e) {
new Notice("Error initializing Excalidraw Automate", 6000);
new Notice(t("ERROR_INITIALIZING_EA"), 6000);
console.error("Error initializing Excalidraw Automate", e);
}
this.logStartupEvent("Excalidraw Automate initialized");
@@ -834,12 +827,12 @@ export default class ExcalidrawPlugin extends Plugin {
//Licat: Are you registering your post processors in onLayoutReady? You should register them in onload instead
this.addMarkdownPostProcessor();
} catch (e) {
new Notice("Error adding markdown post processor", 6000);
console.error("Error adding markdown post processor", e);
new Notice("Error adding Markdown post processor", 6000);
console.error("Error adding Markdown post processor", e);
}
this.logStartupEvent("Markdown post processor added");
this.app.workspace.onLayoutReady(this.onloadOnLayoutReady.bind(this));
this.app.workspace.onLayoutReady(() => this.onloadOnLayoutReady());
this.logStartupEvent("Workspace ready event handler added");
}
@@ -880,6 +873,7 @@ export default class ExcalidrawPlugin extends Plugin {
this.packageManager = new PackageManager(this);
this.eventManager = new EventManager(this);
this.observerManager = new ObserverManager(this);
this.monkeyPatchManager = new MonkeyPatchManager(this);
this.commandManager = new CommandManager(this);
try {
@@ -903,7 +897,7 @@ export default class ExcalidrawPlugin extends Plugin {
try {
//inspiration taken from kanban:
//https://github.com/mgmeyers/obsidian-kanban/blob/44118e25661bff9ebfe54f71ae33805dc88ffa53/src/main.ts#L267
this.registerMonkeyPatches();
this.monkeyPatchManager.initialize();
} catch (e) {
new Notice("Error registering monkey patches", 6000);
console.error("Error registering monkey patches", e);
@@ -928,13 +922,7 @@ export default class ExcalidrawPlugin extends Plugin {
}
this.logStartupEvent("Script engine initialized");
try {
await this.initializeFonts();
} catch (e) {
new Notice("Error initializing fonts", 6000);
console.error("Error initializing fonts", e);
}
this.logStartupEvent("Fonts initialized");
void this.initializeFonts();
try {
void getImageCache().initializeDB(this);
@@ -1041,9 +1029,8 @@ export default class ExcalidrawPlugin extends Plugin {
public async awaitInit() {
let counter = 0;
while (!this.isReady && counter < 150) {
while ((!this.isReady || !this.fontsReady) && counter++ < 200) {
await sleep(50);
counter++;
}
}
@@ -1141,6 +1128,7 @@ export default class ExcalidrawPlugin extends Plugin {
this.fourthFontLoaded = true;
}, 100);
}
this.fontsReady = true;
}
public async addFonts(
@@ -1192,8 +1180,7 @@ export default class ExcalidrawPlugin extends Plugin {
}
return;
}
if (existingStylesheet instanceof HTMLStyleElement) {
if (isInstanceOfHTMLStyleElement(existingStylesheet)) {
existingStylesheet.textContent = PHONE_FOOTER_SAFE_AREA_CSS;
return;
}
@@ -1294,7 +1281,7 @@ export default class ExcalidrawPlugin extends Plugin {
errorlog({
where: "this.registerInstallCodeblockProcessor",
source,
error: e,
error: e as unknown,
});
}
@@ -1389,7 +1376,7 @@ export default class ExcalidrawPlugin extends Plugin {
});
}
if (!keepOriginal) {
void this.app.vault.delete(file);
void this.app.fileManager.trashFile(file);
}
return result;
}
@@ -1411,124 +1398,6 @@ export default class ExcalidrawPlugin extends Plugin {
new Notice(`Converted ${files.length} files.`);
}
private registerMonkeyPatches() {
const key = URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES;
this.register(
around(Workspace.prototype, {
getActiveViewOfType(old) {
return dedupe(key, old, function (...args) {
const result = old && old.apply(this, args);
const maybeEAView = self.app?.workspace?.activeLeaf?.view;
if (!maybeEAView || !(maybeEAView instanceof ExcalidrawView)) {
return result;
}
const error = new Error();
const stackTrace = error.stack;
if (!isCallerFromTemplaterPlugin(stackTrace)) {
return result;
}
const leafOrNode = maybeEAView.getActiveEmbeddable();
if (leafOrNode) {
if (leafOrNode.node && leafOrNode.node.isEditing) {
return {
file: leafOrNode.node.file,
editor: leafOrNode.node.child.editor,
};
}
}
return result;
});
},
}),
);
if (!this.app.plugins.plugins?.["obsidian-hover-editor"]) {
this.register(
//stolen from hover editor
around(WorkspaceLeaf.prototype, {
getRoot(old) {
return function () {
const top = old.call(this);
return top.getRoot === this.getRoot ? top : top.getRoot();
};
},
}),
);
}
const self = this;
// Monkey patch WorkspaceLeaf to open Excalidraw drawings with ExcalidrawView by default
this.register(
around(WorkspaceLeaf.prototype, {
// Drawings can be viewed as markdown or Excalidraw, and we keep track of the mode
// while the file is open. When the file closes, we no longer need to keep track of it.
detach(next) {
return function () {
const state = this.view?.getState();
if (
state?.file &&
self.excalidrawFileModes[this.id || state.file]
) {
delete self.excalidrawFileModes[this.id || state.file];
}
return next.apply(this);
};
},
setViewState(next) {
return function (state: ViewState, ...rest: [ViewStateResult?]) {
const markdownViewLoaded =
self._loaded && // Don't force excalidraw mode during shutdown
state.type === "markdown" && // If we have a markdown file
state.state?.file;
if (
markdownViewLoaded &&
self.excalidrawFileModes[this.id || state.state.file] !==
"markdown"
) {
const filepath: string = state.state.file as string;
if (
self.forceToOpenInMarkdownFilepath !== filepath &&
fileShouldDefaultAsExcalidraw(filepath, this.app)
) {
// If we have it, force the view type to excalidraw
const newState = {
...state,
type: VIEW_TYPE_EXCALIDRAW,
};
self.excalidrawFileModes[filepath] = VIEW_TYPE_EXCALIDRAW;
return next.apply(this, [newState, ...rest]);
}
self.forceToOpenInMarkdownFilepath = null;
}
if (markdownViewLoaded) {
const leaf = this;
window.setTimeout(() => {
if (
!leaf ||
!leaf.view ||
!(leaf.view instanceof MarkdownView) ||
!leaf.view.file ||
!self.isExcalidrawFile(leaf.view.file)
) {
return;
}
foldExcalidrawSection(leaf.view);
}, 500);
}
return next.apply(this, [state, ...rest]);
};
},
}),
);
}
/**
* Loads the startup script that will add event hooks to ExcalidrawAutomate (if provided by the user)
* Because of file operations, this must be run after the Obsidian Layout is ready
@@ -1793,6 +1662,10 @@ export default class ExcalidrawPlugin extends Plugin {
await this.saveData(encryptPersistedAPIKeys(persistedSettings));
}
async onExternalSettingsChange() {
await this.loadSettings();
}
public async openSidepanel(
reveal: boolean = true,
): Promise<ExcalidrawSidepanelView | null> {
@@ -1832,8 +1705,10 @@ export default class ExcalidrawPlugin extends Plugin {
return;
}
visitedDocs.add(ownerDocument);
const e = ownerDocument.createEvent("Event");
e.initEvent(RERENDER_EVENT, true, false);
const e = new CustomEvent(RERENDER_EVENT, {
bubbles: true,
cancelable: false,
});
ownerDocument
.querySelectorAll(
`.excalidraw-embedded-img${
@@ -1882,7 +1757,6 @@ export default class ExcalidrawPlugin extends Plugin {
await this.saveSettings();
new RankMessage(
this.app,
this,
filecount,
rank,
decoration,
@@ -1971,11 +1845,11 @@ export default class ExcalidrawPlugin extends Plugin {
await this.fileManager.renameEventHandler(file, oldPath);
}
public async modifyEventHandler(file: TFile) {
public async modifyEventHandler(file: TAbstractFile) {
await this.fileManager.modifyEventHandler(file);
}
public async deleteEventHandler(file: TFile) {
public async deleteEventHandler(file: TAbstractFile) {
await this.fileManager.deleteEventHandler(file);
}
+32 -43
View File
@@ -34,7 +34,7 @@ import { InsertImageDialog } from "../../shared/Dialogs/InsertImageDialog";
import { ImportSVGDialog } from "../../shared/Dialogs/ImportSVGDialog";
import { InsertMDDialog } from "../../shared/Dialogs/InsertMDDialog";
import { ExcalidrawAutomate } from "../../shared/ExcalidrawAutomate";
import { insertLaTeXToView, search } from "src/utils/excalidrawAutomateUtils";
import { search } from "src/utils/excalidrawAutomateUtils";
import { templatePromt } from "../../shared/Dialogs/Prompt";
import { t } from "../../lang/helpers";
import {
@@ -49,7 +49,7 @@ import {
getListOfTemplateFiles,
getURLImageExtension,
} from "../../utils/fileUtils";
import { setLeftHandedMode, sleep, getImageSize } from "../../utils/utils";
import { setLeftHandedMode, getImageSize } from "../../utils/utils";
import {
extractSVGPNGFileName,
getActivePDFPageNumberFromPDFView,
@@ -91,6 +91,7 @@ import ExcalidrawPlugin from "src/core/main";
import { UIModeSettings } from "src/shared/Dialogs/UIModeSettings";
import { PaneTarget } from "src/types/utilTypes";
import { decompress } from "src/utils/sceneDataUtils";
import { insertLaTeXToView } from "src/utils/excalidrawViewHelpers";
declare const PLUGIN_VERSION: string;
@@ -189,7 +190,7 @@ export class CommandManager {
let folderpath = file.path;
if (file instanceof TFile) {
folderpath = normalizePath(
file.path.substr(0, file.path.lastIndexOf(file.name)),
file.path.substring(0, file.path.lastIndexOf(file.name)),
);
}
void this.plugin.createAndOpenDrawing(
@@ -418,7 +419,7 @@ export class CommandManager {
if (!view) {
return false;
}
if (view.leaf !== this.app.workspace.activeLeaf) {
if (view.leaf !== this.app.workspace.getMostRecentLeaf()) {
return false;
}
const editor = view.editor;
@@ -719,10 +720,7 @@ export class CommandManager {
}
if (view) {
if (!this.settings.taskboneEnabled) {
new Notice(
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
4000,
);
new Notice(t("TASKBONE_NOT_ENABLED"), 4000);
return true;
}
void this.taskbone.getTextForView(view, { forceReScan: false });
@@ -742,10 +740,7 @@ export class CommandManager {
}
if (view) {
if (!this.settings.taskboneEnabled) {
new Notice(
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
4000,
);
new Notice(t("TASKBONE_NOT_ENABLED"), 4000);
return true;
}
void this.taskbone.getTextForView(view, { forceReScan: true });
@@ -765,10 +760,7 @@ export class CommandManager {
}
if (view) {
if (!this.settings.taskboneEnabled) {
new Notice(
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
4000,
);
new Notice(t("TASKBONE_NOT_ENABLED"), 4000);
return true;
}
void this.taskbone.getTextForView(view, {
@@ -935,6 +927,7 @@ export class CommandManager {
this.forceSaveCommand = this.addCommand({
id: "save",
//eslint-disable-next-line obsidianmd/commands/no-default-hotkeys
hotkeys: [{ modifiers: ["Ctrl"], key: "s" }], //See also Poposcope
name: t("FORCE_SAVE"),
checkCallback: (checking: boolean) =>
@@ -993,21 +986,15 @@ export class CommandManager {
this.ea.setView(view);
const el = this.ea.getViewSelectedElement();
if (el.type !== "image") {
new Notice(
"Please select an image or embedded markdown document",
4000,
);
new Notice(t("DELETE_IMAGE_NOTICE"), 4000);
return true;
}
const file = this.ea.getViewFileForImageElement(el);
if (!file) {
new Notice(
"Please select an image or embedded markdown document",
4000,
);
new Notice(t("DELETE_IMAGE_NOTICE"), 4000);
return true;
}
void this.app.vault.delete(file);
void this.app.fileManager.trashFile(file);
this.ea.deleteViewElements([el]);
return true;
}
@@ -1048,7 +1035,6 @@ export class CommandManager {
this.addCommand({
id: "insert-link",
hotkeys: [{ modifiers: ["Mod", "Shift"], key: "k" }],
name: t("INSERT_LINK"),
checkCallback: (checking: boolean) => {
if (checking) {
@@ -1071,6 +1057,7 @@ export class CommandManager {
});
this.addCommand({
// eslint-disable-next-line obsidianmd/commands/no-command-in-command-id -- this is actually the command to insert a "command" into the drawing.
id: "insert-command",
name: t("INSERT_COMMAND"),
checkCallback: (checking: boolean) => {
@@ -1629,7 +1616,7 @@ export class CommandManager {
nodes: CanvasNodeLike[];
};
};
const activeView = this.app.workspace.activeLeaf?.view;
const activeView = this.app.workspace.getMostRecentLeaf()?.view;
const isCanvasViewLike = (
view: typeof activeView,
): view is CanvasViewLike =>
@@ -1819,12 +1806,14 @@ export class CommandManager {
const replacer = (link: string, file: TFile) => {
if (node.file) {
node.file.extension === "pdf"
? node.canvas.createFileNode({
pos: { x: node.x + node.width + 10, y: node.y },
file,
})
: node.setFile(file);
if (node.file.extension === "pdf") {
node.canvas.createFileNode({
pos: { x: node.x + node.width + 10, y: node.y },
file,
});
} else {
node.setFile(file);
}
}
if (node.url) {
node.canvas.createFileNode({
@@ -1959,7 +1948,7 @@ export class CommandManager {
nodes: CanvasNodeLike[];
};
};
const activeView = this.app.workspace.activeLeaf?.view;
const activeView = this.app.workspace.getMostRecentLeaf()?.view;
const isCanvasViewLike = (
view: typeof activeView,
): view is CanvasViewLike =>
@@ -2057,9 +2046,7 @@ export class CommandManager {
}
//console.log({counter, file});
if (!newFile || !(newFile instanceof TFile)) {
new Notice(
"File not found. NewExcalidraw Drawing is taking too long to create. Please try again.",
);
new Notice(t("ANNOTATE_IMAGE_ERROR"));
return;
}
@@ -2107,12 +2094,14 @@ export class CommandManager {
const replacer = (link: string, file: TFile) => {
if (node.file) {
node.file.extension === "pdf"
? node.canvas.createFileNode({
pos: { x: node.x + node.width + 10, y: node.y },
file,
})
: node.setFile(file);
if (node.file.extension === "pdf") {
node.canvas.createFileNode({
pos: { x: node.x + node.width + 10, y: node.y },
file,
});
} else {
node.setFile(file);
}
}
if (node.url) {
node.canvas.createFileNode({
+42 -26
View File
@@ -9,6 +9,7 @@ import {
EventRef,
Menu,
FileView,
TAbstractFile,
} from "obsidian";
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import { getLink } from "../../utils/fileUtils";
@@ -105,37 +106,39 @@ export class EventManager {
public async registerEvents() {
await this.plugin.awaitInit();
this.registerEvent(
this.app.workspace.on("editor-paste", this.onPasteHandler.bind(this)),
this.app.workspace.on("editor-paste", (evt, editor, info) =>
this.onPasteHandler(evt, editor, info),
),
);
this.registerEvent(
this.app.vault.on("rename", this.onRenameHandler.bind(this)),
this.app.vault.on("rename", (file, oldPath) =>
this.onRenameHandler(file, oldPath),
),
);
this.registerEvent(
this.app.vault.on("modify", this.onModifyHandler.bind(this)),
this.app.vault.on("modify", (file) => this.onModifyHandler(file)),
);
this.registerEvent(
this.app.vault.on("delete", this.onDeleteHandler.bind(this)),
this.app.vault.on("delete", (file) => this.onDeleteHandler(file)),
);
//save Excalidraw leaf and update embeds when switching to another leaf
this.registerEvent(
this.plugin.app.workspace.on(
"active-leaf-change",
this.onActiveLeafChangeHandler.bind(this),
this.plugin.app.workspace.on("active-leaf-change", (leaf) =>
this.onActiveLeafChangeHandler(leaf),
),
);
this.registerEvent(
this.app.workspace.on(
"layout-change",
this.onLayoutChangeHandler.bind(this),
this.app.workspace.on("layout-change", () =>
this.onLayoutChangeHandler(),
),
);
//File Save Trigger Handlers
//Save the drawing if the user clicks outside the Excalidraw Canvas
const onClickEventSaveActiveDrawing =
this.onClickSaveActiveDrawing.bind(this);
const onClickEventSaveActiveDrawing = (e: PointerEvent) =>
this.onClickSaveActiveDrawing(e);
this.app.workspace.containerEl.addEventListener(
"click",
onClickEventSaveActiveDrawing,
@@ -147,9 +150,8 @@ export class EventManager {
);
});
this.registerEvent(
this.app.workspace.on(
"file-menu",
this.onFileMenuSaveActiveDrawing.bind(this),
this.app.workspace.on("file-menu", () =>
this.onFileMenuSaveActiveDrawing(),
),
);
@@ -161,13 +163,20 @@ export class EventManager {
);
this.registerEvent(
this.app.workspace.on("file-menu", this.onFileMenuHandler.bind(this)),
this.app.workspace.on("file-menu", (menu, file, source, leaf) => {
if (!(file instanceof TFile)) {
return;
}
this.onFileMenuHandler(menu, file, source, leaf);
}),
);
this.plugin.registerEvent(
this.plugin.app.workspace.on(
"editor-menu",
this.onEditorMenuHandler.bind(this),
),
this.plugin.app.workspace.on("editor-menu", (menu, editor, view) => {
if (!(view instanceof MarkdownView)) {
return;
}
this.onEditorMenuHandler(menu, editor, view);
}),
);
}
@@ -204,7 +213,11 @@ export class EventManager {
if (data.startsWith(`{"type":"excalidraw/clipboard"`)) {
evt.preventDefault();
try {
const drawing = JSON.parse(data);
const drawing = JSON.parse(data) as {
type: string;
elements: ExcalidrawElement[];
};
const hasOneTextElement =
drawing.elements.filter((el: ExcalidrawElement) => el.type === "text")
.length === 1;
@@ -245,22 +258,22 @@ export class EventManager {
} catch (error) {
console.error(
"Error parsing pasted Excalidraw element",
this.onPasteHandler,
this.onPasteHandler.bind(this),
error,
);
}
}
}
private onRenameHandler(file: TFile, oldPath: string) {
private onRenameHandler(file: TAbstractFile, oldPath: string) {
void this.plugin.renameEventHandler(file, oldPath);
}
private onModifyHandler(file: TFile) {
private onModifyHandler(file: TAbstractFile) {
void this.plugin.modifyEventHandler(file);
}
private onDeleteHandler(file: TFile) {
private onDeleteHandler(file: TAbstractFile) {
void this.plugin.deleteEventHandler(file);
}
@@ -273,7 +286,10 @@ export class EventManager {
//In Obsidian 1.8.x the active excalidraw leaf is obscured by an empty leaf without a parent
//This hack resolves it
if (this.app.workspace.activeLeaf === leaf && isUnwantedLeaf(leaf)) {
if (
//this.app.workspace.getMostRecentLeaf() === leaf &&
isUnwantedLeaf(leaf)
) {
leaf.detach();
return;
}
+14 -8
View File
@@ -553,8 +553,8 @@ export class PluginFileManager {
}
if (
this.app.workspace.activeLeaf?.view instanceof ExcalidrawView &&
this.app.workspace.activeLeaf.view.file === file
this.app.workspace.getMostRecentLeaf()?.view instanceof ExcalidrawView &&
this.app.workspace.getMostRecentLeaf()?.view.file === file
) {
this.plugin.lastActiveExcalidrawFilePath = file.path;
}
@@ -588,7 +588,7 @@ export class PluginFileManager {
excalidrawFile: file,
action: "export",
}) ?? newImgPath;
} catch (e) {
} catch (e: unknown) {
errorlog({
where: "FileManager.renameEventHandler",
fn: "plugin.ea.onImageExportPathHook",
@@ -612,7 +612,10 @@ export class PluginFileManager {
});
}
public async modifyEventHandler(file: TFile) {
public async modifyEventHandler(file: TAbstractFile) {
if (!(file instanceof TFile)) {
return;
}
const excalidrawViews = getExcalidrawViews(this.app);
excalidrawViews.forEach((excalidrawView) => {
void (async () => {
@@ -651,7 +654,10 @@ export class PluginFileManager {
// Edge case impact:
// - In extremely rare situations, an update arriving within the "recent switch" timeframe (e.g., from Obsidian Sync)
// might not trigger a reload. This is unlikely and an acceptable trade-off for better user experience.
const activeView = this.app.workspace.activeLeaf.view;
const activeView = this.app.workspace.getMostRecentLeaf()?.view;
if (!activeView) {
return;
}
const isEditingMarkdownSideInSplitView =
(activeView !== excalidrawView &&
activeView instanceof MarkdownView &&
@@ -683,7 +689,7 @@ export class PluginFileManager {
window.clearTimeout(excalidrawView.autosaveTimer);
}
if (excalidrawView.autosaveFunction) {
await excalidrawView.autosaveFunction();
excalidrawView.autosaveFunction();
}
}
} else {
@@ -727,7 +733,7 @@ export class PluginFileManager {
* @param file
* @returns
*/
public async deleteEventHandler(file: TFile) {
public async deleteEventHandler(file: TAbstractFile) {
if (!(file instanceof TFile)) {
return;
}
@@ -780,7 +786,7 @@ export class PluginFileManager {
imgMap.forEach((imgPath: string) => {
const imgFile = this.app.vault.getFileByPath(normalizePath(imgPath));
if (imgFile) {
void this.app.vault.delete(imgFile);
void this.app.fileManager.trashFile(imgFile);
}
});
}, 500);
+50 -32
View File
@@ -36,7 +36,11 @@ import { FILENAMEPARTS, PreviewImageType } from "../../types/utilTypes";
import { CustomMutationObserver, DEBUGGING } from "../../utils/debugHelper";
import { getExcalidrawFileForwardLinks } from "../../utils/excalidrawViewUtils";
import { linkPrompt } from "../../shared/Dialogs/Prompt";
import { isHTMLElement } from "../../utils/typechecks";
import {
isInstanceOfHTMLElement,
isInstanceOfHTMLImageElement,
isInstanceOfSVGElement,
} from "../../utils/typechecks";
import { ExportSettings } from "src/types/exportUtilTypes";
import { setElementDisplay } from "src/utils/htmlUtils";
import { setStyle } from "src/utils/styleUtils";
@@ -175,7 +179,10 @@ const _getPNG = async ({
img.addEventListener("error", cleanup, { once: true });
}
cacheReady && getImageCache().addImageToCache(cacheKey, blobUrl, png);
if (cacheReady) {
getImageCache().addImageToCache(cacheKey, blobUrl, png);
}
return img;
};
@@ -398,8 +405,8 @@ const _getSVGNative = async ({
}
//cache SVG should have the width and height parameters and not the embedded font
if (!maybeSVG) {
cacheReady && getImageCache().addImageToCache(cacheKey, "", svg);
if (!maybeSVG && cacheReady) {
getImageCache().addImageToCache(cacheKey, "", svg);
}
if (width && !isNaN(width)) {
@@ -548,7 +555,9 @@ const addSVGToImgSrc = (
img.addEventListener("error", cleanup, { once: true });
}
cacheReady && getImageCache().addImageToCache(cacheKey, blobUrl, blob);
if (cacheReady) {
getImageCache().addImageToCache(cacheKey, blobUrl, blob);
}
return img;
};
@@ -572,7 +581,7 @@ const createImgElement = async (
let timer: number;
const clickEvent = (ev: PointerEvent) => {
if (!isHTMLElement(ev.target)) {
if (!(isInstanceOfHTMLElement(ev.target) || isInstanceOfSVGElement(ev.target))) {
return;
}
const targetElement = ev.target;
@@ -845,15 +854,16 @@ function parseAlias(input: string): AliasParts {
const parts = input.split("|").map((part) => part.trim());
switch (parts.length) {
case 1:
case 1: {
const singleMatch = getDimensionsFromAliasString(parts[0]);
if (singleMatch) {
return singleMatch; // Return dimensions if valid
}
result.style = parts[0]; // Otherwise, return as style
break;
}
case 2:
case 2: {
const firstDim = getDimensionsFromAliasString(parts[0]);
const secondDim = getDimensionsFromAliasString(parts[1]);
@@ -870,8 +880,9 @@ function parseAlias(input: string): AliasParts {
result.style = parts[1]; // Assuming second part is style
}
break;
}
case 3:
case 3: {
const middleMatch = getDimensionsFromAliasString(parts[1]);
if (middleMatch) {
result.alias = parts[0];
@@ -883,8 +894,9 @@ function parseAlias(input: string): AliasParts {
result.style = parts[2]; // Last part is style
}
break;
}
default:
default: {
const secondValue = getDimensionsFromAliasString(parts[1]);
if (secondValue) {
result.alias = parts[0];
@@ -896,6 +908,7 @@ function parseAlias(input: string): AliasParts {
result.style = parts[parts.length - 1]; // Last part is style
}
break;
}
}
// Clean up the result to remove undefined properties
@@ -1076,7 +1089,7 @@ const tmpObsidianWYSIWYG = async (
internalEmbedDiv.removeClass("inline-embed");
internalEmbedDiv.addClass("media-embed");
internalEmbedDiv.addClass("image-embed");
if (!onCanvas && imgDiv.firstChild instanceof HTMLElement) {
if (!onCanvas && (isInstanceOfHTMLElement(imgDiv.firstChild) || isInstanceOfSVGElement(imgDiv.firstChild))) {
setStyle(imgDiv.firstChild, {
maxHeight: "100%",
maxWidth: null,
@@ -1086,7 +1099,7 @@ const tmpObsidianWYSIWYG = async (
if (
!onCanvas &&
isHoverPopover &&
imgDiv.firstChild instanceof HTMLImageElement
isInstanceOfHTMLImageElement(imgDiv.firstChild)
) {
internalEmbedDiv.style.setProperty(
"--popover-width",
@@ -1237,7 +1250,7 @@ export const markdownPostProcessor = async (
//transcluded text element or some other transcluded content inside the Excalidraw file
//in reading mode these elements should be hidden
const excalidrawFile = Boolean(
ctx.frontmatter?.hasOwnProperty("excalidraw-plugin"),
ctx.frontmatter && "excalidraw-plugin" in ctx.frontmatter,
);
if (!(isPreview || isMarkdownReadingMode || isPrinting) && excalidrawFile) {
setElementDisplay(el, "none");
@@ -1264,7 +1277,7 @@ export const hoverEvent = (
};
//monitoring for div.popover.hover-popover.file-embed.is-loaded to be added to the DOM tree
const legacyExcalidrawPopoverObserverFn: MutationCallback = async (m) => {
const legacyExcalidrawPopoverObserverFn: MutationCallback = (m) => {
if (m.length === 0) {
return;
}
@@ -1319,25 +1332,30 @@ const legacyExcalidrawPopoverObserverFn: MutationCallback = async (m) => {
//this div will be on top of original DIV. By stopping the propagation of the click
//I prevent the default Obsidian feature of opening the link in the native app
const img = await getIMG({
file,
fname: file.path,
fwidth: "300",
fheight: null,
imgstyle: ["excalidraw-svg"],
});
const div = createDiv("", (el) => {
el.appendChild(img);
el.setAttribute("src", file.path);
el.onClickEvent((ev) => {
ev.stopImmediatePropagation();
const src = el.getAttribute("src");
if (src) {
plugin.openDrawing(vault.getFileByPath(src), linkClickModifierType(ev));
} //.ctrlKey||ev.metaKey);
void (async () => {
const img = await getIMG({
file,
fname: file.path,
fwidth: "300",
fheight: null,
imgstyle: ["excalidraw-svg"],
});
});
node.appendChild(div);
const div = createDiv("", (el) => {
el.appendChild(img);
el.setAttribute("src", file.path);
el.onClickEvent((ev) => {
ev.stopImmediatePropagation();
const src = el.getAttribute("src");
if (src) {
plugin.openDrawing(
vault.getFileByPath(src),
linkClickModifierType(ev),
);
} //.ctrlKey||ev.metaKey);
});
});
node.appendChild(div);
})();
};
export const legacyExcalidrawPopoverObserver = DEBUGGING
+182
View File
@@ -0,0 +1,182 @@
import {
MarkdownView,
View,
ViewState,
ViewStateResult,
Workspace,
WorkspaceLeaf,
} from "obsidian";
import { around, dedupe } from "monkey-around";
import type ExcalidrawPlugin from "src/core/main";
import { VIEW_TYPE_EXCALIDRAW } from "src/constants/constants";
import { URLs } from "src/constants/safeUrls";
import { fileShouldDefaultAsExcalidraw } from "src/utils/fileUtils";
import { foldExcalidrawSection } from "src/utils/obsidianUtils";
import type ExcalidrawView from "src/view/ExcalidrawView";
type ViewConstructor<T extends View = View> = new (...args: unknown[]) => T;
/**
* Registers workspace monkey patches that adapt Obsidian behavior
* for Excalidraw and known plugin integrations.
*/
export class MonkeyPatchManager {
private readonly plugin: ExcalidrawPlugin;
constructor(plugin: ExcalidrawPlugin) {
this.plugin = plugin;
}
public initialize(): void {
this.patchTemplaterGetActiveViewOfType();
this.patchHoverEditorGetRoot();
this.patchWorkspaceLeafExcalidrawDefault();
}
private patchTemplaterGetActiveViewOfType(): void {
const key = URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES;
this.plugin.register(
around(Workspace.prototype, {
getActiveViewOfType(old: Workspace["getActiveViewOfType"]) {
return dedupe(key, old, function <
T extends View,
>(this: Workspace, type: ViewConstructor<T>): T | null {
const result = old.call(this, type) as T | null;
const maybeEAView = this.getMostRecentLeaf()?.view;
if (
!maybeEAView ||
maybeEAView.getViewType() !== VIEW_TYPE_EXCALIDRAW
) {
return result;
}
const stackTrace = new Error().stack ?? "";
if (!MonkeyPatchManager.isCallerFromTemplaterPlugin(stackTrace)) {
return result;
}
const leafOrNode = (
maybeEAView as ExcalidrawView
).getActiveEmbeddable();
if (leafOrNode?.node?.isEditing) {
return {
file: leafOrNode.node.file,
editor: leafOrNode.node.child.editor,
} as unknown as T;
}
return result;
});
},
}),
);
}
private patchHoverEditorGetRoot(): void {
if (this.plugin.app.plugins.plugins?.["obsidian-hover-editor"]) {
return;
}
this.plugin.register(
// Stolen from hover editor.
around(WorkspaceLeaf.prototype, {
getRoot(old: WorkspaceLeaf["getRoot"]) {
return function (
this: WorkspaceLeaf,
): ReturnType<WorkspaceLeaf["getRoot"]> {
const top = old.call(this) as WorkspaceLeaf;
return top.getRoot === this.getRoot ? top : top.getRoot();
};
},
}),
);
}
private patchWorkspaceLeafExcalidrawDefault(): void {
const plugin = this.plugin;
this.plugin.register(
around(WorkspaceLeaf.prototype, {
// Drawings can be viewed as markdown or Excalidraw, and we keep track of the mode
// while the file is open. When the file closes, we no longer need to keep track of it.
detach(next: WorkspaceLeaf["detach"]) {
return function (
this: WorkspaceLeaf,
): ReturnType<WorkspaceLeaf["detach"]> {
const state = this.view?.getState();
const stateFile =
typeof state?.file === "string" ? state.file : null;
const leafKey = this.id || stateFile;
if (leafKey && plugin.excalidrawFileModes[leafKey]) {
delete plugin.excalidrawFileModes[leafKey];
}
return next.apply(this) as ReturnType<WorkspaceLeaf["detach"]>;
};
},
setViewState(next: WorkspaceLeaf["setViewState"]) {
return function (
this: WorkspaceLeaf,
state: ViewState,
...rest: [ViewStateResult?]
): ReturnType<WorkspaceLeaf["setViewState"]> {
const filePath = state.state?.file;
const markdownViewLoaded =
plugin._loaded && // Do not force Excalidraw mode during shutdown.
state.type === "markdown" &&
typeof filePath === "string";
if (
markdownViewLoaded &&
plugin.excalidrawFileModes[this.id || filePath] !== "markdown"
) {
if (
plugin.forceToOpenInMarkdownFilepath !== filePath &&
fileShouldDefaultAsExcalidraw(filePath, plugin.app)
) {
const newState: ViewState = {
...state,
type: VIEW_TYPE_EXCALIDRAW,
};
plugin.excalidrawFileModes[filePath] = VIEW_TYPE_EXCALIDRAW;
return next.apply(this, [newState, ...rest]) as ReturnType<
WorkspaceLeaf["setViewState"]
>;
}
plugin.forceToOpenInMarkdownFilepath = null;
}
if (markdownViewLoaded) {
window.setTimeout(() => {
if (
!(this.view instanceof MarkdownView) ||
!this.view.file ||
!plugin.isExcalidrawFile(this.view.file)
) {
return;
}
foldExcalidrawSection(this.view);
}, 500);
}
return next.apply(this, [state, ...rest]) as ReturnType<
WorkspaceLeaf["setViewState"]
>;
};
},
}),
);
}
private static isCallerFromTemplaterPlugin(stackTrace: string): boolean {
const lines = stackTrace.split("\n");
for (const line of lines) {
if (line.trim().startsWith("at Templater.")) {
return true;
}
}
return false;
}
}
+14 -9
View File
@@ -7,6 +7,10 @@ import {
isObsidianThemeDark,
} from "src/utils/obsidianUtils";
import { App, Notice, TFile } from "obsidian";
import {
isInstanceOfDocumentFragment,
isInstanceOfElement,
} from "src/utils/typechecks";
export class ObserverManager {
private plugin: ExcalidrawPlugin;
@@ -80,9 +84,7 @@ export class ObserverManager {
return;
}
const themeObserverFn: MutationCallback = async (
mutations: MutationRecord[],
) => {
const themeObserverFn: MutationCallback = (mutations: MutationRecord[]) => {
const { matchThemeTrigger } = this.settings;
if (!matchThemeTrigger) {
return;
@@ -178,11 +180,14 @@ export class ObserverManager {
mutationsList.forEach((mutation) => {
if (mutation.type === "childList") {
mutation.addedNodes.forEach((node) => {
if (node instanceof Element || node instanceof DocumentFragment) {
if (
isInstanceOfElement(node) ||
isInstanceOfDocumentFragment(node)
) {
ensureFiletypes(node);
}
});
if (mutation.target instanceof Element) {
if (isInstanceOfElement(mutation.target)) {
// Handles folders that were collapsed/expanded without adding nodes
ensureFiletypes(mutation.target);
}
@@ -191,7 +196,7 @@ export class ObserverManager {
if (
mutation.type === "attributes" &&
mutation.target instanceof Element
isInstanceOfElement(mutation.target)
) {
ensureFiletypes(mutation.target);
}
@@ -237,7 +242,7 @@ export class ObserverManager {
const added = Array.from(mutation.addedNodes ?? []);
const hasContainer = added.some(
(node) =>
node instanceof Element &&
isInstanceOfElement(node) &&
(node.matches?.(".nav-files-container") ||
node.querySelector?.(".nav-files-container")),
);
@@ -276,7 +281,7 @@ export class ObserverManager {
this.removeModalContainerObserver();
}
//The user clicks settings, or "open another vault", or the command palette
const modalContainerObserverFn: MutationCallback = async (
const modalContainerObserverFn: MutationCallback = (
m: MutationRecord[],
) => {
const view = this.plugin.activeExcalidrawView;
@@ -293,7 +298,7 @@ export class ObserverManager {
const { errorMessage } = view.excalidrawAPI.getAppState();
if (!errorMessage) {
await this.plugin.activeExcalidrawView.save();
void this.plugin.activeExcalidrawView.save();
}
};
+8 -5
View File
@@ -112,13 +112,18 @@ export class StylesManager {
const iframeDoc = iframe.contentWindow.document;
const iframeWin = iframe.contentWindow;
iframeDoc.open();
iframeDoc.write(`<head>${mainDocument.head.innerHTML}</head>`);
iframeDoc.close();
iframeDoc.close(); // Closes the stream to clear out the default page skeleton
const newHead = iframeDoc.createElement("head");
Array.from(mainDocument.head.children).forEach((child) => {
newHead.appendChild(child.cloneNode(true));
});
iframeDoc.documentElement.replaceChild(newHead, iframeDoc.head);
await iframeLoadedPromise;
const iframeBody = iframe.contentWindow.document.body;
const iframeBody = iframeDoc.body;
iframeBody.setAttribute("style", body.getAttribute("style"));
iframeBody.setAttribute("class", body.getAttribute("class"));
@@ -164,7 +169,6 @@ export class StylesManager {
);
} else {
const lightStyleTag = doc.createElement("style");
lightStyleTag.type = "text/css";
lightStyleTag.setAttribute("id", "excalidraw-embedded-light");
setStyleText(
lightStyleTag,
@@ -173,7 +177,6 @@ export class StylesManager {
doc.head.appendChild(lightStyleTag);
const darkStyleTag = doc.createElement("style");
darkStyleTag.type = "text/css";
darkStyleTag.setAttribute("id", "excalidraw-embedded-dark");
setStyleText(
darkStyleTag,
+61 -47
View File
@@ -748,6 +748,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
borderColor: "#fff",
borderOpacity: 0,
filenameVisible: false,
lockedReadingMode: false,
},
markdownNodeOneClickEditing: false,
canvasImmersiveEmbed: true,
@@ -1233,7 +1234,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}
}
async hide() {
hide() {
this.detachSettingsFocusoutHandler();
if (this.plugin.settings.overrideObsidianFontSize) {
setStyle(mainDocument.documentElement, { fontSize: "" });
@@ -1247,22 +1248,24 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
setRootElementSize();
}
await this.persistDirtySettings();
await this.applyPendingActions();
this.hotkeyEditor.unload();
if (this.hotkeyEditor.isDirty) {
this.plugin.registerHotkeyOverrides();
}
this.plugin.scriptEngine.updateScriptPath();
void (async () => {
void (await this.persistDirtySettings());
void (await this.applyPendingActions());
this.hotkeyEditor.unload();
if (this.hotkeyEditor.isDirty) {
this.plugin.registerHotkeyOverrides();
}
this.plugin.scriptEngine.updateScriptPath();
})();
/* if(this.reloadMathJax) {
this.plugin.loadMathJax();
}*/
}
async display() {
display() {
let detailsEl: HTMLElement;
await this.plugin.loadSettings(); //in case sync loaded changed settings in the background
//await this.plugin.loadSettings(); //in case sync loaded changed settings in the background
this.settingsDirty = false;
this.requestEmbedUpdate = false;
this.requestReloadDrawings = false;
@@ -1317,7 +1320,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
"span",
{
cls: "excalidraw-mastery-promo__summary-title",
text: "Excalidraw Mastery",
text: t("EXCALIDRAW_MASTERY"),
},
);
const excalidrawMasterySummaryState = excalidrawMasterySummary.createEl(
@@ -1509,7 +1512,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("FOLDER_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: Excalidraw")
.setPlaceholder(t("FOLDER_PLACEHOLDER"))
.setValue(this.plugin.settings.folder)
.onChange(async (value) => {
this.plugin.settings.folder = value;
@@ -1534,7 +1537,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("CROP_FOLDER_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: Excalidraw/Cropped")
.setPlaceholder(t("CROP_FOLDER_PLACEHOLDER"))
.setValue(this.plugin.settings.cropFolder)
.onChange(async (value) => {
this.plugin.settings.cropFolder = value;
@@ -1547,7 +1550,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("ANNOTATE_FOLDER_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: Excalidraw/Annotations")
.setPlaceholder(t("ANNOTATE_FOLDER_PLACEHOLDER"))
.setValue(this.plugin.settings.annotateFolder)
.onChange(async (value) => {
this.plugin.settings.annotateFolder = value;
@@ -1560,7 +1563,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("TEMPLATE_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: Excalidraw/Template")
.setPlaceholder(t("TEMPLATE_PLACEHOLDER"))
.setValue(this.plugin.settings.templateFilePath)
.onChange(async (value) => {
this.plugin.settings.templateFilePath = value;
@@ -1574,7 +1577,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("SCRIPT_FOLDER_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: Excalidraw/Scripts")
.setPlaceholder(t("SCRIPT_FOLDER_PLACEHOLDER"))
.setValue(this.plugin.settings.scriptFolderPath)
.onChange(async (value) => {
this.plugin.settings.scriptFolderPath = value;
@@ -1686,7 +1689,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("FILENAME_PREFIX_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: Drawing ")
.setPlaceholder(t("FILENAME_PREFIX_PLACEHOLDER"))
.setValue(this.plugin.settings.drawingFilenamePrefix)
.onChange(async (value) => {
this.plugin.settings.drawingFilenamePrefix = value.replaceAll(
@@ -1766,7 +1769,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("CROP_PREFIX_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: cropped_")
.setPlaceholder(t("CROP_PREFIX_PLACEHOLDER"))
.setValue(this.plugin.settings.cropPrefix)
.onChange(async (value) => {
this.plugin.settings.cropPrefix = value.replaceAll(
@@ -1783,7 +1786,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("CROP_SUFFIX_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: _cropped")
.setPlaceholder(t("CROP_SUFFIX_PLACEHOLDER"))
.setValue(this.plugin.settings.cropSuffix)
.onChange(async (value) => {
this.plugin.settings.cropSuffix = value.replaceAll(
@@ -1800,7 +1803,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("ANNOTATE_PREFIX_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: annotated_")
.setPlaceholder(t("ANNOTATE_PREFIX_PLACEHOLDER"))
.setValue(this.plugin.settings.annotatePrefix)
.onChange(async (value) => {
this.plugin.settings.annotatePrefix = value.replaceAll(
@@ -1817,7 +1820,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("ANNOTATE_SUFFIX_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: _annotated")
.setPlaceholder(t("ANNOTATE_SUFFIX_PLACEHOLDER"))
.setValue(this.plugin.settings.annotateSuffix)
.onChange(async (value) => {
this.plugin.settings.annotateSuffix = value.replaceAll(
@@ -2290,7 +2293,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
)
.setDesc(fragWithHTML(description))
.addDropdown((dropdown) => {
optionValues.forEach((value) => dropdown.addOption(value, value));
optionValues.forEach((value) => {
void dropdown.addOption(value, value);
});
return dropdown.setValue(selectedValue).onChange((value) => {
if (kind === "text") {
selectedTextModelConfig = value;
@@ -2574,9 +2579,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("DYNAMICSTYLE_DESC")))
.addDropdown((dropdown) =>
dropdown
.addOption("none", "Dynamic Styling OFF")
.addOption("colorful", "Match color")
.addOption("gray", "Gray, match tone")
.addOption("none", t("DYNAMICSTYLE_OPTION_NONE"))
.addOption("colorful", t("DYNAMICSTYLE_OPTION_COLORFUL"))
.addOption("gray", t("DYNAMICSTYLE_OPTION_GRAY"))
.setValue(this.plugin.settings.dynamicStyling)
.onChange(async (value) => {
this.requestUpdateDynamicStyling = true;
@@ -2645,10 +2650,10 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("DEFAULT_OPEN_MODE_DESC")))
.addDropdown((dropdown) =>
dropdown
.addOption("normal", "Always in normal-mode")
.addOption("zen", "Always in zen-mode")
.addOption("view", "Always in view-mode")
.addOption("view-mobile", "Usually normal, but view-mode on Phone")
.addOption("normal", t("DEFAULT_OPEN_MODE_OPTION_NORMAL"))
.addOption("zen", t("DEFAULT_OPEN_MODE_OPTION_ZEN"))
.addOption("view", t("DEFAULT_OPEN_MODE_OPTION_VIEW"))
.addOption("view-mobile", t("DEFAULT_OPEN_MODE_OPTION_VIEW_MOBILE"))
.setValue(this.plugin.settings.defaultMode)
.onChange(async (value) => {
this.plugin.settings.defaultMode = value;
@@ -2809,9 +2814,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("DEFAULT_PEN_MODE_DESC")))
.addDropdown((dropdown) =>
dropdown
.addOption("never", "Never")
.addOption("mobile", "On Obsidian Mobile")
.addOption("always", "Always")
.addOption("never", t("DEFAULT_PEN_MODE_OPTION_NEVER"))
.addOption("mobile", t("DEFAULT_PEN_MODE_OPTION_MOBILE"))
.addOption("always", t("DEFAULT_PEN_MODE_OPTION_ALWAYS"))
.setValue(this.plugin.settings.defaultPenMode)
.onChange(async (value: "never" | "always" | "mobile") => {
this.plugin.settings.defaultPenMode = value;
@@ -3070,7 +3075,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
new ModifierKeySettingsComponent(
detailsEl,
this.plugin.settings.modifierKeyConfig,
this.applySettingsUpdate.bind(this),
() => this.applySettingsUpdate(),
).render();
// ------------------------------------------------
@@ -3389,9 +3394,18 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("EMBED_PREVIEW_IMAGETYPE_DESC")))
.addDropdown((dropdown) =>
dropdown
.addOption(PreviewImageType.PNG, "PNG Image")
.addOption(PreviewImageType.SVG, "Native SVG")
.addOption(PreviewImageType.SVGIMG, "SVG Image")
.addOption(
PreviewImageType.PNG,
t("EMBED_PREVIEW_IMAGETYPE_OPTION_PNG"),
)
.addOption(
PreviewImageType.SVG,
t("EMBED_PREVIEW_IMAGETYPE_OPTION_SVG"),
)
.addOption(
PreviewImageType.SVGIMG,
t("EMBED_PREVIEW_IMAGETYPE_OPTION_SVGIMG"),
)
.setValue(this.plugin.settings.previewImageType)
.onChange((value) => {
this.plugin.settings.previewImageType = value as PreviewImageType;
@@ -3408,7 +3422,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("EMBED_TYPE_DESC")))
.addDropdown(async (d: DropdownComponent) => {
dropdown = d;
dropdown.addOption("excalidraw", "excalidraw");
dropdown.addOption("excalidraw", "Excalidraw");
if (this.plugin.settings.autoexportPNG) {
dropdown.addOption("PNG", "PNG");
} else if (this.plugin.settings.embedType === "PNG") {
@@ -3628,7 +3642,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("EMBED_WIDTH_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: 400")
.setPlaceholder("400")
.setValue(this.plugin.settings.width)
.onChange(async (value) => {
this.plugin.settings.width = value;
@@ -3642,7 +3656,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("EMBED_HEIGHT_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: 400")
.setPlaceholder("400")
.setValue(this.plugin.settings.height)
.onChange(async (value) => {
this.plugin.settings.height = value;
@@ -3978,7 +3992,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("MD_DEFAULT_COLOR_DESC")))
.addText((text) =>
text
.setPlaceholder("CSS Color-name|RGB-HEX")
.setPlaceholder(t("DEFAULT_COLOR_MD_DESC"))
.setValue(this.plugin.settings.mdFontColor)
.onChange((value) => {
this.requestReloadDrawings = true;
@@ -3992,7 +4006,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("MD_DEFAULT_BORDER_COLOR_DESC")))
.addText((text) =>
text
.setPlaceholder("CSS Color-name|RGB-HEX")
.setPlaceholder(t("DEFAULT_COLOR_MD_DESC"))
.setValue(this.plugin.settings.mdBorderColor)
.onChange((value) => {
this.requestReloadDrawings = true;
@@ -4006,7 +4020,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("MD_CSS_DESC")))
.addText((text) =>
text
.setPlaceholder("filename of css file in vault")
.setPlaceholder(t("MD_CSS_PLACEHOLDER"))
.setValue(this.plugin.settings.mdCSS)
.onChange((value) => {
this.requestReloadDrawings = true;
@@ -4156,7 +4170,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setDesc(fragWithHTML(t("CJK_ASSETS_FOLDER_DESC")))
.addText((text) =>
text
.setPlaceholder("e.g.: Excalidraw/FontAssets")
.setPlaceholder(t("CJK_ASSETS_FOLDER_PLACEHOLDER"))
.setValue(this.plugin.settings.fontAssetsPath)
.onChange(async (value) => {
this.plugin.settings.fontAssetsPath = value;
@@ -4464,7 +4478,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
}
startupScriptButton.setButtonText(t("STARTUP_SCRIPT_BUTTON_OPEN"));
await this.app.workspace.openLinkText(f.path, "", true);
await this.hide();
this.hide();
});
});
@@ -4648,9 +4662,9 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setName(variableName)
.setDesc(fragWithHTML(description ?? ""))
.addDropdown((dropdown) => {
valueset.forEach((val: string) =>
dropdown.addOption(val.toString(), val.toString()),
);
valueset.forEach((val: string) => {
void dropdown.addOption(val.toString(), val.toString());
});
dropdown
.setValue(getValue(scriptName, variableName) as string)
.onChange(async (value) => {
+28 -4
View File
@@ -24,6 +24,25 @@ declare const PLUGIN_VERSION: string;
let locale: Partial<typeof en> | null = null;
type LocaleFactory = (
device: typeof DEVICE,
frontmatterKeys: typeof FRONTMATTER_KEYS,
cjkFonts: typeof CJK_FONTS,
tagAutoexport: typeof TAG_AUTOEXPORT,
tagMdReadingMode: typeof TAG_MDREADINGMODE,
tagPdfExport: typeof TAG_PDFEXPORT,
safeUrls: typeof URLs,
altLabel: typeof labelALT,
ctrlLabel: typeof labelCTRL,
metaLabel: typeof labelMETA,
shiftLabel: typeof labelSHIFT,
pluginVersion: string,
) => Partial<typeof en>;
type LocaleRuntimeGlobals = {
unpackBase64Deflate?: (value: string) => string;
};
function loadLocale(lang: string): Partial<typeof en> {
if (lang === "zh") {
lang = "zh-cn";
@@ -35,7 +54,12 @@ function loadLocale(lang: string): Partial<typeof en> {
try {
const compressed = PLUGIN_LANGUAGES[lang];
const decompressed = unpackBase64Deflate(compressed);
const runtimeGlobals = window as Window & LocaleRuntimeGlobals;
const unpack = runtimeGlobals.unpackBase64Deflate;
if (typeof unpack !== "function") {
return en;
}
const decompressed = unpack(compressed);
// Construct a factory function string.
// This allows safeEval (which runs in the global scope) to access our imported variables
@@ -53,15 +77,15 @@ function loadLocale(lang: string): Partial<typeof en> {
})`;
// Evaluate the function declaration using your ErrorHandler
const factory = errorHandler.safeEval<Function>(
const factoryResult = errorHandler.safeEval<unknown>(
factoryCode,
"loadLocale - parsing language pack",
window,
);
if (typeof factory !== "function") {
if (typeof factoryResult !== "function") {
return en;
}
const factory = factoryResult as LocaleFactory;
// Execute the evaluated function, injecting the actual imported dependencies
const x = factory(
+57 -4
View File
@@ -19,6 +19,7 @@ export default {
// Sugester
SELECT_FILE_TO_INSERT: "Select a file to insert",
// main.ts
ERROR_INITIALIZING_EA: "Error initializing Excalidraw Automate",
CONVERT_URL_TO_FILE: "Save image from URL to local file",
UNZIP_CURRENT_FILE: "Decompress current Excalidraw file",
PUBLISH_SVG_CHECK:
@@ -65,6 +66,7 @@ export default {
"Create new drawing - IN A POPOUT WINDOW - and embed into active document",
TOGGLE_LOCK: "Toggle Text Element between edit RAW and PREVIEW",
DELETE_FILE: "Delete selected image or Markdown file from Obsidian Vault",
DELETE_IMAGE_NOTICE: "Please select an image or embedded markdown document",
MARKER_FRAME_SHOW: "Marker Frames Visible",
MARKER_FRAME_TITLE_SHOW: "Marker Frame Titles Visible",
COPY_ELEMENT_LINK: "Copy [[link]] for selected element(s)",
@@ -116,6 +118,8 @@ export default {
ABOUT_EXCALIDRAW: "About Excalidraw",
RUN_OCR:
"OCR full drawing: Grab text from freedraw + images to clipboard and doc.props",
TASKBONE_NOT_ENABLED:
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
RERUN_OCR:
"OCR full drawing re-run: Grab text from freedraw + images to clipboard and doc.props",
RUN_OCR_ELEMENTS:
@@ -125,6 +129,8 @@ export default {
CROP_PAGE: "Crop and mask selected page",
CROP_IMAGE: "Crop and mask image",
ANNOTATE_IMAGE: "Annotate image in Excalidraw",
ANNOTATE_IMAGE_ERROR:
"File not found. New Excalidraw drawing is taking too long to create. Please try again.",
INSERT_ACTIVE_PDF_PAGE_AS_IMAGE: "Insert active PDF page as image",
RESET_IMG_TO_100: "Set selected image element size to 100% of original",
RESET_IMG_ASPECT_RATIO: "Reset selected image element aspect ratio",
@@ -252,6 +258,33 @@ export default {
SEARCH_PREVIOUS: "Previous",
//settings.ts
FOLDER_PLACEHOLDER: "e.g.: Excalidraw",
CROP_FOLDER_PLACEHOLDER: "e.g.: Excalidraw/Cropped",
ANNOTATE_FOLDER_PLACEHOLDER: "e.g.: Excalidraw/Annotations",
TEMPLATE_PLACEHOLDER: "e.g.: Excalidraw/Template",
SCRIPT_FOLDER_PLACEHOLDER: "e.g.: Excalidraw/Scripts",
FILENAME_PREFIX_PLACEHOLDER: "e.g.: Drawing ",
CROP_PREFIX_PLACEHOLDER: "e.g.: cropped_",
CROP_SUFFIX_PLACEHOLDER: "e.g.: _cropped",
ANNOTATE_PREFIX_PLACEHOLDER: "e.g.: annotated_",
ANNOTATE_SUFFIX_PLACEHOLDER: "e.g.: _annotated",
DYNAMICSTYLE_OPTION_NONE: "Dynamic Styling OFF",
DYNAMICSTYLE_OPTION_COLORFUL: "Match color",
DYNAMICSTYLE_OPTION_GRAY: "Gray, match tone",
DEFAULT_OPEN_MODE_OPTION_NORMAL: "Always in normal-mode",
DEFAULT_OPEN_MODE_OPTION_ZEN: "Always in zen-mode",
DEFAULT_OPEN_MODE_OPTION_VIEW: "Always in view-mode",
DEFAULT_OPEN_MODE_OPTION_VIEW_MOBILE:
"Usually normal, but view-mode on Phone",
DEFAULT_PEN_MODE_OPTION_NEVER: "Never",
DEFAULT_PEN_MODE_OPTION_MOBILE: "On Obsidian Mobile",
DEFAULT_PEN_MODE_OPTION_ALWAYS: "Always",
EMBED_PREVIEW_IMAGETYPE_OPTION_PNG: "PNG Image",
EMBED_PREVIEW_IMAGETYPE_OPTION_SVG: "Native SVG",
EMBED_PREVIEW_IMAGETYPE_OPTION_SVGIMG: "SVG Image",
DEFAULT_COLOR_MD_DESC: "CSS Color-name|RGB-HEX",
MD_CSS_PLACEHOLDER: "Filename of CSS file in Vault",
CJK_ASSETS_FOLDER_PLACEHOLDER: "e.g.: Excalidraw/FontAssets",
DISABLE_CONTEXT_MENU_NAME: "Disable Excalidraw context menu",
DISABLE_CONTEXT_MENU_DESC:
"Disables the Excalidraw context menu. This can be useful on Mobile devices where the context menu pops up in unwanted moments.",
@@ -259,6 +292,7 @@ export default {
"Ask NotebookLM for help about the plugin. This model is pre-loaded with all my video transcripts, release notes and other helpful content. Chat with NotebookLM to explore my 250+ videos and the Excalidraw documentation.",
NOTEBOOKLM_LINK_TEXT:
"Learn the Plugin. Access the NotebookLM knowledgebase.",
EXCALIDRAW_MASTERY: "Excalidraw Mastery",
EXCALIDRAW_MASTERY_PROMO_ARIA: "Open Excalidraw Mastery",
EXCALIDRAW_MASTERY_PROMO_HTML: `<p><b>Feeling lost in the toggles and menus?</b></p><p>Excalidraw is a Visual PKM powerhouse built for heavy-duty workflows like <b>Visual-First Daily Notes</b>, deep <b>PDF research</b>, <b>automation</b>, <b>AI integration</b>, and <b>Visual Zettelkasten</b>. But all this power comes with complexity.</p><p>Skip the trial and error. <a href="${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}" target="_blank">👉 Join Excalidraw Mastery</a> to learn these exact setups step-by-step. Overcome tool friction and master your knowledge alongside a supportive community of visual thinkers!</p>`,
EXCALIDRAW_MASTERY_PROMO_SHOW: "Show",
@@ -1179,6 +1213,13 @@ export default {
SCRIPT_EXECUTION_ERROR:
"Script execution error. Please find error message on the developer console.",
//ScriptInstallPrompt.ts
SCRIPT_INSTALL_PROMPT_FETCH_ERROR:
"Error opening the Excalidraw Script Store page. " +
"Please double check that you can access the website. " +
"I've logged the link in developer console (press CTRL+SHIFT+i)",
SCRIPT_INSTALL_PROMPT_OPEN_ERROR: "Could not open ScriptEngine repository",
//ExcalidrawViewUtils.ts
MARKER_FRAME_RENDERING_DISABLED_NOTICE:
"There are hidden marker-frames in the scene.",
@@ -1249,6 +1290,11 @@ export default {
ES_YOUTUBE_START_INVALID:
"The YouTube Start Time is invalid. Please check the format and try again",
ES_FILENAME_VISIBLE: "Filename Visible",
ES_LOCKED_READING_MODE_HEAD: "Locked Reading Mode",
ES_LOCKED_READING_MODE_DESC:
"When enabled, interacting with the markdown embeddable will not switch it to edit mode. This is useful for checklists and habit trackers.",
LOCK_READING_MODE: "Lock Reading Mode",
UNLOCK_READING_MODE: "Unlock Reading Mode",
ES_BACKGROUND_HEAD: "Embedded note background color",
ES_BACKGROUND_DESC_INFO: "Click here for more info on colors",
ES_BACKGROUND_DESC_DETAIL:
@@ -1532,9 +1578,10 @@ Thank you & Enjoy!
// Gateway Modals & Texts
EXTRAS_GATEWAY_TITLE: "Excalidraw Extras Required",
EXTRAS_GATEWAY_DESC:
"To keep Excalidraw lightweight and secure, the '{component}' feature has been moved to the Excalidraw Extras companion plugin.",
"The '{component}' feature has been moved to the Excalidraw Extras companion plugin to keep Excalidraw lightweight, stay within Obsidian Sync Basic size restrictions, and give you explicit control over the additional libraries and elevated-permission functionality it requires.",
EXTRAS_GATEWAY_INSTALL_BTN: "Install from Community Plugins",
EXTRAS_GATEWAY_ENABLE_PERM_BTN: "Enable Plugin Permanently",
EXTRAS_GATEWAY_MANUAL_ENABLE_NOTICE:
"I had implemented a smoother workflow that allowed Excalidraw Extras to be enabled and disabled automatically when needed. Unfortunately, I was forced to remove that feature after it was flagged by the Obsidian code scanner as a high-risk issue, accompanied by an automated explanation that I believe does not accurately reflect what the code does. Please enable Excalidraw Extras manually in Community Plugins. If you'd like to see a more convenient experience in the future, please consider contacting Obsidian and asking for plugin-developer-friendly support for safe automation workflows, including companion plugin management.",
EXTRAS_GATEWAY_ENABLE_FEATURE_PERM_BTN: "Enable {component} Permanently",
EXTRAS_GATEWAY_TEMP_ENABLE_TITLE: "Enable Temporarily",
EXTRAS_GATEWAY_TEMP_ENABLE_DESC:
@@ -1542,8 +1589,6 @@ Thank you & Enjoy!
EXTRAS_GATEWAY_SESSION_ENABLE_DESC:
"Enable this feature for the current Obsidian session only.",
EXTRAS_GATEWAY_ENABLE_CURRENT_SESSION: "Enable for this session",
EXTRAS_GATEWAY_TIMER_EXPIRED:
"Excalidraw Extras temporary timer expired. Plugin disabled.",
EXTRAS_GATEWAY_FEATURE_TIMER_EXPIRED:
"Excalidraw Extras: {component} timer expired. Feature disabled.",
EXTRAS_GATEWAY_API_MISSING:
@@ -1552,4 +1597,12 @@ Thank you & Enjoy!
EXTRAS_GATEWAY_FEATURE_DESC:
"The '{component}' feature is currently disabled in your Excalidraw Extras settings.",
EXTRAS_GATEWAY_IGNORE_SESSION: "Ignore for this session",
EXTRAS_GATEWAY_UPDATE_EXACT:
"Excalidraw Extras Update Required. {component} requires EXACTLY v{reqVersion} (Found v{currentVersion})",
EXTRAS_GATEWAY_UPDATE_MIN:
"Excalidraw Extras Update Required. {component} requires >= v{reqVersion} (Found v{currentVersion})",
EXTRAS_GATEWAY_COMP_PLUGIN: "Excalidraw Extras Plugin",
EXTRAS_GATEWAY_UPDATE_TITLE:
"Excalidraw requires a new version of the Extras plugin",
EXTRAS_GATEWAY_UPDATE_BTN: "Open Community Plugins",
};
+1 -1
View File
@@ -211,7 +211,7 @@ export class CropImage {
const context = canvas.getContext("2d");
if (!context) {
reject("Unable to get 2D context");
reject(new Error("Unable to get 2D context"));
return;
}
+2 -2
View File
@@ -182,8 +182,8 @@ export class AIModelConfigModal<
.setName(t("AI_MODEL_CONFIG_MODAL_PROVIDER_NAME"))
.setDesc(t("AI_MODEL_CONFIG_MODAL_PROVIDER_DESC"))
.addDropdown((dropdown) => {
this.options.providerIds.forEach((providerId) =>
dropdown.addOption(providerId, providerId),
this.options.providerIds.forEach(
(providerId) => void dropdown.addOption(providerId, providerId),
);
return dropdown.setValue(this.config.providerId).onChange((value) => {
this.config.providerId = value;
@@ -53,7 +53,19 @@ export class EmbeddalbeMDFileCustomDataSettingsComponent {
this.mdCustomData.filenameVisible = value;
}),
);
new Setting(contentEl)
.setName(t("ES_LOCKED_READING_MODE_HEAD"))
.setDesc(t("ES_LOCKED_READING_MODE_DESC"))
.addToggle((toggle) =>
toggle
.setValue(!!this.mdCustomData.lockedReadingMode)
.onChange((value) => {
this.mdCustomData.lockedReadingMode = value;
}),
);
}
contentEl.createEl("h4", { text: t("ES_BACKGROUND_HEAD") });
const descDiv = contentEl.createDiv({ cls: "excalidraw-setting-desc" });
descDiv.textContent = t("ES_BACKGROUND_DESC_INFO");
+8 -7
View File
@@ -19,7 +19,7 @@ import {
updateYouTubeStartTime,
} from "src/utils/YoutTubeUtils";
import { EmbeddalbeMDFileCustomDataSettingsComponent } from "./EmbeddableMDFileCustomDataSettingsComponent";
import { isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
import { isWinCTRLorMacCMD, labelCTRL } from "src/utils/modifierkeyHelper";
import { CaptureUpdateAction } from "src/constants/constants";
export type EmbeddableMDCustomProps = {
@@ -32,6 +32,7 @@ export type EmbeddableMDCustomProps = {
borderColor: string;
borderOpacity: number;
filenameVisible: boolean;
lockedReadingMode?: boolean;
};
export class EmbeddableSettings extends Modal {
@@ -66,9 +67,9 @@ export class EmbeddableSettings extends Modal {
this.youtubeStart = getYouTubeStartAt(this.element.link);
}
this.mdCustomData =
element.customData?.mdProps ??
view.plugin.settings.embeddableMarkdownDefaults;
this.mdCustomData = (element.customData?.mdProps ??
view.plugin.settings
.embeddableMarkdownDefaults) as EmbeddableMDCustomProps;
if (!element.customData?.mdProps) {
const bgCM = this.plugin.ea.getCM(element.backgroundColor);
this.mdCustomData.backgroundColor = bgCM.stringHEX({ alpha: false });
@@ -164,14 +165,14 @@ export class EmbeddableSettings extends Modal {
button
.setButtonText(t("PROMPT_BUTTON_CANCEL"))
.setTooltip("ESC")
.onClick(this.close.bind(this)),
.onClick(() => this.close()),
)
.addButton((button) =>
button
.setButtonText(t("PROMPT_BUTTON_OK"))
.setTooltip("CTRL/Opt+Enter")
.setTooltip(labelCTRL() + "Enter")
.setCta()
.onClick(this.applySettings.bind(this)),
.onClick(() => this.applySettings()),
);
const onKeyDown = (ev: KeyboardEvent) => {
+3 -3
View File
@@ -81,7 +81,7 @@ export class ExportDialog extends Modal {
this.theme = getExportTheme(
this.plugin,
this.file,
this.api.getAppState().theme,
this.api.getAppState().theme as string,
);
this.boundingBox = this.ea.getBoundingBox(this.ea.getViewElements());
this.embedScene = shouldEmbedScene(this.plugin, this.file);
@@ -127,7 +127,7 @@ export class ExportDialog extends Modal {
} else {
this.boundingBox = this.ea.getBoundingBox(this.ea.getViewElements());
}
if (this.scaleSetting) {
if (this.scaleSetting !== null) {
this.scaleSetting.setDesc(this.size());
}
}
@@ -140,7 +140,7 @@ export class ExportDialog extends Modal {
this.updateBoundingBox();
}
async onClose() {
onClose() {
this.dirty = this.saveSettings;
}
+13 -7
View File
@@ -2,6 +2,12 @@ import { App, Modal } from "obsidian";
import { clamp } from "@radix-ui/number";
import { mainDocument } from "src/constants/constants";
import { setStyle } from "src/utils/styleUtils";
import {
isInstanceOfHTMLButtonElement,
isInstanceOfHTMLInputElement,
isInstanceOfHTMLSelectElement,
isInstanceOfHTMLTextAreaElement,
} from "src/utils/typechecks";
function getClientPoint(e: PointerEvent | TouchEvent) {
if (e.type.startsWith("touch")) {
@@ -99,9 +105,9 @@ export class FloatingModal extends Modal {
constructor(app: App) {
super(app);
// Initialize event handlers with proper binding
this.pointerDownHandler = this.handlePointerDown.bind(this);
this.pointerMoveHandler = this.handlePointerMove.bind(this);
this.pointerUpHandler = this.handlePointerUp.bind(this);
this.pointerDownHandler = (e) => this.handlePointerDown(e);
this.pointerMoveHandler = (e) => this.handlePointerMove(e);
this.pointerUpHandler = () => this.handlePointerUp();
this.modalKeydownStopHandler = (ev: KeyboardEvent) => ev.stopPropagation();
this.setDimBackground(false);
@@ -112,10 +118,10 @@ export class FloatingModal extends Modal {
event: PointerEvent | TouchEvent,
): boolean {
return Boolean(
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement ||
target instanceof HTMLSelectElement ||
target instanceof HTMLButtonElement ||
isInstanceOfHTMLInputElement(target) ||
isInstanceOfHTMLTextAreaElement(target) ||
isInstanceOfHTMLSelectElement(target) ||
isInstanceOfHTMLButtonElement(target) ||
isPointOnText(event, this.ownerDocument) ||
target.closest(".clickable-icon") ||
// ensure close button never starts drag
+12 -10
View File
@@ -43,19 +43,21 @@ export class ImportSVGDialog extends FuzzySuggestModal<TFile> {
return item.path;
}
async onChooseItem(item: TFile, _: KeyboardEvent): Promise<void> {
onChooseItem(item: TFile, _: KeyboardEvent): void {
if (!item) {
return;
}
const ea = getEA(this.view);
const svg = await this.app.vault.read(item);
if (!svg || svg === "") {
return;
}
ea.importSVG(svg);
ea.addToGroup(ea.getElements().map((el) => el.id));
await ea.addElementsToView(true, true, true, true);
ea.destroy();
void (async () => {
const ea = getEA(this.view);
const svg = await this.app.vault.read(item);
if (!svg || svg === "") {
return;
}
ea.importSVG(svg);
ea.addToGroup(ea.getElements().map((el) => el.id));
await ea.addElementsToView(true, true, true, true);
ea.destroy();
})();
}
onClose(): void {
+6 -4
View File
@@ -54,7 +54,7 @@ export class InsertPDFModal extends Modal {
void this.createForm();
}
async onClose() {
onClose() {
if (this.dirty) {
this.plugin.settings.pdfImportScale = this.importScale;
this.plugin.settings.pdfBorderBox = this.borderBox;
@@ -65,7 +65,7 @@ export class InsertPDFModal extends Modal {
this.plugin.settings.pdfNumRows = this.numRows;
this.plugin.settings.pdfDirection = this.direction;
this.plugin.settings.pdfLockAfterImport = this.lockAfterImport;
await this.plugin.saveSettings();
void this.plugin.saveSettings();
}
if (this.pdfDoc) {
this.pdfDoc.destroy();
@@ -142,7 +142,9 @@ export class InsertPDFModal extends Modal {
const pageRangeArray = pageRange.split("-");
if (pageRangeArray.length === 1) {
const page = parseInt(cleanNonDigits(pageRangeArray[0]));
!isNaN(page) && this.pagesToImport.push(page);
if (!isNaN(page)) {
this.pagesToImport.push(page);
}
} else if (pageRangeArray.length === 2) {
const start = parseInt(cleanNonDigits(pageRangeArray[0]));
const end = parseInt(cleanNonDigits(pageRangeArray[1]));
@@ -239,7 +241,7 @@ export class InsertPDFModal extends Modal {
const setFile = async (file: TFile) => {
if (this.pdfDoc) {
await this.pdfDoc.destroy();
this.pdfDoc.destroy();
}
this.pdfDoc = null;
this.pageDimensionsByPage.clear();
+71 -2
View File
@@ -17,6 +17,75 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
`,
"2.25.0": `
## New
- Imporved ink flow for freedraw pen
- You can now toggle between pressure sensitive and constant mode for the default excalidraw.com freedraw pen. [#11507](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11507), [#11551](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11551)
- Comicbook Callout Editor script available in the Script Libarary
- Added new ExtraBold line width option, and XS font option
## Fixed
- BUG: Double Click to edit from Obsidian in Live preview doesn't work anymore [#2813](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2813)
`,
"2.24.2": `
## Fixed
- High impact regression in 2.24.0: Translations were not loading correctly. 🙏[@Lumintian](${URLs.GITHUB_COM}/Lumintian) [#2809](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2809)
## New
- Added lock reading mode to markdown embeddables. If reading mode is locked, clicking the embeddable will not switch to the editor. This is useful for interacting with todo lists, links, and other interactive elements in the embeddables. Based on feedback from the Sketch Your Mind Community. 🙏[@robb3r](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM}/u/robb3r)
`,
"2.24.1": `
To keep Excalidraw lightweight, improve startup performance, reduce plugin size, and address Obsidian's high-risk code scanner findings, several advanced features have been moved to the new **Excalidraw Extras** companion plugin in 2.24.0.
The first time you use one of these features, Excalidraw will automatically prompt you to install Excalidraw Extras:
- LaTeX formulas (MathJax)
- Mermaid diagrams
- PDF printing
- Direct file system access (files outside your vault)
This change reduces Excalidraw's size to under 5 MB, allowing even Obsidian Sync Basic users to sync the plugin across all devices while keeping the core plugin lighter.
---
This (2.24.1) is an emergency follow-up release.
I had to remove a very helpful convenience feature from Excalidraw Extras management: automatic plugin enable/disable.
The feature was removed because of an unexpected Obsidian code scanner review that VERY negatively impacted Excalidraw's scanner score. The same code passed validation without any issues before the release, then failed when released, with no clear warning or guidance. I cannot continue shipping user-friendly automation when the validation target keeps changing.
I support security and quality checks. However, the current scanner process is difficult to work with due to inconsistent results, limited transparency, and the lack of a clear review or appeal process.
If Excalidraw matters to you, please consider contacting Obsidian and advocating for a more transparent, developer-friendly process:
* Stable and consistent scanner results before release
* Clear, actionable error reporting
* A real and timely review and appeal path for questionable findings
* Support for safe plugin workflows, such as companion-plugin management and asset deployment
## Changed
* Removed automatic enable/disable of Excalidraw Extras from the onboarding flow.
* Excalidraw Extras must now be enabled manually in Community Plugins after installation.
`,
"2.24.0": `
To keep Excalidraw lightweight, improve startup performance, reduce plugin size, and address Obsidian's high-risk code scanner findings, several advanced features have been moved to the new **Excalidraw Extras** companion plugin.
The first time you use one of these features, Excalidraw will automatically prompt you to install Excalidraw Extras:
- LaTeX formulas (MathJax)
- Mermaid diagrams
- PDF printing
- Direct file system access (files outside your vault)
This change reduces Excalidraw's size to under 5 MB, allowing even Obsidian Sync Basic users to sync the plugin across all devices while keeping the core plugin lighter.
## Fixed
- Keep runtime custom pen settings per custom pen index instead of sharing one active pen object. Switching between custom pens restores each pen's last adjusted stroke width, colors, fill style, and roughness. 🙏[@arias007](${URLs.GITHUB_COM}/arias007) [#2801](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2801)
- Insert ANY file: Typing “p” in the search field opens the PDF selection [#2791](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2791)
- Blurry arrows in PNG export when arrows have a text label [#2793](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2793), [#11492](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11492)
`,
"2.23.12": `
## Fixed
- Code scanner error
@@ -29,7 +98,7 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
`,
"2.23.10": `
## Fixed
- 2.23.9 regression: Toolbar sizing issue in desktop and compact UI modes [#2789](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES}/2789)
- 2.23.9 regression: Toolbar sizing issue in desktop and compact UI modes [#2789](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2789)
`,
"2.23.9": `
## New
@@ -40,7 +109,7 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
## Fixed
- Clicking Excalidraw links now correctly jumps to the targeted element, group, or frame when the destination is another Excalidraw drawing, including links chosen through the multi-link picker and links triggered from nested embeds.
- In some cases the image cache did not update when nested drawings were modified
- Horizontal and Vertical arrow lines are not always displayed correctly when exporting to SVG or embedding SVG to a markdown note [#1454](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES}/1454)
- Horizontal and Vertical arrow lines are not always displayed correctly when exporting to SVG or embedding SVG to a markdown note [#1454](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/1454)
- Updated vulnerable package dependency lodash-es and nanoid based on Obsidian code scanner findings.
`,
"2.23.8": `
+7 -7
View File
@@ -72,9 +72,9 @@ export class PenSettingsModal extends Modal {
void this.createForm();
}
async onClose() {
onClose() {
if (this.dirty) {
await this.plugin.saveSettings();
void this.plugin.saveSettings();
getExcalidrawViews(this.app, true).forEach((excalidrawView) =>
excalidrawView.updatePinnedCustomPens(),
);
@@ -617,7 +617,7 @@ export class PenSettingsModal extends Modal {
.setLimits(-1, 1, 0.05)
.setValue(ps.penOptions.options.thinning)
.onChange((value) => {
this.dirty;
this.dirty = true;
tSetting.setName(fragWithHTML(`Thinnning <b>${value}</b>`));
ps.penOptions.options.thinning = value;
}),
@@ -633,7 +633,7 @@ export class PenSettingsModal extends Modal {
.setLimits(0, 1, 0.05)
.setValue(ps.penOptions.options.smoothing)
.onChange((value) => {
this.dirty;
this.dirty = true;
sSetting.setName(fragWithHTML(`Smoothing <b>${value}</b>`));
ps.penOptions.options.smoothing = value;
}),
@@ -649,7 +649,7 @@ export class PenSettingsModal extends Modal {
.setLimits(0, 1, 0.05)
.setValue(ps.penOptions.options.streamline)
.onChange((value) => {
this.dirty;
this.dirty = true;
slSetting.setName(fragWithHTML(`Streamline <b>${value}</b>`));
ps.penOptions.options.streamline = value;
}),
@@ -739,7 +739,7 @@ export class PenSettingsModal extends Modal {
: ps.penOptions.options.start.taper,
)
.onChange((value) => {
this.dirty;
this.dirty = true;
ps.penOptions.options.start.taper = value === 151 ? true : value;
stSetting.setName(
fragWithHTML(
@@ -797,7 +797,7 @@ export class PenSettingsModal extends Modal {
: ps.penOptions.options.end.taper,
)
.onChange((value) => {
this.dirty;
this.dirty = true;
ps.penOptions.options.end.taper = value === 151 ? true : value;
etSetting.setName(
fragWithHTML(
+37 -22
View File
@@ -11,7 +11,7 @@ import {
} from "obsidian";
import ExcalidrawView from "../../view/ExcalidrawView";
import ExcalidrawPlugin from "../../core/main";
import { escapeRegExp, sleep } from "../../utils/utils";
import { escapeRegExp } from "../../utils/utils";
import { getLeaf, openLeaf } from "../../utils/obsidianUtils";
import { createOrOverwriteFile } from "src/utils/fileUtils";
import { KeyEvent, isWinCTRLorMacCMD } from "src/utils/modifierkeyHelper";
@@ -107,7 +107,6 @@ export class Prompt extends Modal {
export class LaTexPrompt extends FloatingModal {
public waitForClose: Promise<string>;
private promptEl: HTMLInputElement;
private resolvePromise: (input: string) => void;
private rejectPromise: (reason?: string) => void;
private editorView: EditorView;
@@ -144,11 +143,20 @@ export class LaTexPrompt extends FloatingModal {
);
}
public static Prompt(
public static async Prompt(
plugin: ExcalidrawPlugin,
app: App,
prompt_text?: string,
default_value?: string,
): Promise<string> {
const mathjaxAPI = await plugin.extrasGateway.getMathJax();
if (!mathjaxAPI) {
return Promise.reject(
new Error("MathJax is not available or activation was cancelled"),
);
}
const latexprompt = new this(app, prompt_text, default_value);
return latexprompt.waitForClose;
@@ -210,7 +218,7 @@ export class LaTexPrompt extends FloatingModal {
this.createButton(
actionButtonContainer,
"",
this.submitCallback.bind(this),
() => this.submitCallback(),
t("PROMPT_BUTTON_OK") ?? "",
undefined,
"check",
@@ -220,7 +228,7 @@ export class LaTexPrompt extends FloatingModal {
this.createButton(
actionButtonContainer,
"",
this.cancelCallback.bind(this),
() => this.cancelCallback(),
t("PROMPT_BUTTON_CANCEL"),
undefined,
"x",
@@ -268,8 +276,8 @@ export class LaTexPrompt extends FloatingModal {
this.close();
}
async onOpen(): Promise<void> {
await super.onOpen();
onOpen(): void {
super.onOpen();
this.editorView.focus();
}
@@ -511,7 +519,7 @@ export class GenericInputPrompt extends Modal {
buttonBarContainer.createDiv();
if (this.buttons && this.buttons.length > 0) {
let b = null;
let b: ButtonComponent = null;
for (const button of this.buttons) {
const btn = new ButtonComponent(actionButtonContainer);
setStyle(btn.buttonEl, {
@@ -520,10 +528,17 @@ export class GenericInputPrompt extends Modal {
if (button.tooltip) {
btn.setTooltip(button.tooltip);
}
button.iconId
? btn.setIcon(button.iconId)
: btn.setButtonText(button.caption);
button.tooltip && btn.setTooltip(button.tooltip);
if (button.iconId) {
btn.setIcon(button.iconId);
} else {
btn.setButtonText(button.caption);
}
if (button.tooltip) {
btn.setTooltip(button.tooltip);
}
btn.onClick(() => {
const res = button.action(this.input);
if (res) {
@@ -533,7 +548,7 @@ export class GenericInputPrompt extends Modal {
});
b = b ?? btn;
}
if (b) {
if (b !== null) {
b.setCta();
setStyle(b.buttonEl, {
marginRight: "0",
@@ -544,7 +559,7 @@ export class GenericInputPrompt extends Modal {
this.createButton(
actionButtonContainer,
"",
this.submitClickCallback.bind(this),
() => this.submitClickCallback(),
t("PROMPT_BUTTON_OK") ?? "",
"5px",
"check",
@@ -558,7 +573,7 @@ export class GenericInputPrompt extends Modal {
this.createButton(
actionButtonContainer,
"",
this.cancelClickCallback.bind(this),
() => this.cancelClickCallback(),
t("PROMPT_BUTTON_CANCEL"),
"5px",
"x",
@@ -576,7 +591,7 @@ export class GenericInputPrompt extends Modal {
this.createButton(
editorButtonContainer,
"",
this.delBtnClickCallback.bind(this),
() => this.delBtnClickCallback(),
"Delete",
"5px",
"delete",
@@ -592,7 +607,7 @@ export class GenericInputPrompt extends Modal {
this.createButton(
editorButtonContainer,
"",
this.specialCharsBtnClickCallback.bind(this),
(evt) => this.specialCharsBtnClickCallback(evt),
t("PROMPT_BUTTON_SPECIAL_CHARS"),
"5px",
"at-sign",
@@ -601,7 +616,7 @@ export class GenericInputPrompt extends Modal {
this.createButton(
editorButtonContainer,
"",
this.linkBtnClickCallback.bind(this),
() => this.linkBtnClickCallback(),
t("PROMPT_BUTTON_INSERT_LINK"),
"5px",
"link",
@@ -610,7 +625,7 @@ export class GenericInputPrompt extends Modal {
this.createButton(
editorButtonContainer,
"",
this.uppercaseBtnClickCallback.bind(this),
() => this.uppercaseBtnClickCallback(),
t("PROMPT_BUTTON_UPPERCASE"),
"5px",
"arrow-big-up",
@@ -824,7 +839,7 @@ export class GenericInputPrompt extends Modal {
}, 10);
};
async onOpen() {
onOpen() {
super.onOpen();
this.modalEl.classList.add("excalidraw-modal");
this.containerEl.classList.add("excalidraw-modal");
@@ -1335,8 +1350,8 @@ export class MultiOptionConfirmationPrompt<T = boolean | null> extends Modal {
return button;
}
async onOpen() {
await super.onOpen();
onOpen() {
super.onOpen();
const defaultButton =
this.ctaButtonEl ?? this.contentEl.querySelector("button");
// Obsidian modal open may apply its own autofocus after onOpen; defer to enforce default keyboard action.
+1 -1
View File
@@ -105,7 +105,7 @@ export class PublishOutOfDateFilesDialog extends Modal {
super(plugin.app);
}
async onClose() {}
onClose() {}
onOpen() {
this.containerEl.classList.add("excalidraw-release");
+7 -6
View File
@@ -1,14 +1,13 @@
import { App, MarkdownRenderer, Modal } from "obsidian";
import ExcalidrawPlugin from "../../core/main";
import { App, Component, MarkdownRenderer, Modal } from "obsidian";
import { Rank, SwordColors } from "src/constants/actionIcons";
import { convertSVGStringToElement } from "src/utils/utils";
import { URLs } from "src/constants/safeUrls";
import { setStyle } from "src/utils/styleUtils";
export class RankMessage extends Modal {
private renderComponent: Component;
constructor(
app: App,
private plugin: ExcalidrawPlugin,
private filecount: number,
private rank: Rank,
private color: string,
@@ -19,15 +18,17 @@ export class RankMessage extends Modal {
}
onOpen(): void {
this.renderComponent = new Component();
this.renderComponent.load();
//this.contentEl.classList.add("excalidraw-release");
this.containerEl.classList.add("excalidraw-release");
this.titleEl.setText("Congratulations, glorious knight!");
void this.createForm();
}
async onClose() {
onClose() {
this.contentEl.empty();
this.plugin = null;
this.renderComponent.unload();
}
async createForm() {
@@ -45,7 +46,7 @@ export class RankMessage extends Modal {
`You have ${this.filecount} Excalidraw drawings in your Vault earning you a new rank: **${this.rank}**! You've ascended to **${title}**!\n\nI've spent the past 3+ years building this plugin. If you appreciate my work, consider supporting me on [Ko-Fi](${URLs.KO_FI_COM_ZSOLT}) or join the next [Visual Thinking Workshop](${URLs.VISUAL_THINKING_WORKSHOP_COM}) cohort.`,
this.contentEl,
"",
this.plugin,
this.renderComponent,
);
this.contentEl.createEl("p", { text: "" }, (el) => {
+14 -8
View File
@@ -1,4 +1,4 @@
import { App, MarkdownRenderer, Modal } from "obsidian";
import { App, Component, MarkdownRenderer, Modal } from "obsidian";
import { isVersionNewerThanOther } from "src/utils/utils";
import ExcalidrawPlugin from "../../core/main";
import { RELEASE_NOTES } from "./Messages";
@@ -17,6 +17,7 @@ export class ReleaseNotes extends Modal {
private plugin: ExcalidrawPlugin;
private options: ReleaseNotesOptions;
private version: string;
private renderComponent: Component;
constructor(
app: App,
@@ -31,6 +32,8 @@ export class ReleaseNotes extends Modal {
}
onOpen(): void {
this.renderComponent = new Component();
this.renderComponent.load();
const { containerEl, titleEl, headerEl } = this;
//this.contentEl.classList.add("excalidraw-release");
containerEl.classList.add("excalidraw-release");
@@ -44,16 +47,19 @@ export class ReleaseNotes extends Modal {
} // Disable pointer events on header to allow clicks through
}
async onClose() {
onClose() {
this.contentEl.empty();
this.renderComponent.unload();
if (this.options.persistVersion === false) {
return;
}
await this.plugin.loadSettings();
if (this.plugin.settings.previousRelease !== PLUGIN_VERSION) {
this.plugin.settings.previousRelease = PLUGIN_VERSION;
await this.plugin.saveSettings();
}
void (async () => {
await this.plugin.loadSettings();
if (this.plugin.settings.previousRelease !== PLUGIN_VERSION) {
this.plugin.settings.previousRelease = PLUGIN_VERSION;
await this.plugin.saveSettings();
}
})();
}
async createForm() {
@@ -79,7 +85,7 @@ export class ReleaseNotes extends Modal {
message,
this.contentEl,
"",
this.plugin,
this.renderComponent,
);
this.contentEl.createEl("p", { text: "" }, (el) => {
+37 -33
View File
@@ -1,23 +1,27 @@
import { MarkdownRenderer, Modal, Notice, request } from "obsidian";
import { Component, MarkdownRenderer, Modal, Notice, request } from "obsidian";
import ExcalidrawPlugin from "../../core/main";
import { errorlog } from "../../utils/utils";
import { log } from "src/utils/debugHelper";
import { ContentSearcher } from "../components/ContentSearcher";
import { URLs } from "src/constants/safeUrls";
import { mainDocument } from "src/constants/constants";
import { t } from "src/lang/helpers";
const URL =
URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_INDEX_NEW_MD;
export class ScriptInstallPrompt extends Modal {
private contentDiv: HTMLDivElement;
private renderComponent: Component;
constructor(private plugin: ExcalidrawPlugin) {
super(plugin.app);
// this.titleEl.setText(t("INSTAL_MODAL_TITLE"));
}
async onOpen(): Promise<void> {
onOpen(): void {
this.renderComponent = new Component();
this.renderComponent.load();
this.contentEl.classList.add("excalidraw-scriptengine-install");
this.contentDiv = mainDocument.createElement("div");
this.contentEl.appendChild(this.contentDiv);
@@ -25,42 +29,42 @@ export class ScriptInstallPrompt extends Modal {
new ContentSearcher(this.contentDiv);
this.containerEl.classList.add("excalidraw-scriptengine-install");
try {
const source = await request({ url: URL });
if (!source) {
new Notice(
"Error opening the Excalidraw Script Store page. " +
"Please double check that you can access the website. " +
"I've logged the link in developer console (press CTRL+SHIFT+i)",
5000,
void (async () => {
try {
const source = await request({ url: URL });
if (!source) {
new Notice(t("SCRIPT_INSTALL_PROMPT_FETCH_ERROR"), 5000);
log(URL);
this.close();
return;
}
await MarkdownRenderer.render(
this.plugin.app,
source,
this.contentDiv,
"",
this.renderComponent,
);
log(URL);
this.close();
return;
}
await MarkdownRenderer.render(
this.plugin.app,
source,
this.contentDiv,
"",
this.plugin,
);
this.contentDiv
.querySelectorAll("h1[data-heading],h2[data-heading],h3[data-heading]")
.forEach((el) => {
el.setAttribute("id", el.getAttribute("data-heading"));
this.contentDiv
.querySelectorAll(
"h1[data-heading],h2[data-heading],h3[data-heading]",
)
.forEach((el) => {
el.setAttribute("id", el.getAttribute("data-heading"));
});
this.contentDiv.querySelectorAll("a.internal-link").forEach((el) => {
el.removeAttribute("target");
});
this.contentDiv.querySelectorAll("a.internal-link").forEach((el) => {
el.removeAttribute("target");
});
} catch (e) {
errorlog({ where: "ScriptInstallPrompt.onOpen", error: e });
new Notice("Could not open ScriptEngine repository");
this.close();
}
} catch (e) {
errorlog({ where: "ScriptInstallPrompt.onOpen", error: e as unknown });
new Notice(t("SCRIPT_INSTALL_PROMPT_OPEN_ERROR"));
this.close();
}
})();
}
onClose(): void {
this.contentEl.empty();
this.renderComponent.unload();
}
}
+2 -2
View File
@@ -14,9 +14,9 @@ export class UIModeSettings extends Modal {
void this.createForm();
}
async onClose() {
onClose() {
if (this.isDirty) {
await this.plugin.saveSettings();
void this.plugin.saveSettings();
}
this.plugin = null;
}
@@ -313,20 +313,6 @@ export class UniversalInsertFileModal extends Modal {
return;
}
return;
case "i":
if (isVisible(actionImage)) {
actionImage.buttonEl.click();
}
return;
case "p":
if (isVisible(actionPDF)) {
actionPDF.buttonEl.click();
}
return;
case "f":
if (isVisible(actionIFrame)) {
actionIFrame.buttonEl.click();
}
}
}),
);
+7 -4
View File
@@ -95,15 +95,18 @@ export class VersionMismatchPrompt extends Modal {
redownloadBtn.addClass("mod-cta");
}
async onClose() {
onClose() {
super.onClose();
if (this.isDirty) {
await this.plugin.saveSettings();
void this.plugin.saveSettings();
}
if (!this.resolvePromise) {
return;
}
if (!this.resolved) {
this.resolvePromise && this.resolvePromise(false);
this.resolvePromise(false);
} else {
this.resolvePromise && this.resolvePromise(true);
this.resolvePromise(true);
}
}
}
+30 -14
View File
@@ -6,7 +6,7 @@ import {
FileId,
} from "@zsviczian/excalidraw/types/element/src/types";
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import { App, MarkdownRenderer, Notice, TFile } from "obsidian";
import { App, Component, MarkdownRenderer, Notice, TFile } from "obsidian";
import {
DEFAULT_MD_EMBED_CSS,
fileid,
@@ -70,6 +70,11 @@ import {
import { ExportSettings } from "src/types/exportUtilTypes";
import { setStyleText } from "src/utils/htmlUtils";
import { hideElement, setStyle } from "src/utils/styleUtils";
import {
isInstanceOfHTMLImageElement,
isInstanceOfSVGElement,
} from "src/utils/typechecks";
import { strictArrayBuffer } from "src/utils/obsidianUtils";
//An ugly workaround for the following situation.
//File A is a markdown file that has an embedded Excalidraw file B
@@ -145,7 +150,7 @@ const replaceSVGColors = (
// Modify the fill and stroke attributes of child nodes
const childNodes = (node: ChildNode) => {
if (node instanceof SVGElement) {
if (isInstanceOfSVGElement(node)) {
const oldFill = node.getAttribute("fill")?.toLocaleLowerCase();
const oldStroke = node.getAttribute("stroke")?.toLocaleLowerCase();
@@ -1334,12 +1339,13 @@ export class EmbeddedFilesLoader {
});
});
const base64 = await blobToBase64(blob);
shouldUseCache &&
if (shouldUseCache) {
getImageCache().addImageToCache(cacheKey, "", blob, {
renderScale: requestedScale,
size: { width, height },
pdfPageViewProps: viewProps,
});
}
const result: [DataURL, Size, PDFPageViewProps, number, boolean] = [
`data:image/png;base64,${base64}` as DataURL,
{ width, height },
@@ -1412,10 +1418,11 @@ export class EmbeddedFilesLoader {
case "":
fontDef = "";
break;
default:
default: {
const font = await getFontDataURL(plugin.app, fontName, file.path);
fontDef = font.fontDef;
fontName = font.fontName;
}
}
if (fileCache?.frontmatter && fileCache.frontmatter.banner !== null) {
@@ -1490,14 +1497,17 @@ export class EmbeddedFilesLoader {
color: fontColor && fontColor !== "" ? fontColor : "initial",
});
const renderComponent = new Component();
renderComponent.load();
//await MarkdownRenderer.renderMarkdown(text, mdDIV, file.path, plugin);
await MarkdownRenderer.render(
this.plugin.app,
text,
mdDIV,
file.path,
this.plugin,
renderComponent,
);
renderComponent.unload();
mdDIV
.querySelectorAll(":scope > *[class^='frontmatter']")
@@ -1556,9 +1566,10 @@ export class EmbeddedFilesLoader {
const elementStyle = el.style;
const computedStyle = window.getComputedStyle(el);
let style = "";
for (const prop in elementStyle) {
if (elementStyle.hasOwnProperty(prop)) {
style += `${prop}: ${computedStyle[prop]};`;
for (const [prop] of Object.entries(elementStyle)) {
if (Object.hasOwn(elementStyle ?? {}, prop)) {
const value = computedStyle.getPropertyValue(prop);
style += `${prop}: ${value};`;
}
}
el.setAttribute("style", style);
@@ -1603,7 +1614,7 @@ export class EmbeddedFilesLoader {
}
if (hasSVGwithBitmap && this.isDark) {
imageList.forEach((img) => {
if (img instanceof HTMLImageElement) {
if (isInstanceOfHTMLImageElement(img)) {
setStyle(img, { filter: THEME_FILTER });
}
});
@@ -1661,16 +1672,21 @@ export const generateIdFromFile = async (
// Hash the combined data (file and key, if provided)
// Ensure we pass an ArrayBuffer (not ArrayBufferLike) to subtle.digest
const buffer: ArrayBuffer = dataToHash.buffer.slice(
dataToHash.byteOffset,
dataToHash.byteOffset + dataToHash.byteLength,
) as ArrayBuffer;
const buffer = strictArrayBuffer(
dataToHash.buffer.slice(
dataToHash.byteOffset,
dataToHash.byteOffset + dataToHash.byteLength,
),
);
const hashBuffer = await window.crypto.subtle.digest("SHA-1", buffer);
id = Array.from(new Uint8Array(hashBuffer))
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("") as FileId;
} catch (error) {
errorlog({ where: "EmbeddedFileLoader.generateIdFromFile", error });
errorlog({
where: "EmbeddedFileLoader.generateIdFromFile",
error: error as unknown,
});
id = fileid() as FileId;
}
return id;
+14 -5
View File
@@ -15,6 +15,7 @@ import {
RoundnessType,
ExcalidrawFrameElement,
ExcalidrawTextContainer,
ElementsMap,
} from "@zsviczian/excalidraw/types/element/src/types";
import { ColorMap, MimeType } from "../types/embeddedFileLoaderTypes";
import {
@@ -159,6 +160,7 @@ import {
ensureActiveScriptSettingsObject,
errorMessage,
filterColorMap,
getAppStateStrokeWidthEntry,
getEmbeddedFileForImageElment,
getLineBox,
getTemplate,
@@ -204,6 +206,7 @@ import { getAspectRatio } from "src/utils/YoutTubeUtils";
import { getPDFCropRect } from "src/utils/PDFUtils";
import { CaptureUpdateActionType } from "@zsviczian/excalidraw/types/element/src";
import { URL_REGISTRY } from "src/constants/safeUrls";
import { FREEDRAW_STROKE_WIDTH, StrokeWidthKey } from "@zsviczian/excalidraw/types/common/src";
type ExcalidrawAutomateHelpTarget = ((...args: unknown[]) => unknown) | string;
@@ -1445,8 +1448,10 @@ export class ExcalidrawAutomate {
this.style.backgroundColor,
currentItemFillStyle:
templateAppstate.currentItemFillStyle ?? this.style.fillStyle,
currentItemStrokeWidth:
...getAppStateStrokeWidthEntry (
templateAppstate.currentItemStrokeWidthKey,
templateAppstate.currentItemStrokeWidth ?? this.style.strokeWidth,
),
currentItemStrokeStyle:
templateAppstate.currentItemStrokeStyle ?? this.style.strokeStyle,
currentItemRoughness:
@@ -2444,7 +2449,7 @@ export class ExcalidrawAutomate {
const dimensions = refreshTextDimensions(
textElement,
container,
arrayToMap(this.getElements()),
arrayToMap(this.getElements()) as ElementsMap,
originalText,
);
@@ -3663,8 +3668,8 @@ export class ExcalidrawAutomate {
* @param {ExcalidrawElement[]} [scene.elements] - Array of elements in the scene.
* @param {AppState} [scene.appState] - The app state of the scene.
* @param {BinaryFiles} [scene.files] - The files in the scene.
* @param {boolean} [scene.commitToHistory] - Whether to commit the scene to history. @deprecated Use scene.storageOption instead
* @param {"capture" | "none" | "update"} [scene.storeAction] - The store action for the scene. @deprecated Use scene.storageOption instead
* @param {boolean} [scene.commitToHistory] - Deprecated: Use scene.storageOption instead.
* @param {"capture" | "none" | "update"} [scene.storeAction] - Deprecated: Use scene.storageOption instead
* @param {"IMMEDIATELY" | "NEVER" | "EVENTUALLY"} [scene.captureUpdate] - The capture update action for the scene.
* @param {boolean} [restore=false] - Whether to restore legacy elements in the scene.
*/
@@ -4159,7 +4164,7 @@ export class ExcalidrawAutomate {
* @returns {ExcalidrawElement[][]} Array of arrays of grouped elements.
*/
getMaximumGroups(elements: ExcalidrawElement[]): ExcalidrawElement[][] {
return getMaximumGroups(elements, arrayToMap(elements));
return getMaximumGroups(elements, arrayToMap(elements) as ElementsMap);
}
/**
@@ -4837,6 +4842,10 @@ export class ExcalidrawAutomate {
getPolyBool(): typeof PolyBool {
const defaultEpsilon = 0.0000000001;
PolyBool.epsilon(defaultEpsilon);
if ("buildLog" in PolyBool) {
PolyBool.buildLog(false);
}
return PolyBool;
}
+40 -22
View File
@@ -40,6 +40,7 @@ import {
import { isObsidianThemeDark } from "../utils/obsidianUtils";
import { cleanBlockRef, cleanSectionHeading } from "../utils/pathUtils";
import {
ElementsMap,
ExcalidrawElement,
ExcalidrawImageElement,
ExcalidrawTextElement,
@@ -65,6 +66,7 @@ import { t } from "../lang/helpers";
import { displayFontMessage } from "../utils/excalidrawViewUtils";
import { getPDFRect } from "../utils/PDFUtils";
import { URLs } from "src/constants/safeUrls";
import { errorlog } from "src/utils/coreUtils";
type SceneDataWithFiles = SceneData & { files: BinaryFiles };
@@ -268,7 +270,7 @@ export function getJSON(data: string): { scene: string; pos: number } {
if (parts.value && parts.value.length > 1) {
const result = parts.value[2];
return {
scene: result.substr(0, result.lastIndexOf("}") + 1),
scene: result.substring(0, result.lastIndexOf("}") + 1),
pos: parts.value.index,
}; //this is a workaround in case sync merges two files together and one version is still an old version without the ```codeblock
}
@@ -568,16 +570,22 @@ export class ExcalidrawData {
URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG,
)[1] ?? "1.8.16";
const elements = this.scene.elements;
const elements = this.scene.elements as Mutable<
ExcalidrawElement & { boundElementIds?: string[] }
>[];
for (const el of elements) {
if (el.type === "iframe" && !el.customData) {
//@ts-ignore -- retyping in ExcalidrawData is possible, this is not the live inmutable object
el.type = "embeddable";
}
if (el.boundElements) {
const map = new Map<string, string>();
const map = new Map<string, "text" | "arrow">();
let alreadyHasText: boolean = false;
el.boundElements.forEach((item: { id: string; type: string }) => {
if (item.type !== "text" && item.type !== "arrow") {
return;
}
if (item.type === "text") {
if (!alreadyHasText) {
map.set(item.id, item.type);
@@ -588,7 +596,9 @@ export class ExcalidrawData {
);
if (elementToClean) {
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/1600
elementToClean.containerId = null;
if (elementToClean.type === "text") {
elementToClean.containerId = null;
}
}
}
} else {
@@ -631,27 +641,31 @@ export class ExcalidrawData {
if (el.y === null) {
el.y = 0;
}
/* FixedPointBinding type no longer has focus property. restoreElemenets should take care of this
if (el.startBinding?.focus === null) {
el.startBinding.focus = 0;
}
if (el.endBinding?.focus === null) {
el.endBinding.focus = 0;
}
*/
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/497
if (el.fontSize === null) {
if (el.type === "text" && el.fontSize === null) {
el.fontSize = 20;
}
if (el.type === "text" && !el.hasOwnProperty("autoResize")) {
if (el.type === "text" && !Object.hasOwn(el ?? {}, "autoResize")) {
el.autoResize = true;
}
if (el.type === "text" && !el.hasOwnProperty("lineHeight")) {
el.lineHeight = getLineHeight(el.fontFamily);
if (el.type === "text" && !Object.hasOwn(el ?? {}, "lineHeight")) {
el.lineHeight = getLineHeight(el.fontFamily) as number & {
_brand: "unitlessLineHeight";
};
}
if (el.type === "image" && !el.hasOwnProperty("roundness")) {
if (el.type === "image" && !Object.hasOwn(el ?? {}, "roundness")) {
el.roundness = null;
}
}
@@ -686,7 +700,7 @@ export class ExcalidrawData {
container.id === textEl.containerId,
)[0];
const boundEl = container.boundElements.filter(
(boundEl: { id: string; type: string }) =>
(boundEl: { id: string; type: "text" | "arrow" }) =>
!(
boundEl.type === "text" &&
!elements.some(
@@ -694,15 +708,17 @@ export class ExcalidrawData {
)
),
);
container.boundElements = [{ id: textEl.id, type: "text" }].concat(
boundEl,
);
} catch (error) {
console.log(
"unexpected error in initializeNonInitializedFields",
this.initializeNonInitializedFields,
error,
);
container.boundElements = [
{ id: textEl.id, type: "text" as "text" | "arrow" },
].concat(boundEl);
} catch (e) {
errorlog({
message: "unexpected error in initializeNonInitializedFields",
context: this.initializeNonInitializedFields.bind(
this,
) as unknown,
error: e as unknown,
});
}
},
);
@@ -884,7 +900,7 @@ export class ExcalidrawData {
}
//girdSize, gridStep, previousGridSize, gridModeEnabled migration
if (this.scene.appState.hasOwnProperty("previousGridSize")) {
if (Object.hasOwn(this.scene.appState ?? {}, "previousGridSize")) {
//if previousGridSize was present this is legacy data
if (this.scene.appState.gridSize === null) {
this.scene.appState.gridSize = this.scene.appState.previousGridSize;
@@ -895,7 +911,9 @@ export class ExcalidrawData {
delete this.scene.appState.previousGridSize;
}
if (this.scene.appState?.gridColor?.hasOwnProperty("MajorGridFrequency")) {
if (
Object.hasOwn(this.scene.appState?.gridColor ?? {}, "MajorGridFrequency")
) {
//if this is present, this is legacy data
if (this.scene.appState.gridColor.MajorGridFrequency > 1) {
this.scene.gridStep = this.scene.appState.gridColor.MajorGridFrequency;
@@ -1173,7 +1191,7 @@ export class ExcalidrawData {
private async updateSceneTextElements() {
//update text in scene based on textElements Map
//first get scene text elements
const elementsMap = arrayToMap(this.scene.elements);
const elementsMap = arrayToMap(this.scene.elements) as ElementsMap;
const texts = this.scene.elements?.filter(
(el: ExcalidrawElement) => el.type === "text" && !el.isDeleted,
) as Mutable<ExcalidrawTextElement>[];
+15 -7
View File
@@ -1,7 +1,7 @@
import { App, Notice, TFile } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
import { PDFPageViewProps, Size } from "src/types/embeddedFileLoaderTypes";
import { convertSVGStringToElement } from "../utils/utils";
import { convertSVGStringToElement, errorlog } from "../utils/utils";
import { FILENAMEPARTS, PreviewImageType } from "../types/utilTypes";
import { hasExcalidrawEmbeddedImagesTreeChanged } from "../utils/fileUtils";
import { EXCALIDRAW_PLUGIN } from "src/constants/constants";
@@ -274,14 +274,18 @@ class ImageCache {
transaction.commit();
resolve();
})
.catch((error) => reject(error));
.catch((error) => reject(error as Error));
}
};
request.onerror = () => {
const error = request.error;
console.log(error);
const errorMsg = `Failed to purge invalid files from IndexedDB. Error: ${error.message}`;
errorlog({
where: "purgeInvalideCacheFiles",
error: error,
message: errorMsg,
});
reject(new Error(errorMsg));
};
});
@@ -319,14 +323,18 @@ class ImageCache {
transaction.commit();
resolve();
})
.catch((error) => reject(error));
.catch((error) => reject(error as Error));
}
};
request.onerror = () => {
const error = request.error;
const errorMsg = `Failed to purge invalid backup files from IndexedDB. Error: ${error.message}`;
console.log(error);
errorlog({
where: "purgeInvalidBackupFiles",
error: error,
message: errorMsg,
});
reject(new Error(errorMsg));
};
});
@@ -400,7 +408,7 @@ class ImageCache {
this.getCacheData(key),
new Promise<undefined>((_, reject) =>
window.setTimeout(() => {
reject(undefined);
reject(new Error("Timeout while retrieving cache data"));
}, 100),
),
]);
@@ -442,7 +450,7 @@ class ImageCache {
} catch (error) {
console.error(
"unexpected error in getResolvedCacheData",
this.getResolvedCacheData,
this.getResolvedCacheData.bind(this),
error,
);
return undefined;
+10 -2
View File
@@ -4,6 +4,7 @@ import ExcalidrawView from "../view/ExcalidrawView";
import { FileData, MimeType } from "src/types/embeddedFileLoaderTypes";
import { FileId } from "@zsviczian/excalidraw/types/element/src/types";
import ExcalidrawPlugin from "src/core/main";
import type { ExcalidrawExtrasAPI } from "@zsviczian/excalidraw-extras-api";
export const updateEquation = async (
equation: string,
@@ -58,13 +59,20 @@ export async function tex2dataURL(
}
// 3. Hand the request off to the cleanly isolated Extras plugin
return (await mathjaxAPI.tex2dataURL(tex, scale, preambleStr)) as any;
return (await mathjaxAPI.tex2dataURL(tex, scale, preambleStr)) as {
mimeType: MimeType;
fileId: FileId;
dataURL: DataURL;
created: number;
size: { height: number; width: number };
};
}
export const clearMathJaxVariables = (plugin: ExcalidrawPlugin) => {
// Try to access without prompting the user.
// If the plugin is disabled, we don't need to clear variables anyway.
const api = (plugin.app as any).plugins.plugins["excalidraw-extras"]?.api;
const api = plugin.app.plugins.plugins["excalidraw-extras"]
?.api as ExcalidrawExtrasAPI;
if (api?.mathjax) {
api.mathjax.clearMathJaxVariables();
}
+5 -1
View File
@@ -425,7 +425,11 @@ export class ScriptEngine {
instructions,
);
} catch (error) {
console.error("unexpected error in suggester", this.suggester, error);
console.error(
"unexpected error in suggester",
this.suggester.bind(this),
error,
);
return undefined;
}
}
+35 -32
View File
@@ -14,7 +14,6 @@ import {
import { KeyBlocker } from "src/types/excalidrawAutomateTypes";
import { t } from "src/lang/helpers";
import { nanoid } from "src/constants/constants";
import { sleep } from "src/utils/utils";
import { getEA } from "src/core";
import { setStyle } from "src/utils/styleUtils";
@@ -213,7 +212,7 @@ export class InlineLinkSuggester
return input;
}
async onInputChanged(): Promise<void> {
onInputChanged(): void {
const inputStr = this.modifyInput(this.inputEl.value);
this.caretPos = this.inputEl.selectionStart ?? inputStr.length;
@@ -249,21 +248,23 @@ export class InlineLinkSuggester
return;
}
if (this.mode === "heading") {
await this.loadHeadings(this.activeFile);
} else if (this.mode === "block") {
await this.loadParagraphs(this.activeFile);
} else if (this.mode === "frame" || this.mode === "clippedframe") {
await this.loadFrames(this.activeFile, this.mode);
} else {
this.headingItems = [];
this.paragraphItems = [];
this.frameItems = [];
}
void (async () => {
if (this.mode === "heading") {
await this.loadHeadings(this.activeFile);
} else if (this.mode === "block") {
await this.loadParagraphs(this.activeFile);
} else if (this.mode === "frame" || this.mode === "clippedframe") {
await this.loadFrames(this.activeFile, this.mode);
} else {
this.headingItems = [];
this.paragraphItems = [];
this.frameItems = [];
}
this.tagItems = [];
this.block = true;
super.onInputChanged();
this.tagItems = [];
this.block = true;
super.onInputChanged();
})();
return;
}
@@ -287,7 +288,7 @@ export class InlineLinkSuggester
this.tagItems = this.getTagSuggestions();
this.block = true;
await super.onInputChanged();
super.onInputChanged();
}
private getTagSuggestions(): TagSuggestion[] {
@@ -386,7 +387,7 @@ export class InlineLinkSuggester
return item.path + (item.alias ? `|${item.alias}` : "");
}
async onChooseItem(item: InlineSuggestion | undefined): Promise<void> {
onChooseItem(item: InlineSuggestion | undefined): void {
if (!item) {
return;
}
@@ -409,18 +410,20 @@ export class InlineLinkSuggester
}
if (this.isParagraph(item)) {
const id = await this.ensureParagraphHasId(item);
if (!id) {
return;
}
const linktext = this.app.metadataCache.fileToLinktext(
item.file,
this.getSourcePath() ?? "",
true,
);
const aliasSuffix =
this.activeAlias !== null ? `|${this.activeAlias}` : "";
this.insertLink(`[[${linktext}#^${id}${aliasSuffix}]]`);
void (async () => {
const id = await this.ensureParagraphHasId(item);
if (!id) {
return;
}
const linktext = this.app.metadataCache.fileToLinktext(
item.file,
this.getSourcePath() ?? "",
true,
);
const aliasSuffix =
this.activeAlias !== null ? `|${this.activeAlias}` : "";
this.insertLink(`[[${linktext}#^${id}${aliasSuffix}]]`);
})();
return;
}
@@ -442,13 +445,13 @@ export class InlineLinkSuggester
this.insertLink(linkString);
}
async selectSuggestion(
selectSuggestion(
value: FuzzyMatch<InlineSuggestion>,
evt: MouseEvent | KeyboardEvent,
) {
evt?.preventDefault?.();
evt?.stopPropagation?.();
await this.onChooseItem(value?.item);
void this.onChooseItem(value?.item);
}
open(): void {
+6 -4
View File
@@ -3,6 +3,7 @@ import { escapeRegExp } from "../../utils/utils";
import { htmlToMarkdown, Notice, setIcon } from "obsidian";
import { mainDocument } from "src/constants/constants";
import { setStyle } from "src/utils/styleUtils";
import { isInstanceOfHTMLElement } from "src/utils/typechecks";
export class ContentSearcher {
private contentDiv: HTMLElement;
@@ -115,7 +116,7 @@ export class ContentSearcher {
const childNodes = Array.from(exportContent.childNodes);
const startIndex = childNodes.findIndex(
(node) => node instanceof HTMLElement && node.tagName === "HR",
(node) => isInstanceOfHTMLElement(node) && node.tagName === "HR",
);
const nodesToExport =
startIndex > -1 ? childNodes.slice(startIndex) : childNodes;
@@ -390,8 +391,9 @@ export class ContentSearcher {
parent = parent.parentElement;
}
return mainDocument.scrollingElement instanceof HTMLElement
? mainDocument.scrollingElement
: null;
if (isInstanceOfHTMLElement(mainDocument.scrollingElement)) {
return mainDocument.scrollingElement;
}
return null;
}
}
@@ -115,17 +115,24 @@ export const findArc = (
const arc = [];
const step = sweep ? -1 : 1;
for (let i = indexDest; true; i += step) {
arc.push(points[i]);
let i = indexDest;
if (i === indexCur) {
break;
}
// Checking if indices exist prevents runtime crashes
if (indexCur !== -1 && indexDest !== -1) {
while (i >= -1 && i <= points.length) {
arc.push(points[i]);
if (sweep && i === 0) {
i = points.length;
} else if (!sweep && i === points.length - 1) {
i = -1;
if (i === indexCur) {
break;
}
if (sweep && i === 0) {
i = points.length;
} else if (!sweep && i === points.length - 1) {
i = -1;
} else {
i += step;
}
}
}
+2 -1
View File
@@ -381,7 +381,7 @@ const walkers = {
let localGroup = randomId();
switch (fillRule) {
case "nonzero":
case "nonzero": {
let initialWindingOrder = "clockwise";
elements = points.map((pointArr, idx): ExcalidrawDraw => {
@@ -421,6 +421,7 @@ const walkers = {
};
});
break;
}
case "evenodd":
elements = points.map((pointArr, idx): ExcalidrawDraw => {
const tPoints: Point[] = transformPoints(pointArr, mat4.clone(mat));
-5
View File
@@ -4,7 +4,6 @@ import { ViewStateResult, WorkspaceLeaf } from "obsidian";
import {
AppState,
BinaryFiles,
ExcalidrawInitialDataState,
ExcalidrawProps,
LibraryItems,
SceneData,
@@ -50,10 +49,6 @@ export type ExcalidrawViewScene = Omit<
files: BinaryFiles;
};
export type ExcalidrawViewInitialData = ExcalidrawInitialDataState & {
libraryItems?: LibraryItems;
};
export type ExcalidrawViewAppState = Omit<
Partial<AppState>,
"showHyperlinkPopup"
+1
View File
@@ -1,6 +1,7 @@
declare module "polybooljs" {
interface PolyBoolStatic {
epsilon(value: number): void;
buildLog(value: boolean): void;
}
const PolyBool: PolyBoolStatic;
+7 -7
View File
@@ -106,7 +106,7 @@ export type ObsidianCommandManager = {
};
export type ObsidianDraggable = {
type?: "file" | "files" | "link" | string;
type?: "file" | "files" | "link" | "text" | "unknown";
file?: TFile;
files?: TFile[];
title?: string;
@@ -158,17 +158,16 @@ export type LocalGraphView = View & {
};
declare global {
const unpackBase64Deflate: (value: string) => string;
interface Window {
ExcalidrawAutomate: ExcalidrawAutomate;
pdfjsLib: PdfJsLibrary;
unpackBase64Deflate?: (value: string) => string;
PolyBool?: PolyBoolLibrary;
electronWindow?: {
isAlwaysOnTop(): boolean;
setAlwaysOnTop(flag: boolean): void;
};
eval: typeof window.eval;
eval: (x: string) => unknown;
React?: typeof import("react");
ReactDOM?: typeof import("react-dom/client");
ExcalidrawLib?: typeof ExcalidrawLib;
@@ -193,9 +192,10 @@ declare module "obsidian" {
setType(name: string, type: string): void;
};
plugins: {
plugins: {
[key: string]: Plugin | undefined;
};
manifests: Record<string, PluginManifest>;
plugins: Record<string, (Plugin & { api?: unknown }) | undefined>;
enablePlugin(id: string): Promise<void>;
disablePlugin(id: string): Promise<void>;
};
}
interface FileManager {
+8 -4
View File
@@ -30,6 +30,7 @@ import {
getGeminiImageRequestConfig,
getGeminiSupportedSizes,
} from "src/utils/geminiImageModelUtils";
import { strictArrayBuffer } from "./obsidianUtils";
type NormalizedBinaryInput = {
source: string;
@@ -1768,12 +1769,15 @@ const buildMultipartFormBody = (
chunks.push(encoder.encode(`--${boundary}--\r\n`));
const combined = concatUint8Arrays(chunks);
return {
contentType: `multipart/form-data; boundary=${boundary}`,
body: combined.buffer.slice(
combined.byteOffset,
combined.byteOffset + combined.byteLength,
) as ArrayBuffer,
body: strictArrayBuffer(
combined.buffer.slice(
combined.byteOffset,
combined.byteOffset + combined.byteLength,
),
),
};
};
+188 -95
View File
@@ -5,6 +5,7 @@ import type {
ExtrasComponent,
} from "@zsviczian/excalidraw-extras-api";
import { t } from "../lang/helpers";
import en from "src/lang/locale/en";
const EXTRAS_PLUGIN_ID = "excalidraw-extras";
@@ -12,6 +13,7 @@ const REQUIRED_EXTRAS_VERSIONS: Record<
string,
{ min?: string; exact?: string }
> = {
plugin: { min: "0.0.14" },
mathjax: { min: "1.0.0" },
mermaid: { exact: "2.2.2" },
pdf: { min: "1.0.0" },
@@ -20,10 +22,15 @@ const REQUIRED_EXTRAS_VERSIONS: Record<
type ActionResolution = "success" | "ignore" | "cancel";
export class ExcalidrawExtrasGateway {
private pluginDisableTimer: NodeJS.Timeout | null = null;
private featureDisableTimers: Record<string, NodeJS.Timeout> = {};
export type VersionCheckResult = {
valid: boolean;
isExact?: boolean;
compName?: string;
reqVersion?: string;
currentVersion?: string;
};
export class ExcalidrawExtrasGateway {
private ignoredComponents: Set<string> = new Set();
private activationTask: Promise<ActionResolution> | null = null;
@@ -43,7 +50,7 @@ export class ExcalidrawExtrasGateway {
}
public async getMermaid(): Promise<ExcalidrawExtrasAPI["mermaid"] | null> {
const api = await this.ensureActiveAndGetAPI("mermaid" as ExtrasComponent);
const api = await this.ensureActiveAndGetAPI("mermaid");
return api ? api.mermaid : null;
}
@@ -61,10 +68,14 @@ export class ExcalidrawExtrasGateway {
return null;
}
if (!this.activationTask) {
this.activationTask = this.handleActivation(component).finally(() => {
this.activationTask = null; // Clear shared task for future triggers
});
if (this.activationTask === null) {
this.activationTask = (async () => {
try {
return await this.handleActivation(component);
} finally {
this.activationTask = null;
}
})();
}
const resolution = await this.activationTask;
@@ -83,7 +94,7 @@ export class ExcalidrawExtrasGateway {
return null;
}
if (!this.isVersionValid(component, api)) {
if (!this.checkVersion(component, api).valid) {
return null;
}
@@ -96,7 +107,12 @@ export class ExcalidrawExtrasGateway {
// If everything is already perfect, return success immediately
if (this.isInstalled() && this.isPluginEnabled()) {
const api = this.getAPI();
if (api && api.features.isActive(component)) {
// Added version check to the success path so it opens the modal if an update is needed
if (
api &&
api.features.isActive(component) &&
this.checkVersion(component, api).valid
) {
return "success";
}
}
@@ -114,64 +130,85 @@ export class ExcalidrawExtrasGateway {
}
public isInstalled(): boolean {
return !!(this.app as any).plugins.manifests[EXTRAS_PLUGIN_ID];
return !!this.app.plugins.manifests[EXTRAS_PLUGIN_ID];
}
public isPluginEnabled(): boolean {
return !!(this.app as any).plugins.plugins[EXTRAS_PLUGIN_ID];
return !!this.app.plugins.plugins[EXTRAS_PLUGIN_ID];
}
public getAPI(): ExcalidrawExtrasAPI | null {
return (this.app as any).plugins.plugins[EXTRAS_PLUGIN_ID]?.api || null;
return (
(this.app.plugins.plugins[EXTRAS_PLUGIN_ID]
?.api as ExcalidrawExtrasAPI) || null
);
}
public isVersionValid(component: string, api: ExcalidrawExtrasAPI): boolean {
public checkVersion(
component: string,
api: ExcalidrawExtrasAPI,
): VersionCheckResult {
// 1. Check overall plugin version first
const pluginReq = REQUIRED_EXTRAS_VERSIONS.plugin;
if (pluginReq) {
const manifest = this.app.plugins.manifests[EXTRAS_PLUGIN_ID];
const pluginVersion = manifest?.version || "0.0.0";
const pluginCompName = t("EXTRAS_GATEWAY_COMP_PLUGIN");
if (pluginReq.exact && pluginVersion !== pluginReq.exact) {
return {
valid: false,
isExact: true,
compName: pluginCompName,
reqVersion: pluginReq.exact,
currentVersion: pluginVersion,
};
}
if (
pluginReq.min &&
this.compareVersions(pluginVersion, pluginReq.min) < 0
) {
return {
valid: false,
isExact: false,
compName: pluginCompName,
reqVersion: pluginReq.min,
currentVersion: pluginVersion,
};
}
}
// 2. Check specific component version
const currentVersion = api.versions[component as keyof typeof api.versions];
const req = REQUIRED_EXTRAS_VERSIONS[component];
if (!req) {
return true;
return { valid: true };
}
const compName = t(
`EXTRAS_GATEWAY_COMP_${component.toUpperCase()}` as keyof typeof en,
);
if (req.exact && currentVersion !== req.exact) {
const compName = t(
`EXTRAS_GATEWAY_COMP_${component.toUpperCase()}` as any,
);
new Notice(
`Excalidraw Extras Update Required. ${compName} requires EXACTLY v${req.exact} (Found v${currentVersion})`,
);
window.open(`obsidian://show-plugin?id=${EXTRAS_PLUGIN_ID}`);
return false;
return {
valid: false,
isExact: true,
compName,
reqVersion: req.exact,
currentVersion,
};
}
if (req.min && this.compareVersions(currentVersion, req.min) < 0) {
const compName = t(
`EXTRAS_GATEWAY_COMP_${component.toUpperCase()}` as any,
);
new Notice(
`Excalidraw Extras Update Required. ${compName} requires >= v${req.min} (Found v${currentVersion})`,
);
window.open(`obsidian://show-plugin?id=${EXTRAS_PLUGIN_ID}`);
return false;
return {
valid: false,
isExact: false,
compName,
reqVersion: req.min,
currentVersion,
};
}
return true;
}
public async enablePlugin(minutes: number = 0) {
const pluginsManager = (this.app as any).plugins;
await pluginsManager.enablePlugin(EXTRAS_PLUGIN_ID);
if (this.pluginDisableTimer) {
clearTimeout(this.pluginDisableTimer);
}
if (minutes > 0) {
// Note: -1 bypasses this, leaving it on for the session
this.pluginDisableTimer = setTimeout(
async () => {
await pluginsManager.disablePlugin(EXTRAS_PLUGIN_ID);
new Notice(t("EXTRAS_GATEWAY_TIMER_EXPIRED"));
},
minutes * 60 * 1000,
);
}
return { valid: true };
}
public async enableFeature(
@@ -198,8 +235,8 @@ export class ExcalidrawExtrasGateway {
}
/**
* A progressive state-machine Modal. It checks the environment every time it renders.
* If you enable the plugin, it re-renders and moves seamlessly to the "Enable Feature" step if needed.
* A progressive state-machine modal that evaluates the environment at each render
* and advances when prerequisites are satisfied.
*/
class ExtrasActivationModal extends Modal {
private hasResolved = false;
@@ -214,7 +251,7 @@ class ExtrasActivationModal extends Modal {
}
onOpen() {
this.renderStep();
void this.renderStep();
}
async renderStep() {
@@ -222,7 +259,7 @@ class ExtrasActivationModal extends Modal {
contentEl.empty();
const compName = t(
`EXTRAS_GATEWAY_COMP_${this.component.toUpperCase()}` as any,
`EXTRAS_GATEWAY_COMP_${this.component.toUpperCase()}` as keyof typeof en,
);
// Step 1: Install Plugin
@@ -243,21 +280,39 @@ class ExtrasActivationModal extends Modal {
return;
}
// Step 2: Enable Plugin
if (!this.gateway.isPluginEnabled()) {
// Step 2: Plugin installed but disabled
if (this.gateway.isInstalled() && !this.gateway.isPluginEnabled()) {
contentEl.createEl("h2", { text: t("EXTRAS_GATEWAY_TITLE") });
contentEl.createEl("p", {
text: t("EXTRAS_GATEWAY_DESC").replace("{component}", compName),
});
contentEl.createEl("p", {
text: t("EXTRAS_GATEWAY_MANUAL_ENABLE_NOTICE"),
});
this.addControls(
contentEl,
async (minutes) => {
await this.gateway.enablePlugin(minutes);
this.renderStep(); // Re-evaluate state!
},
t("EXTRAS_GATEWAY_ENABLE_PERM_BTN"),
);
new Setting(contentEl)
.addButton((btn) =>
btn
.setButtonText(t("EXTRAS_GATEWAY_UPDATE_BTN"))
.setCta()
.onClick(() => {
this.resolveAndClose("cancel");
window.setTimeout(() => {
window.open(`obsidian://show-plugin?id=${EXTRAS_PLUGIN_ID}`);
}, 50);
}),
)
.addButton((btn) =>
btn
.setButtonText(t("BACKUP_CANCEL"))
.onClick(() => this.resolveAndClose("cancel")),
)
.addButton((btn) =>
btn
.setButtonText(t("EXTRAS_GATEWAY_IGNORE_SESSION"))
.setWarning()
.onClick(() => this.resolveAndClose("ignore")),
);
return;
}
@@ -269,8 +324,38 @@ class ExtrasActivationModal extends Modal {
return;
}
if (!this.gateway.isVersionValid(this.component, api)) {
this.resolveAndClose("cancel");
const versionCheck = this.gateway.checkVersion(this.component, api);
if (!versionCheck.valid) {
contentEl.createEl("h2", { text: t("EXTRAS_GATEWAY_UPDATE_TITLE") });
const msg = t(
versionCheck.isExact
? "EXTRAS_GATEWAY_UPDATE_EXACT"
: "EXTRAS_GATEWAY_UPDATE_MIN",
)
.replace("{component}", versionCheck.compName)
.replace("{reqVersion}", versionCheck.reqVersion)
.replace("{currentVersion}", versionCheck.currentVersion);
contentEl.createEl("p", { text: msg });
new Setting(contentEl)
.addButton((btn) =>
btn
.setButtonText(t("EXTRAS_GATEWAY_UPDATE_BTN"))
.setCta()
.onClick(() => {
this.resolveAndClose("cancel");
window.setTimeout(() => {
window.open(`obsidian://show-plugin?id=${EXTRAS_PLUGIN_ID}`);
}, 50);
}),
)
.addButton((btn) =>
btn
.setButtonText(t("BACKUP_CANCEL"))
.onClick(() => this.resolveAndClose("cancel")),
);
return;
}
@@ -287,9 +372,11 @@ class ExtrasActivationModal extends Modal {
this.addControls(
contentEl,
async (minutes) => {
await this.gateway.enableFeature(this.component, api, minutes);
this.renderStep(); // Re-evaluate state!
(minutes) => {
void (async () => {
await this.gateway.enableFeature(this.component, api, minutes);
await this.renderStep(); // Re-evaluate state!
})();
},
featureBtnText,
);
@@ -314,29 +401,30 @@ class ExtrasActivationModal extends Modal {
const isSessionOnly =
this.component === "mathjax" || this.component === "mermaid";
if (isSessionOnly) {
new Setting(container)
.setName(t("EXTRAS_GATEWAY_TEMP_ENABLE_TITLE"))
.setDesc(t("EXTRAS_GATEWAY_SESSION_ENABLE_DESC"))
.addButton((btn) =>
btn
.setButtonText(t("EXTRAS_GATEWAY_ENABLE_CURRENT_SESSION"))
.onClick(() => onEnable(-1)),
);
} else {
new Setting(container)
.setName(t("EXTRAS_GATEWAY_TEMP_ENABLE_TITLE"))
.setDesc(t("EXTRAS_GATEWAY_TEMP_ENABLE_DESC"))
.addButton((btn) =>
btn.setButtonText("5 min").onClick(() => onEnable(5)),
)
.addButton((btn) =>
btn.setButtonText("30 min").onClick(() => onEnable(30)),
)
.addButton((btn) =>
btn.setButtonText("1 hour").onClick(() => onEnable(60)),
);
if (this.gateway.isInstalled() && this.gateway.isPluginEnabled()) {
if (isSessionOnly) {
new Setting(container)
.setName(t("EXTRAS_GATEWAY_TEMP_ENABLE_TITLE"))
.setDesc(t("EXTRAS_GATEWAY_SESSION_ENABLE_DESC"))
.addButton((btn) =>
btn
.setButtonText(t("EXTRAS_GATEWAY_ENABLE_CURRENT_SESSION"))
.onClick(() => onEnable(-1)),
);
} else {
new Setting(container)
.setName(t("EXTRAS_GATEWAY_TEMP_ENABLE_TITLE"))
.setDesc(t("EXTRAS_GATEWAY_TEMP_ENABLE_DESC"))
.addButton((btn) =>
btn.setButtonText("5 Min").onClick(() => onEnable(5)),
)
.addButton((btn) =>
btn.setButtonText("30 Min").onClick(() => onEnable(30)),
)
.addButton((btn) =>
btn.setButtonText("1 Hour").onClick(() => onEnable(60)),
);
}
}
new Setting(container)
@@ -353,19 +441,24 @@ class ExtrasActivationModal extends Modal {
);
}
private resolveAndClose(result: ActionResolution) {
private resolveAndClose(
result: ActionResolution,
shouldClose: boolean = true,
) {
if (this.hasResolved) {
return;
}
this.hasResolved = true;
this.resolvePromise(result);
this.close();
if (shouldClose) {
this.close();
}
}
onClose() {
this.contentEl.empty();
if (!this.hasResolved) {
this.resolveAndClose("cancel");
this.resolveAndClose("cancel", false);
}
}
}
+2 -1
View File
@@ -10,7 +10,8 @@ export async function getDataURL(
const dataURL = reader.result as DataURL;
resolve(dataURL);
};
reader.onerror = (error) => reject(error);
reader.onerror = (error: ProgressEvent<FileReader>) =>
reject(new Error(`Failed to read file as DataURL.}`));
reader.readAsDataURL(new Blob([new Uint8Array(file)], { type: mimeType }));
});
}
+8 -13
View File
@@ -1,15 +1,14 @@
export const durationTreshold = 0; //0.05; //ms
export const DEBUGGING = false;
export const log = console.log.bind(window.console);
//eslint-disable-next-line obsidianmd/rule-custom-message
export const log = (...args: unknown[]) => console.log(...args);
export const debug = (
fn: (...args: unknown[]) => unknown,
fnName: string,
...messages: unknown[]
) => {
//console.log(fnName,fn,...messages);
console.log(fnName, ...messages);
log(fnName, ...messages);
};
let timestamp: number[] = [];
@@ -47,19 +46,15 @@ export class CustomMutationObserver {
}
observe(target: Node, options: MutationObserverInit) {
const wrappedCallback: MutationCallback = async (
mutationsList,
observer,
) => {
const wrappedCallback: MutationCallback = (mutationsList, observer) => {
const startTime = performance.now(); // Get start time
await this.originalCallback(mutationsList, observer); // Invoke the original callback
this.originalCallback(mutationsList, observer); // Invoke the original callback
const endTime = performance.now(); // Get end time
const executionTime = endTime - startTime;
if (executionTime > durationTreshold) {
console.log(
`Excalidraw ${this.name} MutationObserver callback took ${executionTime}ms to execute`,
observer,
);
const message = `Excalidraw ${this.name} MutationObserver callback took ${executionTime}ms to execute`;
// eslint-disable-next-line obsidianmd/rule-custom-message -- needed for production debugging
console.log(message, observer);
}
};
+3 -1
View File
@@ -14,6 +14,7 @@ export const setDynamicStyle = (
dynamicStyle: DynamicStyle,
textBackgroundColor?: string,
) => {
color = color ?? "white";
if (dynamicStyle === "none") {
//view.excalidrawContainer?.removeAttribute("style");
window.setTimeout(() =>
@@ -24,7 +25,8 @@ export const setDynamicStyle = (
);
const toolspanel = view.toolsPanelRef?.current?.containerRef?.current;
if (toolspanel) {
let toolsStyle = toolspanel.getAttribute("style");
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/2810
let toolsStyle = toolspanel.getAttribute("style") ?? "";
toolsStyle = toolsStyle.replace(/--color-primary.*/, "");
toolspanel.setAttribute("style", toolsStyle);
}
+55 -54
View File
@@ -40,8 +40,6 @@ import {
isVersionNewerThanOther,
scaleLoadedImage,
} from "src/utils/utils";
import { LaTexPrompt } from "src/shared/Dialogs/Prompt";
import { t } from "src/lang/helpers";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { EmbeddedFilesLoader } from "src/shared/EmbeddedFileLoader";
import {
@@ -59,9 +57,9 @@ import {
sceneRemoveInternalLinks,
} from "./excalidrawViewUtils";
import { ScriptEngine } from "src/shared/Scripts";
import { getEA } from "src/core";
import { ColorMap, FileData } from "src/types/embeddedFileLoaderTypes";
import { ExportSettings } from "src/types/exportUtilTypes";
import type { StrokeWidthKey } from "@zsviczian/excalidraw/types/common/src/constants";
declare const PLUGIN_VERSION: string;
@@ -828,57 +826,6 @@ export function repositionElementsToCursor(
});
}
export const insertLaTeXToView = (
view: ExcalidrawView,
center: boolean = false,
) => {
const app = view.plugin.app;
const ea = getEA(view);
LaTexPrompt.Prompt(
app,
t("ENTER_LATEX"),
view.plugin.settings.latexBoilerplate,
).then(
async (formula: string) => {
const lastLatexEl = ea
.getViewElements()
.filter(
(el) =>
el.type === "image" && view.excalidrawData.hasEquation(el.fileId),
)
.reduce(
(maxel, curr) =>
!maxel || curr.updated > maxel.updated ? curr : maxel,
undefined,
) as ExcalidrawImageElement;
let scaleX = 1;
let scaleY = 1;
if (lastLatexEl) {
const equation = view.excalidrawData.getEquation(lastLatexEl.fileId);
const dataurl = await ea.tex2dataURL(equation.latex);
if (dataurl.size.width > 0 && dataurl.size.height > 0) {
scaleX = lastLatexEl.width / dataurl.size.width;
scaleY = lastLatexEl.height / dataurl.size.height;
}
}
if (formula) {
const id = await ea.addLaTex(0, 0, formula, scaleX, scaleY);
if (center) {
const el = ea.getElement(id);
const { width, height } = el;
const { x, y } = ea.getViewCenterPosition();
el.x = x - width / 2;
el.y = y - height / 2;
}
await ea.addElementsToView(!center, false, true);
ea.selectElementsInView([id]);
}
ea.destroy();
},
() => {},
);
};
export const search = async (view: ExcalidrawView) => {
const ea = view.plugin.ea;
ea.reset();
@@ -1162,3 +1109,57 @@ export function ensureActiveScriptSettingsObject(
ScriptSettingValue
>;
}
export const getStrokeKeyFormLegacyWidth = (strokeWidth: number): StrokeWidthKey => {
switch(strokeWidth) {
case 0.5:
return "thin";
case 1:
return "medium";
case 2:
return "bold";
default:
return undefined;
}
}
// Returns an appState key for the stroke width
// excalidraw.com deprected and removed currentItemStrokeWidth from appState
// but the plugin still supports it to allow custom line width settings for scripts and custom pens
// if the legacy stroke width is provided, it will be converted to the corresponding stroke width key
// if there is a matching key, the key will be preferred over the legacy stroke width value
// if there is no matching key, the legacy stroke width value will be used
export const getAppStateStrokeWidthEntry = (strokeWidthKey:StrokeWidthKey, legacyStrokeWidth: number) => {
if (legacyStrokeWidth !== undefined) {
strokeWidthKey = getStrokeKeyFormLegacyWidth(legacyStrokeWidth);
}
if (!!legacyStrokeWidth && !strokeWidthKey) {
return { currentItemStrokeWidth: legacyStrokeWidth };
}
if (!strokeWidthKey) {
return {};
}
return {currentItemStrokeWidthKey: strokeWidthKey};
}
//replicated from excalidraw constants.ts
const FREEDRAW_STROKE_WIDTH: Readonly<
Record<StrokeWidthKey | "extraBold", ExcalidrawElement["strokeWidth"]>
> = {
extraThin: 0.25,
thin: 0.5,
medium: 1,
bold: 2,
extraBold: 4, // legacy (may be used again in the future)
};
//based on excalidraw constants.ts getStrokeWidthByKey
export const getFreedrawStrokeWidthByKey = (
strokeWidthKey: StrokeWidthKey,
strokeWidth?: number,
): ExcalidrawElement["strokeWidth"] => {
if (strokeWidth) {
return strokeWidth;
}
return FREEDRAW_STROKE_WIDTH[strokeWidthKey];
};
+19 -6
View File
@@ -7,6 +7,7 @@ import { getCommonBoundingBox, restoreElements } from "src/constants/constants";
import { getEA } from "src/core";
import { t } from "src/lang/helpers";
import type ExcalidrawView from "src/view/ExcalidrawView";
import { errorlog } from "./utils";
function estimateBounds(
elements: ExcalidrawElement[],
@@ -64,8 +65,10 @@ export const insertLaTeXToView = (
) => {
const app = view.plugin.app;
const ea = getEA(view);
void import("src/shared/Dialogs/Prompt").then(({ LaTexPrompt }) => {
LaTexPrompt.Prompt(
view.plugin,
app,
t("ENTER_LATEX"),
view.plugin.settings.latexBoilerplate,
@@ -82,31 +85,41 @@ export const insertLaTeXToView = (
!maxel || curr.updated > maxel.updated ? curr : maxel,
undefined,
) as ExcalidrawImageElement;
let scaleX = 1;
let scaleY = 1;
if (lastLatexEl) {
const equation = view.excalidrawData.getEquation(lastLatexEl.fileId);
const dataurl = await ea.tex2dataURL(equation.latex);
if (dataurl.size.width > 0 && dataurl.size.height > 0) {
if (dataurl && dataurl.size.width > 0 && dataurl.size.height > 0) {
scaleX = lastLatexEl.width / dataurl.size.width;
scaleY = lastLatexEl.height / dataurl.size.height;
}
}
if (formula) {
const id = await ea.addLaTex(0, 0, formula, scaleX, scaleY);
if (center) {
const el = ea.getElement(id);
const { width, height } = el;
const { x, y } = ea.getViewCenterPosition();
el.x = x - width / 2;
el.y = y - height / 2;
if (el) {
const { width, height } = el;
const { x, y } = ea.getViewCenterPosition();
el.x = x - width / 2;
el.y = y - height / 2;
}
}
await ea.addElementsToView(!center, false, true);
ea.selectElementsInView([id]);
}
ea.destroy();
},
() => {},
(e) => {
// Promise rejection handler (e.g. user cancelled prompt or Extras plugin is missing)
if (e && e instanceof Error) {
errorlog({ message: "LaTeX Insertion aborted", error: e as unknown });
}
},
);
});
};
+3 -2
View File
@@ -47,6 +47,7 @@ import { EmbeddedFile } from "src/shared/EmbeddedFileLoader";
import { CaptureUpdateAction } from "src/constants/constants";
import { setSanitizedHtml } from "./htmlUtils";
import { URLs } from "src/constants/safeUrls";
import { isInstanceOfHTMLDivElement } from "./typechecks";
type CommandLinkOptInPlugin = {
settings: {
@@ -891,7 +892,7 @@ export function getViewColorPalette(
const api = view.excalidrawAPI;
const { colorPalette } = api.getAppState();
if (!colorPalette || !colorPalette.hasOwnProperty(palette)) {
if (!colorPalette || !Object.hasOwn(colorPalette ?? {}, palette)) {
return getDefaultColorPalette();
}
@@ -1028,7 +1029,7 @@ export const setMobileNavbarPosition = (dock: boolean) => {
const navbar = mainDocument.querySelector(
"body>.app-container>.mobile-navbar",
);
if (navbar && navbar instanceof HTMLDivElement) {
if (navbar && isInstanceOfHTMLDivElement(navbar)) {
if (dock) {
navbar.addClass("excalidraw-mobile-navbar-docked");
} else {
+1 -4
View File
@@ -1,8 +1,5 @@
import { Notice } from "obsidian";
import {
DEVICE,
EXCALIDRAW_PLUGIN,
} from "src/constants/constants";
import { DEVICE, EXCALIDRAW_PLUGIN } from "src/constants/constants";
import { t } from "src/lang/helpers";
import { download } from "./fileUtils";
import { svgToBase64 } from "./utils";
+1 -2
View File
@@ -1,7 +1,6 @@
import { DataURL } from "@zsviczian/excalidraw/types/excalidraw/types";
import {
App,
DataAdapter,
loadPdfJs,
MetadataCache,
normalizePath,
@@ -177,7 +176,7 @@ export const getURLImageExtension = (url: string): string => {
};
export const getMimeType = (extension: string): MimeType => {
if (IMAGE_MIME_TYPES.hasOwnProperty(extension)) {
if (Object.hasOwn(IMAGE_MIME_TYPES, extension)) {
return IMAGE_MIME_TYPES[extension as ImageExtension];
}
switch (extension) {
+1 -1
View File
@@ -127,7 +127,7 @@ export type MagicCacheData =
| {
status: "error";
message?: string;
code: "ERR_GENERATION_INTERRUPTED" | string;
code: "ERR_GENERATION_INTERRUPTED";
};
const SYSTEM_PROMPT = `You are a skilled front-end developer who builds interactive prototypes from wireframes, and is an expert at CSS Grid and Flex design.
+1 -1
View File
@@ -6,4 +6,4 @@ export const labelCTRL = () => (isApplePlatform() ? "CMD" : "CTRL");
export const labelALT = () => (isApplePlatform() ? "OPT" : "ALT");
export const labelMETA = () =>
isApplePlatform() ? "CTRL" : DEVICE.isWindows ? "WIN" : "META";
export const labelSHIFT = () => "SHIFT";
export const labelSHIFT = () => "SHIFT" as const;
+14 -2
View File
@@ -24,6 +24,7 @@ import {
import { parse, stringify } from "yaml";
import type ExcalidrawView from "src/view/ExcalidrawView";
import { setStyle } from "./styleUtils";
import { isInstanceOfHTMLBodyElement } from "./typechecks";
export const getParentOfClass = (
element: Element,
@@ -33,7 +34,7 @@ export const getParentOfClass = (
while (
parent &&
!parent.classList.contains(cssClass) &&
!(parent instanceof window.HTMLBodyElement)
!isInstanceOfHTMLBodyElement(parent)
) {
parent = parent.parentElement;
}
@@ -620,7 +621,7 @@ export function getAudioElementHeight(): number {
let height = 0;
try {
// Force layout calculation
mainDocument.body.offsetHeight;
height = mainDocument.body.offsetHeight;
// Get height from bounding rect
const rect = audioElement.getBoundingClientRect();
@@ -650,3 +651,14 @@ export function stripYamlFrontmatter(text: string): string {
}
return text.replace(/^---\s*\r?\n[\s\S]*?\r?\n---\s*\r?\n?/, "");
}
export function strictArrayBuffer(
buffer: ArrayBuffer | SharedArrayBuffer,
): ArrayBuffer {
if (buffer instanceof SharedArrayBuffer) {
const strictBuffer = new ArrayBuffer(buffer.byteLength);
new Uint8Array(strictBuffer).set(new Uint8Array(buffer));
return strictBuffer;
}
return buffer;
}
+8 -2
View File
@@ -1,4 +1,7 @@
import type { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import type {
ElementsMap,
ExcalidrawElement,
} from "@zsviczian/excalidraw/types/element/src/types";
import type { AppState } from "@zsviczian/excalidraw/types/excalidraw/types";
import type { TFile } from "obsidian";
import { FRONTMATTER_KEYS, getContainerElement } from "src/constants/constants";
@@ -248,7 +251,10 @@ export function _getContainerElement(
return null;
}
if (element.containerId) {
return getContainerElement(element, arrayToMap(scene.elements));
return getContainerElement(
element,
arrayToMap(scene.elements) as ElementsMap,
);
}
return null;
}
+2 -2
View File
@@ -57,7 +57,7 @@ export const installButton = async (
where:
"ExcalidrawPlugin.registerInstallCodeblockProcessor.codeblockProcessor.onClick",
source,
error: e,
error: e as unknown,
});
}
const fname = decodedURI.substring(decodedURI.lastIndexOf("/") + 1);
@@ -92,7 +92,7 @@ export const installButton = async (
scriptFile = await download(source, scriptFile, scriptPath);
if (!scriptFile) {
setButtonText("ERROR");
throw "File not found";
throw new Error("File not found");
}
svgFile = await download(getIMGFilename(source, "svg"), svgFile, svgPath);
setButtonText("UPTODATE");
+1 -1
View File
@@ -32,7 +32,7 @@ type StyleObject = Partial<CSSStyleDeclaration> & {
};
export const setStyle = (
element: HTMLElement | SVGSVGElement | null | undefined,
element: HTMLElement | SVGElement | null | undefined,
styles: StyleObject,
): void => {
if (!element) {
+188 -21
View File
@@ -1,24 +1,191 @@
/**
* Checks if a given target is an HTMLElement.
*
* This function is necessary because `instanceof HTMLElement` can fail
* in environments with multiple execution contexts (e.g., popout windows),
* where `HTMLElement` comes from different global objects.
* Instead, we use feature detection by checking for key properties
* common to all HTML elements (nodeType and tagName).
*
* @param target - The target to check.
* @returns True if the target is an HTMLElement, false otherwise.
* Cross-window-safe type guards
* Uses the element's own window (defaultView) to get the correct HTMLElement constructor.
*/
export function isHTMLElement(
target: EventTarget | null,
): target is HTMLElement {
return (
target !== null &&
typeof target === "object" &&
"nodeType" in target &&
target.nodeType === 1 && // nodeType 1 means it's an element
"tagName" in target &&
typeof target.tagName === "string"
); // tagName exists on HTML elements
export function isInstanceOfHTMLElement(value: unknown): value is HTMLElement {
if (value == null || typeof value !== "object") {
return false;
}
const win = (value as { ownerDocument?: Document }).ownerDocument
?.defaultView;
return win?.HTMLElement
? value instanceof win.HTMLElement
: value instanceof HTMLElement;
}
export function isInstanceOfHTMLDivElement(
value: unknown,
): value is HTMLDivElement {
if (value == null || typeof value !== "object") {
return false;
}
const win = (value as { ownerDocument?: Document }).ownerDocument
?.defaultView;
return win?.HTMLDivElement
? value instanceof win.HTMLDivElement
: value instanceof HTMLDivElement;
}
export function isInstanceOfHTMLBodyElement(
value: unknown,
): value is HTMLBodyElement {
if (value == null || typeof value !== "object") {
return false;
}
const win = (value as { ownerDocument?: Document }).ownerDocument
?.defaultView;
return win?.HTMLBodyElement
? value instanceof win.HTMLBodyElement
: value instanceof HTMLBodyElement;
}
export function isInstanceOfHTMLImageElement(
value: unknown,
): value is HTMLImageElement {
if (value == null || typeof value !== "object") {
return false;
}
const win = (value as { ownerDocument?: Document }).ownerDocument
?.defaultView;
return win?.HTMLImageElement
? value instanceof win.HTMLImageElement
: value instanceof HTMLImageElement;
}
export function isInstanceOfElement(value: unknown): value is Element {
if (value == null || typeof value !== "object") {
return false;
}
const win = (value as { ownerDocument?: Document }).ownerDocument
?.defaultView;
return win?.Element ? value instanceof win.Element : value instanceof Element;
}
export function isInstanceOfDocumentFragment(
value: unknown,
): value is DocumentFragment {
if (value == null || typeof value !== "object") {
return false;
}
const win = (value as { ownerDocument?: Document }).ownerDocument
?.defaultView;
return win?.DocumentFragment
? value instanceof win.DocumentFragment
: value instanceof DocumentFragment;
}
export function isInstanceOfSVGSVGElement(
value: unknown,
): value is SVGSVGElement {
if (value == null || typeof value !== "object") {
return false;
}
const win = (value as { ownerDocument?: Document }).ownerDocument
?.defaultView;
return win?.SVGSVGElement
? value instanceof win.SVGSVGElement
: value instanceof SVGSVGElement;
}
export function isInstanceOfSVGElement(value: unknown): value is SVGElement {
if (value == null || typeof value !== "object") {
return false;
}
const win = (value as { ownerDocument?: Document }).ownerDocument
?.defaultView;
return win?.SVGElement
? value instanceof win.SVGElement
: value instanceof SVGElement;
}
export function isInstanceOfHTMLStyleElement(
value: unknown,
): value is HTMLStyleElement {
if (value == null || typeof value !== "object") {
return false;
}
const win = (value as { ownerDocument?: Document }).ownerDocument
?.defaultView;
return win?.HTMLStyleElement
? value instanceof win.HTMLStyleElement
: value instanceof HTMLStyleElement;
}
export function isInstanceOfHTMLInputElement(
value: unknown,
): value is HTMLInputElement {
if (value == null || typeof value !== "object") {
return false;
}
const win = (value as { ownerDocument?: Document }).ownerDocument
?.defaultView;
return win?.HTMLInputElement
? value instanceof win.HTMLInputElement
: value instanceof HTMLInputElement;
}
export function isInstanceOfHTMLTextAreaElement(
value: unknown,
): value is HTMLTextAreaElement {
if (value == null || typeof value !== "object") {
return false;
}
const win = (value as { ownerDocument?: Document }).ownerDocument
?.defaultView;
return win?.HTMLTextAreaElement
? value instanceof win.HTMLTextAreaElement
: value instanceof HTMLTextAreaElement;
}
export function isInstanceOfHTMLSelectElement(
value: unknown,
): value is HTMLSelectElement {
if (value == null || typeof value !== "object") {
return false;
}
const win = (value as { ownerDocument?: Document }).ownerDocument
?.defaultView;
return win?.HTMLSelectElement
? value instanceof win.HTMLSelectElement
: value instanceof HTMLSelectElement;
}
export function isInstanceOfHTMLButtonElement(
value: unknown,
): value is HTMLButtonElement {
if (value == null || typeof value !== "object") {
return false;
}
const win = (value as { ownerDocument?: Document }).ownerDocument
?.defaultView;
return win?.HTMLButtonElement
? value instanceof win.HTMLButtonElement
: value instanceof HTMLButtonElement;
}
+10 -19
View File
@@ -20,6 +20,7 @@ import {
} from "../constants/constants";
import ExcalidrawPlugin from "../core/main";
import {
ElementsMap,
ExcalidrawElement,
ExcalidrawImageElement,
ImageCrop,
@@ -51,6 +52,7 @@ import ExcalidrawView from "../view/ExcalidrawView";
import { getEmptyDrawingElementsRuntime } from "src/constants/emptydrawing";
import { makeEntitiesXmlSafe, sanitizedFragment } from "./htmlUtils";
import { URLs } from "src/constants/safeUrls";
import { isInstanceOfSVGSVGElement } from "./typechecks";
export { errorlog, getDataURL } from "./coreUtils";
export { addAppendUpdateCustomData } from "./elementCustomDataUtils";
@@ -84,7 +86,7 @@ export async function checkVersionMismatch(plugin: ExcalidrawPlugin) {
const result = await versionMismatchPrompt.start();
if (result) {
plugin.manifest.version = PLUGIN_VERSION;
await plugin.app.setting.open();
plugin.app.setting.open();
plugin.app.setting.openTabById("community-plugins");
}
}
@@ -1035,10 +1037,6 @@ export function fragWithHTML(html: string) {
return createFragment((frag) => frag.appendChild(sanitizedFragment(html)));
}
export async function sleep(ms: number) {
return new Promise((resolve) => window.setTimeout(resolve, ms));
}
/**REACT 18
//see also: https://github.com/zsviczian/obsidian-excalidraw-plugin/commit/b67d70c5196f30e2968f9da919d106ee66f2a5eb
//https://github.com/zsviczian/obsidian-excalidraw-plugin/commit/cc9d7828c7ee7755c1ef942519c43df32eae249f
@@ -1057,7 +1055,10 @@ export function _getContainerElement(
return null;
}
if (element.containerId) {
return getContainerElement(element, arrayToMap(scene.elements));
return (
getContainerElement(element, arrayToMap(scene.elements) as ElementsMap) ??
null
);
//return scene.elements.find((el:ExcalidrawElement)=>el.id === element.containerId) ?? null;
}
return null;
@@ -1112,7 +1113,7 @@ export function isContainer(el: ExcalidrawElement) {
export function hyperlinkIsImage(data: string): boolean {
if (!isHyperLink(data)) {
false;
return false;
}
const corelink = data.split("?")[0];
return IMAGE_TYPES.contains(
@@ -1228,16 +1229,6 @@ export async function getYouTubeThumbnailLink(
return `${URLs.I_YTIMG_COM}/${videoId}/default.jpg`;
}
export function isCallerFromTemplaterPlugin(stackTrace: string) {
const lines = stackTrace.split("\n");
for (const line of lines) {
if (line.trim().startsWith("at Templater.")) {
return true;
}
}
return false;
}
export function convertSVGStringToElement(svg: string): SVGSVGElement {
const parser = new DOMParser();
const doc = parser.parseFromString(makeEntitiesXmlSafe(svg), "image/svg+xml");
@@ -1247,12 +1238,12 @@ export function convertSVGStringToElement(svg: string): SVGSVGElement {
}
const root = doc.documentElement;
if (root instanceof SVGSVGElement) {
if (isInstanceOfSVGSVGElement(root)) {
return root;
}
const nestedSvg = doc.querySelector("svg");
if (nestedSvg instanceof SVGSVGElement) {
if (isInstanceOfSVGSVGElement(nestedSvg)) {
return nestedSvg;
}
}
+7 -4
View File
@@ -7,7 +7,7 @@ import { isUnwantedLeaf, setExcalidrawView } from "src/utils/obsidianUtils";
export async function switchToExcalidraw(app: App) {
const leaves = app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW_LOADING);
for (const leaf of leaves) {
await (leaf.view as ExcalidrawLoading)?.switchToeExcalidraw();
await (leaf.view as ExcalidrawLoading)?.switchToExcalidraw();
}
}
@@ -24,11 +24,14 @@ export class ExcalidrawLoading extends FileView {
this.displayLoadingText();
}
public async switchToeExcalidraw() {
const prevLeaf = this.app.workspace.activeLeaf;
public async switchToExcalidraw() {
const prevLeaf = this.app.workspace.getLeaf();
await setExcalidrawView(this.leaf);
await sleep(100); // added this 2026.04.19 after instances where the hack did not seem to work, but wasn't able to reliably reproduce. This timeout does not seem to cause any issues and may help in cases where the hack was not working due to some sort of race condition
const activeLeaf = this.app.workspace.activeLeaf;
const activeLeaf = this.app.workspace.getLeaf();
if (!activeLeaf) {
return;
}
if (
prevLeaf === this.leaf &&
activeLeaf !== prevLeaf &&
+850 -724
View File
File diff suppressed because it is too large. Load diff
+72 -16
View File
@@ -24,6 +24,7 @@ import { EmbeddableMDCustomProps } from "src/shared/Dialogs/EmbeddableSettings";
import { EmbeddableLeafRef } from "src/types/excalidrawViewTypes";
import { t } from "src/lang/helpers";
import { removeStyle, setStyle } from "src/utils/styleUtils";
import { isInstanceOfHTMLElement } from "src/utils/typechecks";
type PdfViewLike = {
containerEl?: HTMLElement;
@@ -137,7 +138,7 @@ function setPDFViewTheme(view: ExcalidrawView, pdfView: PdfViewLike | null) {
const thumbnailViewEl = pdfView.containerEl?.querySelector(
".pdf-thumbnail-view",
);
if (thumbnailViewEl instanceof HTMLElement) {
if (isInstanceOfHTMLElement(thumbnailViewEl)) {
setStyle(thumbnailViewEl, {
filter: "var(--theme-filter)",
});
@@ -551,7 +552,7 @@ function RenderObsidianView({
canvasColor: string;
selectedElementId: string;
sceneZoom: number;
}): JSX.Element {
}): React.JSX.Element {
const { subpath, file } = processLinkText(linkText, view);
if (!file) {
@@ -571,12 +572,20 @@ function RenderObsidianView({
const pdfObserverDisabledRef = React.useRef(false);
const mobilePatchCleanupRef = React.useRef(null);
const initialViewFileRef = React.useRef(view.file);
const mdPropsRef = React.useRef(mdProps);
const fileRef = React.useRef(file);
const prevLockRef = React.useRef(mdProps?.lockedReadingMode);
// Update themeRef when theme changes
React.useEffect(() => {
themeRef.current = theme;
}, [theme]);
React.useEffect(() => {
mdPropsRef.current = mdProps;
fileRef.current = file;
}, [mdProps, file]);
//--------------------------------------------------------------------------------
//block propagation of events to the parent if the embeddable element is active
//--------------------------------------------------------------------------------
@@ -651,7 +660,7 @@ function RenderObsidianView({
const setKeepOnTop = () => {
const keepontop =
view.app.workspace.activeLeaf === view.leaf && DEVICE.isDesktop;
view.app.workspace.getMostRecentLeaf() === view.leaf && DEVICE.isDesktop;
if (keepontop) {
if (!view.ownerWindow.electronWindow.isAlwaysOnTop()) {
view.ownerWindow.electronWindow.setAlwaysOnTop(true);
@@ -694,6 +703,22 @@ function RenderObsidianView({
containerRef.current,
element.id,
);
// --- PATCH NATIVE OBSIDIAN CANVAS NODE ---
// Obsidian's native canvas event listeners will force the node into edit mode
// on certain clicks/double-clicks. This intercepts Obsidian's core method.
const node = leafRef.current.node;
if (node && typeof node.startEditing === "function") {
const originalStartEditing = node.startEditing;
node.startEditing = function (...args: unknown[]) {
// Read directly from the ref to ensure dynamic lock toggling works
if (mdPropsRef.current?.lockedReadingMode) {
return;
}
return originalStartEditing.apply(this, args) as unknown;
};
}
setColors(containerRef.current, element, mdProps, canvasColor, viewType);
view.updateEmbeddableLeafRef(element.id, leafRef.current);
viewTypeRef.current = "markdown";
@@ -838,7 +863,7 @@ function RenderObsidianView({
if (!mdProps) {
return;
}
if (!leafRef.current?.hasOwnProperty("node")) {
if (!Object.hasOwn(leafRef.current ?? {}, "node")) {
return;
}
@@ -867,9 +892,12 @@ function RenderObsidianView({
.stringHEX({ alpha: true })
: "transparent";
color === "transparent"
? canvasNode?.addClass("transparent")
: canvasNode?.removeClass("transparent");
if (color === "transparent") {
canvasNode?.addClass("transparent");
} else {
canvasNode?.removeClass("transparent");
}
if (canvasNode) {
setStyle(canvasNode, {
"--canvas-background": color,
@@ -892,9 +920,12 @@ function RenderObsidianView({
.alphaTo((mdProps.backgroundOpacity ?? 100) / 100)
.stringHEX({ alpha: true });
color === "transparent"
? canvasNode?.addClass("transparent")
: canvasNode?.removeClass("transparent");
if (color === "transparent") {
canvasNode?.addClass("transparent");
} else {
canvasNode?.removeClass("transparent");
}
if (canvasNode) {
setStyle(canvasNode, {
"--canvas-background": color,
@@ -1054,6 +1085,19 @@ function RenderObsidianView({
return;
}
const currentMdProps = mdPropsRef.current;
const currentFile = fileRef.current;
if (currentMdProps?.lockedReadingMode) {
// Special case: if the card is a back-of-the-note card, ticking a checkbox in
// reading mode triggers a change to the open file which would result in a view update.
if (currentFile?.path === view.file.path) {
view.setPreventReload();
void view.setEmbeddableNodeIsEditing();
}
return;
}
/*if(isActiveRef.current && leafRef.current?.leaf) {
setKeepOnTop();
view.app.workspace.setActiveLeaf(leafRef.current.leaf, { focus: true });
@@ -1167,7 +1211,10 @@ function RenderObsidianView({
activeEmbeddable?.element.id === element.id &&
activeEmbeddable?.state === "active";
if (previousIsActive === isActiveRef.current) {
const lockChanged = prevLockRef.current !== mdProps?.lockedReadingMode;
prevLockRef.current = !!mdProps?.lockedReadingMode;
if (previousIsActive === isActiveRef.current && !lockChanged) {
return;
}
@@ -1183,13 +1230,21 @@ function RenderObsidianView({
view.plugin.settings.markdownNodeOneClickEditing &&
!containerRef.current?.hasClass("is-editing")
) {
//!node.isEditing
const newTheme = getTheme(view, themeRef.current);
containerRef.current?.addClasses(["is-editing", "is-focused"]);
void view.canvasNodeFactory.startEditing(node, newTheme);
if (mdPropsRef.current?.lockedReadingMode) {
if (fileRef.current?.path === view.file.path) {
view.setPreventReload();
void view.setEmbeddableNodeIsEditing();
}
} else {
//!node.isEditing
const newTheme = getTheme(view, themeRef.current);
containerRef.current?.addClasses(["is-editing", "is-focused"]);
void view.canvasNodeFactory.startEditing(node, newTheme);
}
} else {
containerRef.current?.removeClasses(["is-editing", "is-focused"]);
view.canvasNodeFactory.stopEditing(node);
view.clearEmbeddableNodeIsEditing();
}
return;
}
@@ -1238,12 +1293,13 @@ function RenderObsidianView({
activeEmbeddable?.state,
isActiveRef,
activeEmbeddable?.element,
activeEmbeddable?.state,
element,
view,
isEditingRef,
view.canvasNodeFactory,
themeRef.current,
mdProps?.lockedReadingMode,
file.path,
]);
return null;
@@ -26,7 +26,10 @@ import {
} from "src/utils/customEmbeddableUtils";
import { getActivePDFPageNumberFromPDFView } from "src/utils/obsidianUtils";
import { cleanSectionHeading } from "src/utils/pathUtils";
import { EmbeddableSettings } from "src/shared/Dialogs/EmbeddableSettings";
import {
EmbeddableSettings,
EmbeddableMDCustomProps,
} from "src/shared/Dialogs/EmbeddableSettings";
import {
insertImageToView,
openExternalLink,
@@ -35,6 +38,7 @@ import { getEA } from "src/core";
import { CaptureUpdateAction } from "src/constants/constants";
import { URLs } from "src/constants/safeUrls";
import { setStyle } from "src/utils/styleUtils";
import { addAppendUpdateCustomData } from "src/utils/elementCustomDataUtils";
type BlockCacheEntry = Awaited<
ReturnType<ExcalidrawView["app"]["metadataCache"]["blockCache"]["getForFile"]>
@@ -109,7 +113,9 @@ export class EmbeddableMenu {
const app = view.app;
element = view.excalidrawAPI
.getSceneElements()
.find((e: ExcalidrawElement) => e.id === element.id);
.find(
(e: ExcalidrawElement) => e.id === element.id,
) as ExcalidrawEmbeddableElement;
if (!element) {
return;
}
@@ -364,6 +370,46 @@ export class EmbeddableMenu {
);
}
private async actionToggleLockReadingMode(
element: ExcalidrawEmbeddableElement,
) {
if (!element) {
return;
}
const mdProps =
(element.customData?.mdProps as EmbeddableMDCustomProps) ??
this.view.plugin.settings.embeddableMarkdownDefaults;
const isLocked = !!mdProps.lockedReadingMode;
mdProps.lockedReadingMode = !isLocked;
const ea = getEA(this.view);
ea.copyViewElementsToEAforEditing([element]);
const eaEl = ea.getElement(element.id);
addAppendUpdateCustomData(eaEl, mdProps);
await ea.addElementsToView();
ea.destroy();
// Fetch the updated element reference from the scene
const api = this.view.excalidrawAPI;
const updatedElement = api
.getSceneElements()
.find(
(e: ExcalidrawElement) => e.id === element.id,
) as ExcalidrawEmbeddableElement;
// Force an appState update so the React menu component re-renders
if (updatedElement) {
this.view.updateScene({
appState: {
activeEmbeddable: {
element: updatedElement,
state: "active",
},
},
});
}
}
private actionProperties(element: ExcalidrawEmbeddableElement, file: TFile) {
if (!element) {
return;
@@ -472,6 +518,10 @@ export class EmbeddableMenu {
);
const top = `${y - 2.5 * ROOTELEMENTSIZE - appState.offsetTop}px`;
const left = `${x - appState.offsetLeft}px`;
const mdProps =
(element.customData?.mdProps as EmbeddableMDCustomProps) ??
view.plugin.settings.embeddableMarkdownDefaults;
const isLockedReadingMode = !!mdProps.lockedReadingMode;
return (
<div
@@ -497,8 +547,8 @@ export class EmbeddableMenu {
<ActionButton
key={"MarkdownSection"}
title={t("PIN_VIEW")}
action={async () =>
this.actionBaseViewSelection(file, subpath, element)
action={() =>
void this.actionBaseViewSelection(file, subpath, element)
}
icon={ICONS.ZoomToSection}
/>
@@ -507,8 +557,8 @@ export class EmbeddableMenu {
<ActionButton
key={"MarkdownSection"}
title={t("NARROW_TO_HEADING")}
action={async () =>
this.actionMarkdownSelection(
action={() =>
void this.actionMarkdownSelection(
file,
isExcalidrawFile,
subpath,
@@ -522,12 +572,24 @@ export class EmbeddableMenu {
<ActionButton
key={"MarkdownBlock"}
title={t("NARROW_TO_BLOCK")}
action={async () =>
this.actionMarkdownBlock(file, subpath, element)
action={() =>
void this.actionMarkdownBlock(file, subpath, element)
}
icon={ICONS.ZoomToBlock}
/>
)}
{isMD && (
<ActionButton
key="LockReadingMode"
title={
isLockedReadingMode
? t("UNLOCK_READING_MODE")
: t("LOCK_READING_MODE")
}
action={() => void this.actionToggleLockReadingMode(element)}
icon={isLockedReadingMode ? ICONS.Edit : ICONS.Read}
/>
)}
<ActionButton
key={"ZoomToElement"}
title={t("ZOOM_TO_FIT")}
@@ -557,7 +619,9 @@ export class EmbeddableMenu {
<ActionButton
key={"Camera"}
title={t("CAPTURE_PAGE")}
action={() => this.actionInsertPageAsImage(element)}
action={() => {
void this.actionInsertPageAsImage(element);
}}
icon={ICONS.Camera}
/>
</>
@@ -568,9 +632,11 @@ export class EmbeddableMenu {
}
}
if (isObsidianiFrame || isExcalidrawiFrame) {
const iframe = isExcalidrawiFrame
? api.getHTMLIFrameElement(element.id)
: view.getEmbeddableElementById(element.id);
const iframe = (
isExcalidrawiFrame
? api.getHTMLIFrameElement(element.id)
: view.getEmbeddableElementById(element.id)
) as HTMLIFrameElement;
if (!iframe || !iframe.contentWindow) {
return null;
}
+36 -15
View File
@@ -16,15 +16,28 @@ import { UniversalInsertFileModal } from "src/shared/Dialogs/UniversalInsertFile
import { t } from "src/lang/helpers";
import { getExcalidrawViews } from "src/utils/obsidianUtils";
import { CaptureUpdateAction } from "src/constants/constants";
import { getAppStateStrokeWidthEntry, getFreedrawStrokeWidthByKey } from "src/utils/excalidrawAutomateUtils";
export function setPen(pen: PenStyle, api: ExcalidrawImperativeAPI) {
const st = api.getAppState();
const strokeWidthEntry =
!pen.strokeWidth || pen.strokeWidth === 0
? {}
: getAppStateStrokeWidthEntry(undefined, pen.strokeWidth);
const currentItemStrokeWidthKey =
"currentItemStrokeWidthKey" in strokeWidthEntry
? strokeWidthEntry.currentItemStrokeWidthKey
: null;
const currentItemStrokeWidth =
"currentItemStrokeWidth" in strokeWidthEntry
? strokeWidthEntry.currentItemStrokeWidth
: null;
api.updateScene({
appState: {
currentStrokeOptions: pen.penOptions,
...(!pen.strokeWidth || pen.strokeWidth === 0
? null
: { currentItemStrokeWidth: pen.strokeWidth }),
currentItemStrokeWidthKey,
currentItemStrokeWidth,
currentItemStrokeVariability: pen.penOptions.constantPressure ? "constant" : "variable",
...(pen.backgroundColor
? { currentItemBackgroundColor: pen.backgroundColor }
: null),
@@ -38,7 +51,9 @@ export function setPen(pen: PenStyle, api: ExcalidrawImperativeAPI) {
...(pen.freedrawOnly && !st.resetCustomPen //switching from custom pen to next custom pen
? {
resetCustomPen: {
currentItemStrokeWidthKey: st.currentItemStrokeWidthKey,
currentItemStrokeWidth: st.currentItemStrokeWidth,
currentItemStrokeVariability: st.currentItemStrokeVariability,
currentItemBackgroundColor: st.currentItemBackgroundColor,
currentItemStrokeColor: st.currentItemStrokeColor,
currentItemFillStyle: st.currentItemFillStyle,
@@ -56,16 +71,21 @@ export function resetStrokeOptions(
api: ExcalidrawImperativeAPI,
clearCurrentStrokeOptions: boolean,
) {
const appState = api.getAppState();
api.updateScene({
appState: {
...(resetCustomPen
? {
currentItemStrokeWidth: resetCustomPen.currentItemStrokeWidth,
currentItemStrokeWidthKey:
resetCustomPen.currentItemStrokeWidthKey,
currentItemStrokeWidth:
resetCustomPen.currentItemStrokeWidth,
currentItemBackgroundColor:
resetCustomPen.currentItemBackgroundColor,
currentItemStrokeColor: resetCustomPen.currentItemStrokeColor,
currentItemFillStyle: resetCustomPen.currentItemFillStyle,
currentItemRoughness: resetCustomPen.currentItemRoughness,
currentItemStrokeVariability: resetCustomPen.currentItemStrokeVariability,
}
: null),
resetCustomPen: null,
@@ -77,7 +97,7 @@ export function resetStrokeOptions(
export class ObsidianMenu {
private clickTimestamp: number[];
private activePen: PenStyle;
private activePens: Record<number, PenStyle> = {};
private longpressTimeout: { [key: number]: number } = {};
private prevClickTimestamp: number = 0;
constructor(
@@ -119,8 +139,8 @@ export class ObsidianMenu {
}
//apply pen settings to canvas
this.activePen = { ...pen };
setPen(pen, api);
this.activePens[index] = this.activePens[index] ?? { ...pen };
setPen(this.activePens[index], api);
api.setActiveTool({ type: "freedraw" });
}
@@ -223,22 +243,23 @@ export class ObsidianMenu {
pen.freedrawOnly
) {
window.setTimeout(() =>
setPen(this.activePen, this.view.excalidrawAPI),
setPen(this.activePens[index] ?? pen, this.view.excalidrawAPI),
);
}
if (
this.activePen &&
appState.resetCustomPen &&
appState.activeTool.type === "freedraw" &&
appState.currentStrokeOptions === pen.penOptions &&
pen.freedrawOnly
) {
this.activePen.strokeWidth = appState.currentItemStrokeWidth;
this.activePen.backgroundColor = appState.currentItemBackgroundColor;
this.activePen.strokeColor = appState.currentItemStrokeColor;
this.activePen.fillStyle = appState.currentItemFillStyle;
this.activePen.roughness = appState.currentItemRoughness;
const activePen = this.activePens[index] ?? { ...pen };
activePen.strokeWidth = getFreedrawStrokeWidthByKey(appState.currentItemStrokeWidthKey, appState.currentItemStrokeWidth);
activePen.backgroundColor = appState.currentItemBackgroundColor;
activePen.strokeColor = appState.currentItemStrokeColor;
activePen.fillStyle = appState.currentItemFillStyle;
activePen.roughness = appState.currentItemRoughness;
this.activePens[index] = activePen;
}
return (
@@ -354,7 +375,7 @@ export class ObsidianMenu {
this.view.ownerWindow.clearTimeout(t),
);
this.longpressTimeout = {};
this.activePen = null;
this.activePens = {};
this.plugin = null;
this.toolsRef = null;
this.view = null;
+16 -17
View File
@@ -40,6 +40,8 @@ import { ScriptEngine } from "src/shared/Scripts";
import { UniversalInsertFileModal } from "src/shared/Dialogs/UniversalInsertFileModal";
import { Position } from "src/types/excalidrawViewTypes";
import { setStyle } from "src/utils/styleUtils";
import { ObsidianDraggable } from "src/types/types";
import type React from "react";
/*
static getDropAction(event: DragEvent): string {
@@ -117,7 +119,8 @@ export class DropManager {
{ clientX: event.clientX, clientY: event.clientY },
st,
);
const draggable = this.app.dragManager.draggable;
const draggable = this.app.dragManager
.draggable as unknown as ObsidianDraggable;
const internalDragAction = internalDragModifierType(event);
const externalDragAction = webbrowserDragModifierType(event);
const localFileDragAction = localFileDragModifierType(event);
@@ -145,8 +148,8 @@ export class DropManager {
pointerPosition: this.currentPosition, //the pointer position on canvas at the time of drop
});
} catch (e) {
new Notice("on drop hook error. See console log for details");
errorlog({ where: "ExcalidrawView.onDrop", error: e });
new Notice("On drop hook error. See console log for details");
errorlog({ where: "ExcalidrawView.onDrop", error: e as unknown });
return false;
}
} else {
@@ -219,7 +222,7 @@ export class DropManager {
void (async () => {
if (["image", "image-fullsize"].contains(internalDragAction)) {
const ea: ExcalidrawAutomate = getEA(this.view);
ea.canvas.theme = api.getAppState().theme;
ea.canvas.theme = api.getAppState().theme as string;
let counter: number = 0;
const ids: string[] = [];
for (const f of draggable.files) {
@@ -361,7 +364,7 @@ export class DropManager {
this.currentPosition,
undefined,
src[1],
).then(ea.destroy);
).then(() => ea.destroy());
return false;
}
}
@@ -442,21 +445,17 @@ export class DropManager {
maybeFile.path
}`,
);
switch (action) {
case "Import":
break;
case "Overwrite":
if (action !== "Import") {
if (action === "Overwrite") {
await this.app.vault.modifyBinary(
maybeFile,
fileToImport,
);
// there is deliberately no break here
case "Use":
default:
const ea = getEA(this.view);
await insertImageToView(ea, pos, maybeFile);
ea.destroy();
return false;
}
const ea = getEA(this.view);
await insertImageToView(ea, pos, maybeFile);
ea.destroy();
return false;
}
}
const file = await importFileToVault(
@@ -497,7 +496,7 @@ export class DropManager {
ea.destroy(),
);
if (localFileDragAction !== "embeddable") {
new Notice("Not imported to Vault. Embedded with local URI");
new Notice("Not imported to vault. Embedded with local uri.");
}
} else {
const ea = getEA(this.view);
+1 -1
View File
@@ -423,7 +423,7 @@ export class ExcalidrawSidepanelView extends ItemView {
* Restores persisted tabs on startup without revealing the panel, executing scripts to rebuild content.
*/
private async restorePersistedTabs(): Promise<void> {
if (this.restorePromise) {
if (this.restorePromise !== null) {
return this.restorePromise;
}
this.restorePromise = (async () => {
+69 -128
View File
@@ -2,15 +2,15 @@
height: 100%;
margin: 0px;
background-color: var(--background-primary);
position:relative;
position: relative;
}
.block-language-excalidraw {
text-align:center;
text-align: center;
}
svg.excalidraw-svg {
width: 100%;
width: 100%;
}
.excalidraw-embedded-img {
@@ -50,7 +50,7 @@ div.excalidraw-svg-left {
}
button.ToolIcon_type_button[title="Export"] {
display:none;
display: none;
}
.excalidraw-prompt-div {
@@ -104,8 +104,8 @@ button.ToolIcon_type_button[title="Export"] {
}
.ex-coffee-div {
text-align: center;
margin-bottom: 10px;
text-align: center;
margin-bottom: 10px;
}
.excalidraw-mastery-promo {
@@ -196,7 +196,7 @@ button.ToolIcon_type_button[title="Export"] {
.excalidraw-scriptengine-install td>img {
width: 100%;
max-width:800px;
max-width: 800px;
}
.excalidraw-scriptengine-install img.coffee {
@@ -227,7 +227,7 @@ button.ToolIcon_type_button[title="Export"] {
}
.excalidraw-scriptengine-install .modal {
max-height:90%;
max-height: 90%;
width: auto;
}
@@ -250,18 +250,20 @@ button.ToolIcon_type_button[title="Export"] {
}
.workspace-leaf-content .excalidraw-view {
padding: 0px 1px; /*1px so on ipad swipe in from left and right still works*/
padding: 0px 1px;
/*1px so on ipad swipe in from left and right still works*/
overflow: hidden;
}
.excalidraw-videoWrapper {
max-width:600px;
}
.excalidraw-videoWrapper.settings {
max-width:340px;
max-width: 600px;
}
.excalidraw-videoWrapper div{
.excalidraw-videoWrapper.settings {
max-width: 340px;
}
.excalidraw-videoWrapper div {
position: relative;
padding-bottom: 56.25%;
height: 0;
@@ -281,7 +283,7 @@ button.ToolIcon_type_button[title="Export"] {
height: 100%;
}
.excalidraw-release .modal-content{
.excalidraw-release .modal-content {
padding-right: 5px;
margin-right: -5px;
user-select: text;
@@ -293,7 +295,7 @@ button.ToolIcon_type_button[title="Export"] {
}
.excalidraw-scriptengine-install tbody>tr>td>div>img {
height:20px;
height: 20px;
background-color: silver;
padding: 2px;
}
@@ -318,7 +320,7 @@ button.ToolIcon_type_button[title="Export"] {
position: absolute;
padding: 12px;
border-radius: 10px;
box-shadow: 0 8px 24px rgba(0,0,0,0.25);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);
background-color: var(--background-primary);
border: 1px solid var(--background-modifier-border);
z-index: 9999;
@@ -347,7 +349,7 @@ textarea.excalidraw-wysiwyg {
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
border-radius: 0;
border-radius: 0;
}
.is-tablet .excalidraw button,
@@ -356,11 +358,6 @@ textarea.excalidraw-wysiwyg {
height: 1.8rem;
}
.excalidraw-hidden,
.excalidraw-display-none {
display: none !important;
}
.excalidraw-display-flex {
display: flex;
}
@@ -378,7 +375,7 @@ textarea.excalidraw-wysiwyg {
background: var(--background-primary-alt);
}
.excalidraw-ai-provider-table > .setting-item {
.excalidraw-ai-provider-table>.setting-item {
margin-top: 0;
margin-bottom: 0;
padding-bottom: 0.5rem;
@@ -396,7 +393,7 @@ textarea.excalidraw-wysiwyg {
min-height: 0;
}
.excalidraw-ai-provider-table__row + .excalidraw-ai-provider-table__row {
.excalidraw-ai-provider-table__row+.excalidraw-ai-provider-table__row {
border-top: 1px solid var(--background-modifier-border);
}
@@ -506,7 +503,8 @@ div.excalidraw-draginfo {
padding: 0.5rem;
}
.excalidraw-sidepanel-tab__button { /* probably unused */
.excalidraw-sidepanel-tab__button {
/* probably unused */
display: inline-flex;
align-items: center;
gap: 0.35rem;
@@ -680,7 +678,7 @@ img.excalidraw-cropped-pdfpage,
opacity: 0;
}
.popover .excalidraw-svg {
.popover .excalidraw-svg {
width: 100%;
max-width: inherit;
height: 100%;
@@ -688,24 +686,26 @@ img.excalidraw-cropped-pdfpage,
}
root {
--excalidraw-caret-color: initial;
--excalidraw-caret-color: initial;
}
.excalidraw-settings-links-container {
align-items: center;
color: inherit;
display: flex;
gap: .3em;
text-align: center;
text-decoration: none;
flex-wrap: wrap;
justify-content: center;
flex-direction: row;
align-items: center;
color: inherit;
display: flex;
gap: .3em;
text-align: center;
text-decoration: none;
flex-wrap: wrap;
justify-content: center;
flex-direction: row;
}
.excalidraw-settings-links-container a {
display: flex; /* Align children horizontally */
align-items: center; /* Center items vertically */
display: flex;
/* Align children horizontally */
align-items: center;
/* Center items vertically */
text-align: left;
margin-right: 4px;
margin-left: 4px;
@@ -761,19 +761,14 @@ root {
margin-bottom: -2px;
}
.is-mobile .modal-container.excalidraw-modal .modal.excalidraw-modal {
align-self: flex-start;
transform: none !important;
margin-top: calc(var(--safe-area-inset-top) + var(--header-height) + var(--size-4-2));
width: 100%;
}
.excalidraw-prompt-buttonbar-top,
.excalidraw-prompt-buttonbar-bottom {
display: flex;
flex-wrap: wrap;
align-items: flex-start; /* keep both rows top‐aligned */
row-gap: 0.5em; /* vertical space when wrapped */
align-items: flex-start;
/* keep both rows top‐aligned */
row-gap: 0.5em;
/* vertical space when wrapped */
}
/* top bar specifics */
@@ -788,20 +783,20 @@ root {
}
/* make each child a flex row */
.excalidraw-prompt-buttonbar-top > div,
.excalidraw-prompt-buttonbar-bottom > div {
.excalidraw-prompt-buttonbar-top>div,
.excalidraw-prompt-buttonbar-bottom>div {
display: flex;
}
/* push the first group to the left */
.excalidraw-prompt-buttonbar-top > div:first-child,
.excalidraw-prompt-buttonbar-bottom > div:first-child {
.excalidraw-prompt-buttonbar-top>div:first-child,
.excalidraw-prompt-buttonbar-bottom>div:first-child {
margin-right: auto;
}
/* push the second group to the right */
.excalidraw-prompt-buttonbar-top > div:last-child,
.excalidraw-prompt-buttonbar-bottom > div:last-child {
.excalidraw-prompt-buttonbar-top>div:last-child,
.excalidraw-prompt-buttonbar-bottom>div:last-child {
margin-left: auto;
}
@@ -810,7 +805,7 @@ root {
flex-direction: column;
background: var(--background-secondary);
border-radius: 8px;
box-shadow: 0 1px 4px 0 rgba(0,0,0,0.10);
box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.10);
padding: 0.5em 0.8em;
margin-bottom: 0.5em;
max-width: calc(100% - 1.6em);
@@ -885,7 +880,8 @@ root {
justify-content: center;
}
.excalidraw-search .document-search-button:hover, .excalidraw-search .document-search-button:focus {
.excalidraw-search .document-search-button:hover,
.excalidraw-search .document-search-button:focus {
background: var(--background-modifier-hover);
color: var(--text-accent);
}
@@ -898,69 +894,8 @@ root {
pointer-events: none;
}
.excalidraw-LatexPrompt {
.cm-editor {
margin-top: var(--size-4-2);
justify-content: center;
align-items: center;
/* this is safe, if unsupported, will be ignored */
anchor-name: --latex-editor;
& > .cm-scroller, & > .cm-announcment {
align-self: start;
width: 100%
}
/* taken from Obsidian, doesn't apply automatically,
because the rule does not have :focus-within */
&.cm-focused {
border-color: var(--background-modifier-border-focus);
transition: box-shadow 0.15s ease-in-out, border 0.15s ease-in-out;
box-shadow: 0 0 0 var(--input-border-width-focus) var(--background-modifier-border-focus);
}
/* centering the popup */
& .cm-tooltip-cursor.cm-tooltip {
left: unset !important;
& .cm-tooltip-arrow {
left: 50% !important;
transform: translateX(-50%);
}
}
[jax="CHTML"][display="true"] {
margin: 0;
}
}
.cm-content {
caret-color: var(--caret-color);
}
}
@supports (anchor-name: --test) {
.excalidraw-LatexPrompt .cm-editor .cm-tooltip-cursor.cm-tooltip {
position: fixed !important;
position-anchor: --latex-editor;
top: unset !important;
max-width: calc(100vw - var(--size-4-4));
margin: var(--size-4-2) 0;
overflow-x: clip;
&.cm-tooltip-above {
bottom: anchor(top);
}
&.cm-tooltip-below {
top: anchor(bottom) !important;
}
}
}
.excalidraw-filetype-tag {
order: 99;
order: 99;
}
.excalidraw-mobile-navbar-docked {
@@ -975,16 +910,16 @@ root {
Obsidian Sheets Plus support
*/
.excalidraw__embeddable__outer .lj-content-view {
width: var(--embeddable-width);
height: var(--embeddable-height);
width: var(--embeddable-width);
height: var(--embeddable-height);
}
.excalidraw__embeddable__outer #sheet-box {
height: calc(var(--embeddable-height) - var(--lj-toolbar-height) + 40px);
height: calc(var(--embeddable-height) - var(--lj-toolbar-height) + 40px);
}
.excalidraw__embeddable__outer .lj-univer .univer-relative.univer-grid {
width: var(--embeddable-width);
width: var(--embeddable-width);
}
/*
@@ -997,16 +932,18 @@ End Obsidian Sheets Plus support
}
.excalidraw-button-bgcolor {
&-normal {
background-color: var(--interactive-normal);
&-normal {
background-color: var(--interactive-normal);
color: var(--text-normal);
}
&-accent {
background-color: var(--interactive-accent);
&-accent {
background-color: var(--interactive-accent);
color: var(--text-on-accent);
}
&-success {
background-color: var(--interactive-success);
&-success {
background-color: var(--interactive-success);
color: var(--text-on-success);
}
}
@@ -1106,3 +1043,7 @@ End Obsidian Sheets Plus support
width: 100%;
cursor: move;
}
.excalidraw .App-bottom-bar .App-toolbar {
min-width: 12.8em;
}