mirror of
https://github.com/zsviczian/obsidian-excalidraw-plugin.git
synced 2026-12-03 06:43:35 +00:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aea9461ad0 | ||
|
|
16369deb00 | ||
|
|
1c04f1b483 | ||
|
|
214c7f5a47 | ||
|
|
f81ab8b3eb | ||
|
|
2f2dee5295 | ||
|
|
57c18446e1 | ||
|
|
7b49bded34 | ||
|
|
cf916b0da9 | ||
|
|
d4a99e86a8 | ||
|
|
c024f1cfa3 | ||
|
|
3c95990d7a | ||
|
|
b225dd77fe | ||
|
|
08bbe656ff | ||
|
|
395b9591bd | ||
|
|
3137ebc08b |
No files matched your search
@@ -37,6 +37,91 @@ Use https://github.com/obsidian-typings/obsidian-typings as a reference when dea
|
||||
|
||||
Treat build code and runtime code as one system.
|
||||
|
||||
## Project overview
|
||||
|
||||
- Target: Obsidian Community Plugin (TypeScript → bundled JavaScript).
|
||||
- Entry point: `src/main.ts` compiled to `main.js` and loaded by Obsidian.
|
||||
- Required release artifacts: `main.js`, `manifest.json`, and optional `styles.css`.
|
||||
|
||||
## Environment & tooling
|
||||
|
||||
- Node.js: use current LTS (Node 22+).
|
||||
- **Package manager: npm** (required for this sample - `package.json` defines npm scripts and dependencies).
|
||||
- **Bundler: esbuild** (required for this sample - `esbuild.config.mjs` and build scripts depend on it). Alternative bundlers like Rollup or webpack are acceptable for other projects if they bundle all external dependencies into `main.js`.
|
||||
- Types: `obsidian` type definitions.
|
||||
|
||||
## Linting
|
||||
|
||||
- ESLint is preconfigured with `eslint-plugin-obsidianmd` for Obsidian-specific rules.
|
||||
- Run `npm run lint` to lint the project.
|
||||
- A GitHub Action automatically lints every commit on all branches.
|
||||
|
||||
## Security, privacy, and compliance
|
||||
|
||||
Follow Obsidian's **Developer Policies** and **Plugin Guidelines**. In particular:
|
||||
|
||||
- Default to local/offline operation. Only make network requests when essential to the feature.
|
||||
- No hidden telemetry. If you collect optional analytics or call third-party services, require explicit opt-in and document clearly in `README.md` and in settings.
|
||||
- Never execute remote code, fetch and eval scripts, or auto-update plugin code outside of normal releases.
|
||||
- Minimize scope: read/write only what's necessary inside the vault. Do not access files outside the vault.
|
||||
- Clearly disclose any external services used, data sent, and risks.
|
||||
- Respect user privacy. Do not collect vault contents, filenames, or personal information unless absolutely necessary and explicitly consented.
|
||||
- Avoid deceptive patterns, ads, or spammy notifications.
|
||||
- Register and clean up all DOM, app, and interval listeners using the provided `register*` helpers so the plugin unloads safely.
|
||||
|
||||
## UX & copy guidelines (for UI text, commands, settings)
|
||||
|
||||
- Prefer sentence case for headings, buttons, and titles.
|
||||
- Use clear, action-oriented imperatives in step-by-step copy.
|
||||
- Use **bold** to indicate literal UI labels. Prefer "select" for interactions.
|
||||
- Use arrow notation for navigation: **Settings → Community plugins**.
|
||||
- Keep in-app strings short, consistent, and free of jargon.
|
||||
|
||||
## Performance
|
||||
|
||||
- Keep startup light. Defer heavy work until needed.
|
||||
- Avoid long-running tasks during `onload`; use lazy initialization.
|
||||
- Batch disk access and avoid excessive vault scans.
|
||||
- Debounce/throttle expensive operations in response to file system events.
|
||||
|
||||
## Coding conventions
|
||||
|
||||
- TypeScript with `"strict": true` preferred.
|
||||
- **Keep `main.ts` minimal**: Focus only on plugin lifecycle (onload, onunload, addCommand calls). Delegate all feature logic to separate modules.
|
||||
- **Split large files**: If any file exceeds ~200-300 lines, consider breaking it into smaller, focused modules.
|
||||
- **Use clear module boundaries**: Each file should have a single, well-defined responsibility.
|
||||
- Bundle everything into `main.js` (no unbundled runtime deps).
|
||||
- Avoid Node/Electron APIs if you want mobile compatibility; set `isDesktopOnly` accordingly.
|
||||
- Prefer `async/await` over promise chains; handle errors gracefully.
|
||||
|
||||
## Mobile
|
||||
|
||||
- Don't assume desktop-only behavior unless `isDesktopOnly` is `true`.
|
||||
- Avoid large in-memory structures; be mindful of memory and storage constraints.
|
||||
|
||||
## Agent do/don't
|
||||
|
||||
**Do**
|
||||
|
||||
- Add commands with stable IDs (don't rename once released).
|
||||
- Provide defaults and validation in settings.
|
||||
- Write idempotent code paths so reload/unload doesn't leak listeners or intervals.
|
||||
- Use `this.register*` helpers for everything that needs cleanup.
|
||||
|
||||
**Don't**
|
||||
|
||||
- Introduce network calls without an obvious user-facing reason and documentation.
|
||||
- Ship features that require cloud services without clear disclosure and explicit opt-in.
|
||||
- Store or transmit vault contents unless essential and consented.
|
||||
|
||||
## References
|
||||
|
||||
- Obsidian sample plugin: https://github.com/obsidianmd/obsidian-sample-plugin
|
||||
- API documentation: https://docs.obsidian.md
|
||||
- Developer policies: https://docs.obsidian.md/Developer+policies
|
||||
- Plugin guidelines: https://docs.obsidian.md/Plugins/Releasing/Plugin+guidelines
|
||||
- Style guide: https://help.obsidian.md/style-guide
|
||||
|
||||
## Repository Map
|
||||
|
||||
### Runtime Source
|
||||
@@ -583,4 +668,4 @@ When you are asked to modify this repository:
|
||||
|
||||
- All types and helpers for Excalidraw element `customData` (extensible metadata on elements, e.g., for LaTeX, PDF, image, or plugin-specific keys) are centralized in `src/utils/elementCustomDataUtils.ts`.
|
||||
- If you need to add a new `customData` key, type, or helper, always add it to this file and import from here in all consumers. This avoids type duplication and ensures discoverability for future maintainers and agents.
|
||||
- See `ExcalidrawCustomData`, `ExcalidrawCustomDataPatch`, `ExcalidrawPDFCustomData`, `ExcalidrawLatexCustomData`, and `addAppendUpdateCustomData` in that file for canonical patterns.
|
||||
- See `ExcalidrawCustomData`, `ExcalidrawCustomDataPatch`, `ExcalidrawPDFCustomData`, `ExcalidrawLatexCustomData`, and `addAppendUpdateCustomData` in that file for canonical patterns.
|
||||
@@ -1321,6 +1321,22 @@ export declare class ExcalidrawAutomate {
|
||||
autoexportConfig: AutoexportConfig;
|
||||
excalidrawFile: TFile;
|
||||
}) => AutoexportConfig | null;
|
||||
/**
|
||||
* If set, this callback is triggered when the scene changes in the target view.
|
||||
* You can use this to react to appState or element changes.
|
||||
* Any script can sign up for updates via this hook.
|
||||
* Because this hook fires extremely frequently (on every mouse move during drawing),
|
||||
* you MUST specify which appState keys you are interested in OR set trackElements to true.
|
||||
* If trackElements is falsy and appStateKeys is empty or undefined, the callback will NOT be triggered to prevent performance issues.
|
||||
* For sidepanel tabs, there is an additional filter feature: if triggerWhenInvisible is false,
|
||||
* the callback will only trigger when the sidepanel is visible and the tab is active.
|
||||
*/
|
||||
onSceneChangeHook: {
|
||||
appStateKeys?: (keyof AppState)[];
|
||||
trackElements?: boolean;
|
||||
triggerWhenInvisible?: boolean;
|
||||
callback: (elements: readonly ExcalidrawElement[], appState: AppState, files: BinaryFiles, view: ExcalidrawView, ea: ExcalidrawAutomate) => void;
|
||||
} | null;
|
||||
/**
|
||||
* if set, this callback is triggered, when an Excalidraw file is opened
|
||||
* You can use this callback in case you want to do something additional when the file is opened.
|
||||
@@ -1738,6 +1754,8 @@ export interface SidepanelTab {
|
||||
getHostEA(): ExcalidrawAutomate;
|
||||
/** Returns whether the tab is currently visible in the UI */
|
||||
isVisible(): boolean;
|
||||
/** Returns whether the tab is the currently active tab in the sidepanel */
|
||||
isActiveTab(): boolean;
|
||||
}
|
||||
|
||||
/* ***************************** */
|
||||
@@ -2474,11 +2492,17 @@ export type ExcalidrawElbowArrowElement = Merge<ExcalidrawArrowElement, {
|
||||
*/
|
||||
endIsSpecial: boolean | null;
|
||||
}>;
|
||||
export type StrokeVariability = "variable" | "constant";
|
||||
export type StrokeOptions = Readonly<{
|
||||
variability: StrokeVariability;
|
||||
streamline: number;
|
||||
}>;
|
||||
export type ExcalidrawFreeDrawElement = _ExcalidrawElementBase & Readonly<{
|
||||
type: "freedraw";
|
||||
points: readonly LocalPoint[];
|
||||
pressures: readonly number[];
|
||||
simulatePressure: boolean;
|
||||
strokeOptions: StrokeOptions;
|
||||
}>;
|
||||
export type FileId = string & {
|
||||
_brand: "FileId";
|
||||
@@ -2768,9 +2792,11 @@ export interface AppState {
|
||||
currentItemStrokeColor: string;
|
||||
currentItemBackgroundColor: string;
|
||||
currentItemFillStyle: ExcalidrawElement["fillStyle"];
|
||||
currentItemStrokeWidth: number;
|
||||
currentItemStrokeWidth: number | undefined;
|
||||
currentItemStrokeWidthKey: StrokeWidthKey;
|
||||
currentItemStrokeStyle: ExcalidrawElement["strokeStyle"];
|
||||
currentItemRoughness: number;
|
||||
currentItemStrokeVariability: StrokeVariability;
|
||||
currentItemOpacity: number;
|
||||
currentItemFontFamily: FontFamilyValues;
|
||||
currentItemFontSize: number;
|
||||
@@ -3863,34 +3889,7 @@ declare class App extends React.Component<AppProps, AppState> {
|
||||
* 1 = 100% zoom, 2 = 200% zoom, 0.5 = 50% zoom
|
||||
*/
|
||||
value: number) => void;
|
||||
private cancelInProgressAnimation;
|
||||
scrollToContent: (
|
||||
/**
|
||||
* target to scroll to
|
||||
*
|
||||
* - string - id of element or group, or url containing elementLink
|
||||
* - ExcalidrawElement | ExcalidrawElement[] - element(s) objects
|
||||
*/
|
||||
target?: string | ExcalidrawElement | readonly ExcalidrawElement[], opts?: ({
|
||||
fitToContent?: boolean;
|
||||
fitToViewport?: never;
|
||||
viewportZoomFactor?: number;
|
||||
animate?: boolean;
|
||||
duration?: number;
|
||||
} | {
|
||||
fitToContent?: never;
|
||||
fitToViewport?: boolean;
|
||||
/** when fitToViewport=true, how much screen should the content cover,
|
||||
* between 0.1 (10%) and 1 (100%)
|
||||
*/
|
||||
viewportZoomFactor?: number;
|
||||
animate?: boolean;
|
||||
duration?: number;
|
||||
}) & {
|
||||
minZoom?: number;
|
||||
maxZoom?: number;
|
||||
canvasOffsets?: Offsets;
|
||||
}) => void;
|
||||
scrollToContent: (target?: string | ExcalidrawElement | readonly NonDeletedExcalidrawElement[], opts?: ScrollToContentOptions) => void;
|
||||
private maybeUnfollowRemoteUser;
|
||||
/** use when changing scrollX/scrollY/zoom based on user interaction */
|
||||
private translateCanvas;
|
||||
@@ -4048,6 +4047,7 @@ declare class App extends React.Component<AppProps, AppState> {
|
||||
private newImagePlaceholder;
|
||||
private handleLinearElementOnPointerDown;
|
||||
private getCurrentItemRoundness;
|
||||
private getCurrentItemStrokeWidth;
|
||||
private createGenericElementOnPointerDown;
|
||||
private createFrameElementOnPointerDown;
|
||||
private maybeCacheReferenceSnapPoints;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
+245
-28
@@ -67,7 +67,7 @@ The script assembles dynamic "New Section" labels contextualizing the timestamp
|
||||
7. Switches focus permanently to Note B and automatically executes `ea.viewZoomToElements()` centering the screen precisely on the newly built container.
|
||||
|
||||
```js*/
|
||||
|
||||
const VERSION = "v260629";
|
||||
const FRAME_MARGIN = 10;
|
||||
|
||||
if (!ea.verifyMinimumPluginVersion || !ea.verifyMinimumPluginVersion("2.23.8")) {
|
||||
@@ -150,17 +150,31 @@ const getLucideIconIds = () => {
|
||||
let suppressEscape = false;
|
||||
|
||||
class FolderSuggest extends ea.obsidian.AbstractInputSuggest {
|
||||
constructor(app, inputEl) {
|
||||
constructor(app, inputEl, state = null, originFolderPath = "/") {
|
||||
super(app, inputEl);
|
||||
this.inputEl = inputEl;
|
||||
this.state = state;
|
||||
this.originFolderPath = originFolderPath === "/" ? "" : originFolderPath;
|
||||
}
|
||||
getSuggestions(query) {
|
||||
const folders = app.vault.getAllLoadedFiles()
|
||||
let folders = app.vault.getAllLoadedFiles()
|
||||
.filter(f => f instanceof ea.obsidian.TFolder)
|
||||
.map(f => f.path);
|
||||
|
||||
// Filter and map paths relative to the current origin folder
|
||||
if (this.state && this.state.useRelativeFolder) {
|
||||
const prefix = this.originFolderPath ? this.originFolderPath + "/" : "";
|
||||
folders = folders.filter(p => p.startsWith(prefix) || p === this.originFolderPath);
|
||||
folders = folders.map(p => p === this.originFolderPath ? "" : p.substring(prefix.length));
|
||||
}
|
||||
|
||||
return folders.filter(p => p.toLowerCase().includes(query.toLowerCase()));
|
||||
}
|
||||
renderSuggestion(value, el) { el.setText(value); }
|
||||
renderSuggestion(value, el) {
|
||||
// Display an indicator for the current folder if left empty in relative mode
|
||||
const display = value === "" && this.state && this.state.useRelativeFolder ? "./ (Current Folder)" : value;
|
||||
el.setText(display || "/");
|
||||
}
|
||||
selectSuggestion(value) {
|
||||
this.inputEl.value = value;
|
||||
this.inputEl.dispatchEvent(new Event("input"));
|
||||
@@ -704,7 +718,7 @@ async function injectVisualFormat(target_ea, targetX, targetY, sectionRawText, t
|
||||
// Conditionally add dynamic links back to the originating element and (if applicable) the DNP
|
||||
let linkStr = "";
|
||||
if (embeddedElementId && ontologyAction && originFilePath) {
|
||||
linkStr += `(${ontologyAction}::[[${originFilePath}#^${embeddedElementId}]])`;
|
||||
linkStr += `(${ontologyAction}::[[${originFilePath}#^group=${embeddedElementId}]])`;
|
||||
}
|
||||
if (!isCurrentDNP) {
|
||||
const frameOntology = settings.frameOntology || "note";
|
||||
@@ -849,7 +863,7 @@ async function injectMarkdownFormat(file, target_ea, targetX, targetY, sectionRa
|
||||
if (embeddedElementId && ontologyAction && originFilePath) {
|
||||
const originFile = app.vault.getAbstractFileByPath(originFilePath);
|
||||
const originLinkpath = originFile ? getObsidianLinkpath(originFile, file.path) : originFilePath.replace(/\.md$/i, "");
|
||||
linkStr += ` (${ontologyAction}::[[${originLinkpath}#^${embeddedElementId}]])`;
|
||||
linkStr += ` (${ontologyAction}::[[${originLinkpath}#^group=${embeddedElementId}]])`;
|
||||
}
|
||||
if (!isCurrentDNP) {
|
||||
const frameOntology = settings.frameOntology || "note";
|
||||
@@ -1078,10 +1092,10 @@ async function injectIntoOriginView(originView, activeElement, format, actionTyp
|
||||
const isEmbeddable = actionType === "CAPTURE_HERE" || !isMarkdownImage;
|
||||
if (isEmbeddable) {
|
||||
// Markdown Format + Embeddable: Multiple links
|
||||
eaEl.link = `(${ontologyAction}:: [[${linkpath}#${refPath}]] [[${linkpath}#^${frameID}]])`;
|
||||
eaEl.link = `(${ontologyAction}:: [[${linkpath}#${refPath}]] [[${linkpath}#^group=${frameID}]])`;
|
||||
} else {
|
||||
// Markdown Format + Static Image: Element ID link only
|
||||
eaEl.link = `(${ontologyAction}:: [[${linkpath}#^${frameID}]])`;
|
||||
eaEl.link = `(${ontologyAction}:: [[${linkpath}#^group=${frameID}]])`;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1310,8 +1324,15 @@ async function start() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Set the folder from the modal box
|
||||
const targetFolder = (customFolder !== undefined && customFolder !== "") ? customFolder : opt.folder;
|
||||
// Set the folder from the modal box (and apply relative behaviors)
|
||||
let targetFolder = (customFolder !== undefined && customFolder !== "") ? customFolder : opt.folder;
|
||||
if (captureData.useRelativeFolder) {
|
||||
const baseFolder = originView.file.parent.path;
|
||||
if (baseFolder !== "/") {
|
||||
targetFolder = targetFolder ? `${baseFolder}/${targetFolder}` : baseFolder;
|
||||
}
|
||||
}
|
||||
|
||||
const folder = ea.obsidian.normalizePath(targetFolder);
|
||||
|
||||
// 3. Assemble WikiLink and File Path
|
||||
@@ -1343,13 +1364,13 @@ async function start() {
|
||||
}
|
||||
}
|
||||
|
||||
// Handle Existing File Conflict Workflow
|
||||
// Handle Existing File Conflict Workflow (Bypasses rename warning if type matches)
|
||||
if (fileTarget) {
|
||||
const existingType = await detectNoteType(fileTarget);
|
||||
const hasNoteType = existingType === noteType;
|
||||
const hasPrefix = opt.prefix ? fileTarget.basename.startsWith(opt.prefix) : true;
|
||||
|
||||
if (!hasNoteType || !hasPrefix) {
|
||||
if (!hasNoteType) {
|
||||
const conflictDecision = await resolveExistingFileConflict(fileTarget, hasNoteType, hasPrefix, opt.prefix);
|
||||
if (!conflictDecision) return;
|
||||
|
||||
@@ -1379,9 +1400,9 @@ async function start() {
|
||||
let folderPath = (opt.type === "folder") ? `${folder}/${cleanFilename}` : folder;
|
||||
const formattedFolderPath = folderPath ? folderPath.replace(/^\/+/, "") + "/" : "";
|
||||
|
||||
const format = app.vault.getConfig("newLinkFormat");
|
||||
const fmt = app.vault.getConfig("newLinkFormat");
|
||||
let linkpath = `${formattedFolderPath}${targetBasename}`;
|
||||
if (format === "shortest") {
|
||||
if (fmt === "shortest") {
|
||||
const matches = app.vault.getFiles().filter(f => f.basename === targetBasename);
|
||||
if (matches.length === 0) {
|
||||
linkpath = targetBasename;
|
||||
@@ -1399,7 +1420,7 @@ async function start() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 4. Create File if new (File exists in memory for linking)
|
||||
// 4. Create File if new
|
||||
const file = await ensureTargetFileExists(folder, cleanFilename, fname, opt, noteType);
|
||||
|
||||
if (actionType === "ADD_LINK_CREATE") {
|
||||
@@ -1546,15 +1567,19 @@ function buildCaptureFolderBox(contentEl, state) {
|
||||
.setName("Folder")
|
||||
.setDesc("Target directory for the note");
|
||||
|
||||
let folderInputComp;
|
||||
const currentFolderPath = ea.targetView ? ea.targetView.file.parent.path : "/";
|
||||
|
||||
folderSetting.addText(text => {
|
||||
state.ui.folderInput = text;
|
||||
folderInputComp = text;
|
||||
text.inputEl.style.width = "100%";
|
||||
|
||||
state.isProgrammaticUpdate = true;
|
||||
text.setValue(state.initialFolder);
|
||||
state.isProgrammaticUpdate = false;
|
||||
|
||||
new FolderSuggest(app, text.inputEl);
|
||||
new FolderSuggest(app, text.inputEl, state, currentFolderPath);
|
||||
|
||||
// Track manual edits by the user (ignoring programmatic setValue)
|
||||
text.inputEl.addEventListener("input", () => {
|
||||
@@ -1563,6 +1588,49 @@ function buildCaptureFolderBox(contentEl, state) {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Relative vs Absolute folder path toggle
|
||||
folderSetting.addExtraButton(btn => {
|
||||
state.ui.folderToggleBtn = btn;
|
||||
const updateIcon = () => {
|
||||
btn.setIcon(state.useRelativeFolder ? "folder-dot" : "folder-lock");
|
||||
btn.setTooltip(state.useRelativeFolder ? "In current folder or subfolder" : "Fixed absolute folder path");
|
||||
};
|
||||
updateIcon();
|
||||
|
||||
btn.onClick(() => {
|
||||
state.useRelativeFolder = !state.useRelativeFolder;
|
||||
settings.useRelativeFolder = state.useRelativeFolder; // Save global preference
|
||||
ea.setScriptSettings(settings);
|
||||
updateIcon();
|
||||
|
||||
// Handle path transformation automatically
|
||||
state.isProgrammaticUpdate = true;
|
||||
let currentVal = folderInputComp.getValue().trim();
|
||||
const prefix = currentFolderPath === "/" ? "" : currentFolderPath;
|
||||
|
||||
if (state.useRelativeFolder) {
|
||||
// Absolute to Relative
|
||||
if (currentVal === prefix) {
|
||||
folderInputComp.setValue("");
|
||||
} else if (currentVal.startsWith(prefix + "/")) {
|
||||
folderInputComp.setValue(currentVal.substring(prefix.length + 1));
|
||||
} else {
|
||||
folderInputComp.setValue(""); // Does not fall within current path, clear
|
||||
}
|
||||
} else {
|
||||
// Relative to Absolute
|
||||
if (currentVal === "") {
|
||||
folderInputComp.setValue(prefix);
|
||||
} else {
|
||||
folderInputComp.setValue(prefix ? `${prefix}/${currentVal}` : currentVal);
|
||||
}
|
||||
}
|
||||
|
||||
state.isProgrammaticUpdate = false;
|
||||
state.ui.folderInput.inputEl.dispatchEvent(new Event("input")); // Re-evaluate suggester
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function buildCaptureSearchBox(contentEl, state, callbacks) {
|
||||
@@ -1747,12 +1815,12 @@ function buildCaptureLinkTypeSelector(contentEl, state, callbacks) {
|
||||
state.selectedNoteType = selectedNoteType;
|
||||
}
|
||||
|
||||
const linkTypeRow = new ea.obsidian.Setting(contentEl).setName("Link Type");
|
||||
linkTypeRow.controlEl.addClass("link-type-row-control");
|
||||
const iconPreviewSpan = linkTypeRow.controlEl.createSpan();
|
||||
const noteTypeRow = new ea.obsidian.Setting(contentEl).setName("Type");
|
||||
noteTypeRow.controlEl.addClass("link-type-row-control");
|
||||
const iconPreviewSpan = noteTypeRow.controlEl.createSpan();
|
||||
state.ui.iconPreviewSpan = iconPreviewSpan;
|
||||
|
||||
linkTypeRow.addDropdown(dropdown => {
|
||||
noteTypeRow.addDropdown(dropdown => {
|
||||
state.ui.dropdownComponent = dropdown;
|
||||
noteTypeKeys.forEach(k => dropdown.addOption(k, k));
|
||||
dropdown.setValue(selectedNoteType);
|
||||
@@ -1772,6 +1840,11 @@ function buildCaptureLinkTypeSelector(contentEl, state, callbacks) {
|
||||
if (opt && opt.folder !== undefined && state.ui.folderInput) {
|
||||
state.isProgrammaticUpdate = true;
|
||||
state.ui.folderInput.setValue(opt.folder);
|
||||
state.useRelativeFolder = !!opt.useRelativeFolder;
|
||||
if (state.ui.folderToggleBtn) {
|
||||
state.ui.folderToggleBtn.setIcon(state.useRelativeFolder ? "folder-dot" : "folder-lock");
|
||||
state.ui.folderToggleBtn.setTooltip(state.useRelativeFolder ? "In current folder or subfolder" : "Fixed absolute folder path");
|
||||
}
|
||||
state.isProgrammaticUpdate = false;
|
||||
}
|
||||
}
|
||||
@@ -1780,7 +1853,7 @@ function buildCaptureLinkTypeSelector(contentEl, state, callbacks) {
|
||||
});
|
||||
|
||||
// Add a button to manually pull the target directory from the active Note Type
|
||||
linkTypeRow.addExtraButton(btn => {
|
||||
noteTypeRow.addExtraButton(btn => {
|
||||
state.ui.resetFolderBtn = btn;
|
||||
btn.setIcon("folder-sync")
|
||||
.setTooltip("Apply folder from selected Note Type")
|
||||
@@ -1789,12 +1862,54 @@ function buildCaptureLinkTypeSelector(contentEl, state, callbacks) {
|
||||
if (opt && opt.folder !== undefined && state.ui.folderInput) {
|
||||
state.isProgrammaticUpdate = true;
|
||||
state.ui.folderInput.setValue(opt.folder);
|
||||
state.useRelativeFolder = !!opt.useRelativeFolder;
|
||||
if (state.ui.folderToggleBtn) {
|
||||
state.ui.folderToggleBtn.setIcon(state.useRelativeFolder ? "folder-dot" : "folder-lock");
|
||||
state.ui.folderToggleBtn.setTooltip(state.useRelativeFolder ? "In current folder or subfolder" : "Fixed absolute folder path");
|
||||
}
|
||||
state.isProgrammaticUpdate = false;
|
||||
state.folderManuallyEdited = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// 4.1 On-the-spot Note Type creation
|
||||
noteTypeRow.addExtraButton(btn => {
|
||||
btn.setIcon("plus")
|
||||
.setTooltip("Create new Note Type")
|
||||
.onClick(() => {
|
||||
const tempId = "New Type " + (Object.keys(settings.noteTypes).length + 1);
|
||||
settings.noteTypes[tempId] = {
|
||||
folder: "",
|
||||
useRelativeFolder: state.useRelativeFolder,
|
||||
type: "file",
|
||||
template: settings.baseTemplateForNewNoteTypes || "",
|
||||
prefix: "",
|
||||
icon: "file",
|
||||
ontology: { default: "referencing", actions: ["referencing"] }
|
||||
};
|
||||
|
||||
// Passed with isNew = true to gracefully handle escape/cancel deletions
|
||||
openEditNoteTypeModal(tempId, (finalName) => {
|
||||
ea.setScriptSettings(settings);
|
||||
const targetName = finalName || tempId;
|
||||
|
||||
// Refresh dropdown options
|
||||
const selectEl = state.ui.dropdownComponent.selectEl;
|
||||
while(selectEl.options.length > 0) selectEl.remove(0);
|
||||
Object.keys(settings.noteTypes).sort().forEach(k => state.ui.dropdownComponent.addOption(k, k));
|
||||
|
||||
// Select newly created type
|
||||
state.selectedNoteType = targetName;
|
||||
settings.lastSelectedNoteType = targetName;
|
||||
state.ui.dropdownComponent.setValue(targetName);
|
||||
|
||||
callbacks.updateIconPreview();
|
||||
callbacks.updateOntologyDropdown();
|
||||
}, true);
|
||||
});
|
||||
});
|
||||
|
||||
callbacks.updateIconPreview();
|
||||
}
|
||||
|
||||
@@ -1862,6 +1977,7 @@ function buildCaptureFooter(contentEl, state, modal) {
|
||||
state.finalData = {
|
||||
filename: val,
|
||||
folder: folderVal,
|
||||
useRelativeFolder: state.useRelativeFolder, // Append relative setting state
|
||||
noteType: state.selectedNoteType,
|
||||
format: state.selectedFormat,
|
||||
ontologyAction: state.selectedOntology,
|
||||
@@ -1904,7 +2020,22 @@ async function openCaptureModal(initialSearchValue) {
|
||||
modal.modalEl.style.width = "480px";
|
||||
modal.modalEl.style.maxWidth = "100%";
|
||||
modal.modalEl.classList.add("excalidraw-capture-note-modal");
|
||||
modal.titleEl.setText("Capture Contextual Note");
|
||||
|
||||
// Clear default title text and convert to a flex container to align elements
|
||||
modal.titleEl.empty();
|
||||
modal.titleEl.style.display = "flex";
|
||||
modal.titleEl.style.justifyContent = "space-between";
|
||||
modal.titleEl.style.alignItems = "center";
|
||||
modal.titleEl.style.width = "100%";
|
||||
|
||||
// Add Main Title
|
||||
modal.titleEl.createSpan({ text: "Capture Contextual Note" });
|
||||
|
||||
// Add right-aligned Version string
|
||||
modal.titleEl.createSpan({
|
||||
text: VERSION,
|
||||
attr: { style: "font-size: 0.5em; color: var(--text-muted); font-weight: normal; margin-right: 8px;" }
|
||||
});
|
||||
|
||||
let initialFolder = "";
|
||||
let initialFilename = initialSearchValue || "";
|
||||
@@ -1970,6 +2101,7 @@ async function openCaptureModal(initialSearchValue) {
|
||||
const state = {
|
||||
finalData: null,
|
||||
initialFolder,
|
||||
useRelativeFolder: settings.useRelativeFolder || false,
|
||||
initialSearchValue: initialFilename,
|
||||
folderManuallyEdited: false, // Start false so we can auto-update if they change to a new file
|
||||
isProgrammaticUpdate: false,
|
||||
@@ -2041,6 +2173,11 @@ async function openCaptureModal(initialSearchValue) {
|
||||
if (opt && opt.folder !== undefined) {
|
||||
state.isProgrammaticUpdate = true;
|
||||
state.ui.folderInput.setValue(opt.folder);
|
||||
state.useRelativeFolder = !!opt.useRelativeFolder;
|
||||
if (state.ui.folderToggleBtn) {
|
||||
state.ui.folderToggleBtn.setIcon(state.useRelativeFolder ? "folder-dot" : "folder-lock");
|
||||
state.ui.folderToggleBtn.setTooltip(state.useRelativeFolder ? "In current folder or subfolder" : "Fixed absolute folder path");
|
||||
}
|
||||
state.isProgrammaticUpdate = false;
|
||||
}
|
||||
}
|
||||
@@ -2393,6 +2530,18 @@ function buildNoteTypesSection(contentEl) {
|
||||
const noteTypesSection = contentEl.createEl("details", { cls: "setting-sub-section" });
|
||||
noteTypesSection.createEl("summary", { text: "Note Types & Custom Ontologies" });
|
||||
|
||||
const baseTemplateContainer = noteTypesSection.createDiv({ attr: { style: "margin-bottom: 15px;" } });
|
||||
new ea.obsidian.Setting(baseTemplateContainer)
|
||||
.setName("Base Template for New Ontologies")
|
||||
.setDesc("A generic template used automatically when creating new note types on the fly.")
|
||||
.addText(text => {
|
||||
text.setValue(settings.baseTemplateForNewNoteTypes || "").onChange(val => {
|
||||
settings.baseTemplateForNewNoteTypes = val;
|
||||
ea.setScriptSettings(settings);
|
||||
});
|
||||
new TemplateSuggest(app, text.inputEl);
|
||||
});
|
||||
|
||||
const addBtnContainer = noteTypesSection.createDiv({ cls: "flex-row-spaced", attr: { style: "margin-bottom:15px;" } });
|
||||
addBtnContainer.createEl("span", { text: "Manage your note types:" });
|
||||
const addBtn = addBtnContainer.createEl("button", { text: "Add", cls: "mod-cta" });
|
||||
@@ -2404,16 +2553,19 @@ function buildNoteTypesSection(contentEl) {
|
||||
const tempId = "New Type " + (Object.keys(settings.noteTypes).length + 1);
|
||||
settings.noteTypes[tempId] = {
|
||||
folder: "",
|
||||
useRelativeFolder: false,
|
||||
type: "file",
|
||||
template: "",
|
||||
template: settings.baseTemplateForNewNoteTypes || "",
|
||||
prefix: "",
|
||||
icon: "file",
|
||||
ontology: { default: "referencing", actions: ["referencing"] }
|
||||
};
|
||||
|
||||
// Passed with isNew = true to gracefully handle escape/cancel deletions
|
||||
openEditNoteTypeModal(tempId, () => {
|
||||
ea.setScriptSettings(settings);
|
||||
refreshCallback();
|
||||
});
|
||||
}, true);
|
||||
});
|
||||
|
||||
refreshCallback();
|
||||
@@ -2462,12 +2614,13 @@ function openSettingsModal() {
|
||||
// -------------------------------------------------------------
|
||||
// 7. UI: Detailed Single Note Type Editor Modal (Secondary Modal)
|
||||
// -------------------------------------------------------------
|
||||
function openEditNoteTypeModal(noteTypeKey, saveCallback) {
|
||||
function openEditNoteTypeModal(noteTypeKey, saveCallback, isNew = false) {
|
||||
const modal = new ea.obsidian.Modal(app);
|
||||
modal.titleEl.setText(`Configure Note Type`);
|
||||
|
||||
const typeConfig = settings.noteTypes[noteTypeKey];
|
||||
let originalKeyName = noteTypeKey;
|
||||
let isSaved = false;
|
||||
|
||||
// Fetch ExcaliBrain ontology actions
|
||||
let brainOntologies = [];
|
||||
@@ -2524,15 +2677,67 @@ function openEditNoteTypeModal(noteTypeKey, saveCallback) {
|
||||
settings.noteTypes[finalName] = typeConfig;
|
||||
delete settings.noteTypes[originalKeyName];
|
||||
}
|
||||
saveCallback();
|
||||
isSaved = true;
|
||||
saveCallback(finalName);
|
||||
modal.close();
|
||||
});
|
||||
|
||||
let folderInputComp;
|
||||
const currentFolderPath = ea.targetView ? ea.targetView.file.parent.path : "/";
|
||||
|
||||
new ea.obsidian.Setting(contentEl)
|
||||
.setName("Target Vault Folder")
|
||||
.addText(text => {
|
||||
folderInputComp = text;
|
||||
text.setValue(typeConfig.folder).onChange(val => { typeConfig.folder = val; });
|
||||
new FolderSuggest(app, text.inputEl);
|
||||
// Passing typeConfig directly ensures the Suggester inherits the toggle boolean accurately
|
||||
new FolderSuggest(app, text.inputEl, typeConfig, currentFolderPath);
|
||||
typeConfig._tempTextInput = text.inputEl;
|
||||
})
|
||||
.addExtraButton(btn => {
|
||||
const updateIcon = () => {
|
||||
btn.setIcon(typeConfig.useRelativeFolder ? "folder-dot" : "folder-lock");
|
||||
btn.setTooltip(typeConfig.useRelativeFolder ? "Relative to current note's folder" : "Absolute folder path");
|
||||
};
|
||||
updateIcon();
|
||||
|
||||
btn.onClick(() => {
|
||||
typeConfig.useRelativeFolder = !typeConfig.useRelativeFolder;
|
||||
updateIcon();
|
||||
|
||||
// Handle path transformation automatically
|
||||
let currentVal = folderInputComp.getValue().trim();
|
||||
const prefix = currentFolderPath === "/" ? "" : currentFolderPath;
|
||||
|
||||
if (typeConfig.useRelativeFolder) {
|
||||
// Absolute to Relative
|
||||
if (currentVal === prefix) {
|
||||
folderInputComp.setValue("");
|
||||
typeConfig.folder = "";
|
||||
} else if (currentVal.startsWith(prefix + "/")) {
|
||||
const newRelative = currentVal.substring(prefix.length + 1);
|
||||
folderInputComp.setValue(newRelative);
|
||||
typeConfig.folder = newRelative;
|
||||
} else {
|
||||
folderInputComp.setValue("");
|
||||
typeConfig.folder = "";
|
||||
}
|
||||
} else {
|
||||
// Relative to Absolute
|
||||
if (currentVal === "") {
|
||||
folderInputComp.setValue(prefix);
|
||||
typeConfig.folder = prefix;
|
||||
} else {
|
||||
const newAbsolute = prefix ? `${prefix}/${currentVal}` : currentVal;
|
||||
folderInputComp.setValue(newAbsolute);
|
||||
typeConfig.folder = newAbsolute;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeConfig._tempTextInput) {
|
||||
typeConfig._tempTextInput.dispatchEvent(new Event("input"));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
new ea.obsidian.Setting(contentEl)
|
||||
@@ -2543,9 +2748,16 @@ function openEditNoteTypeModal(noteTypeKey, saveCallback) {
|
||||
new TemplateSuggest(app, text.inputEl);
|
||||
});
|
||||
|
||||
// Strip unsafe characters to guarantee OS-level file creation compatibility
|
||||
new ea.obsidian.Setting(contentEl)
|
||||
.setName("File Prefix")
|
||||
.addText(text => text.setValue(typeConfig.prefix).onChange(val => { typeConfig.prefix = val; }));
|
||||
.addText(text => text.setValue(typeConfig.prefix).onChange(val => {
|
||||
const cleaned = val.replace(/[\\/:"*?<>|]/g, '');
|
||||
if (cleaned !== val) {
|
||||
text.setValue(cleaned);
|
||||
}
|
||||
typeConfig.prefix = cleaned;
|
||||
}));
|
||||
|
||||
const iconSetting = new ea.obsidian.Setting(contentEl)
|
||||
.setName("Lucide Icon");
|
||||
@@ -2673,6 +2885,11 @@ function openEditNoteTypeModal(noteTypeKey, saveCallback) {
|
||||
};
|
||||
|
||||
modal.onClose = () => {
|
||||
// If the creation workflow is abandoned before explicitly saving, erase the orphaned entry
|
||||
if (isNew && !isSaved) {
|
||||
delete settings.noteTypes[originalKeyName];
|
||||
ea.setScriptSettings(settings);
|
||||
}
|
||||
setTimeout(() => { delete modal; });
|
||||
};
|
||||
modal.open();
|
||||
|
||||
+565
-160
File diff suppressed because it is too large.
Load diff
+538
-514
File diff suppressed because it is too large.
Load diff
@@ -649,7 +649,7 @@
|
||||
},
|
||||
{
|
||||
"fname": "Mindmap Builder.md",
|
||||
"mtime": 1781460603530
|
||||
"mtime": 1782759480611
|
||||
},
|
||||
{
|
||||
"fname": "Mindmap Builder.svg",
|
||||
@@ -665,7 +665,7 @@
|
||||
},
|
||||
{
|
||||
"fname": "Capture Note.md",
|
||||
"mtime": 1780986335837
|
||||
"mtime": 1782745696796
|
||||
},
|
||||
{
|
||||
"fname": "Capture Note.svg",
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "obsidian-excalidraw-plugin",
|
||||
"name": "Excalidraw",
|
||||
"version": "2.25.0-beta.3",
|
||||
"version": "2.25.0-beta.5",
|
||||
"minAppVersion": "1.8.7",
|
||||
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
|
||||
"author": "Zsolt Viczian",
|
||||
|
||||
Generated
+4
-4
@@ -13,7 +13,7 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.110",
|
||||
"@zsviczian/excalidraw": "0.18.111",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
@@ -5232,9 +5232,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@zsviczian/excalidraw": {
|
||||
"version": "0.18.110",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.110.tgz",
|
||||
"integrity": "sha512-R/5aZ/6Sbk3O/TI0O28kA/KzyeXC61NDXFVjIi5857Lmx2Gvf1Xva3APKoqsnBwiR2aNjB92qBE86AiUyvxmhA==",
|
||||
"version": "0.18.111",
|
||||
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.111.tgz",
|
||||
"integrity": "sha512-Y0rHChvXRDVafpwxZ10CoKeV2U7EkhpNcC3xa4M29xEfFPH4fdFhbxwxODBg4aqMzBXD36MD1SSo+MDN3EXahg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@braintree/sanitize-url": "6.0.2",
|
||||
|
||||
+1
-1
@@ -29,7 +29,7 @@
|
||||
"@popperjs/core": "^2.11.8",
|
||||
"@radix-ui/number": "^1.1.2",
|
||||
"@zsviczian/colormaster": "^1.2.2",
|
||||
"@zsviczian/excalidraw": "0.18.110",
|
||||
"@zsviczian/excalidraw": "0.18.111",
|
||||
"chroma-js": "^3.1.2",
|
||||
"clsx": "^2.0.0",
|
||||
"es6-promise-pool": "2.5.0",
|
||||
|
||||
@@ -219,7 +219,7 @@ export const URL_REGISTRY = {
|
||||
"https://community.obsidian.md/plugins/obsidian-excalidraw-plugin",
|
||||
UrlPurpose.RELEASE_LOG,
|
||||
),
|
||||
GITHUB_COM: defineUrl("https://github.com/", UrlPurpose.RELEASE_LOG),
|
||||
GITHUB_COM: defineUrl("https://github.com", UrlPurpose.RELEASE_LOG),
|
||||
GITHUB_COM_EXCALIDRAW_EXCALIDRAW_ISSUES: defineUrl(
|
||||
"https://github.com/excalidraw/excalidraw/issues",
|
||||
UrlPurpose.RELEASE_LOG,
|
||||
|
||||
@@ -235,7 +235,7 @@ export class PluginFileManager {
|
||||
excalidrawFile: file,
|
||||
action: "export",
|
||||
}) ?? imageFullpath;
|
||||
} catch (e) {
|
||||
} catch (e: unknown) {
|
||||
errorlog({
|
||||
where: "FileManager.embedDrawing",
|
||||
fn: "plugin.ea.onImageExportPathHook",
|
||||
@@ -771,7 +771,7 @@ export class PluginFileManager {
|
||||
excalidrawFile: file,
|
||||
action: "delete",
|
||||
}) ?? imgPath;
|
||||
} catch (e) {
|
||||
} catch (e: unknown) {
|
||||
errorlog({
|
||||
where: "FileManager.deleteEventHandler",
|
||||
fn: "plugin.ea.onImageExportPathHook",
|
||||
|
||||
@@ -1197,6 +1197,10 @@ export default {
|
||||
SELECT_TO_EMBED: "Select the drawing to insert into active document.",
|
||||
SELECT_MD: "Select the markdown document you want to insert",
|
||||
|
||||
//ToolsPanel.tsx
|
||||
TASKBON_NOT_ENABLED:
|
||||
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
|
||||
|
||||
//SelectCard.ts
|
||||
TYPE_SECTION: "Type section name to select.",
|
||||
SELECT_SECTION_OR_TYPE_NEW:
|
||||
|
||||
@@ -29,6 +29,36 @@ I build this plugin as a labor of love. Curious about the philosophy behind it?
|
||||
## Fixed
|
||||
- BUG: Double Click to edit from Obsidian in Live preview doesn't work anymore [#2813](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2813)
|
||||
- Edge cases leading to memory leak and CPU overload when closing a markdown preview while embedded Excalidraw drawings are loading, or closing an ExcalidrawView, while nested images are still loading.
|
||||
- Markdown-embed-as-image snapshot drops MathJax/LaTeX output [#2818](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2818), [#2282](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2282) 🙏[@Jmarcos13](${URLs.GITHUB_COM}/Jmarcos13) via [#2822](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_PULL}/2822)
|
||||
- Fixed the "Customize the Embedded File Link" action. If you change the dimensions of the markdown image or the pdf page reference number, the image immediately updates in the scene. You can also use this feature to swap out images e.g. a png icon to an SVG icon. Default shortcut is CTRL+WIN+Click or CMD+Control+Click on the image element.
|
||||
|
||||
## New in ExcalidrawAutomate
|
||||
- Added \`onSceneChangeHook\` to allow scripts and sidepanel tabs to react to scene changes. The hook supports filtering by \`appStateKeys\` and checking for tab visibility to optimize performance.
|
||||
|
||||
\`\`\`ts
|
||||
/**
|
||||
* If set, this callback is triggered when the scene changes in the target view.
|
||||
* You can use this to react to appState or element changes.
|
||||
* Any script can sign up for updates via this hook.
|
||||
* Because this hook fires extremely frequently (on every mouse move during drawing),
|
||||
* you MUST specify which appState keys you are interested in OR set trackElements to true.
|
||||
* If trackElements is falsy and appStateKeys is empty or undefined, the callback will NOT be triggered to prevent performance issues.
|
||||
* For sidepanel tabs, there is an additional filter feature: if triggerWhenInvisible is false,
|
||||
* the callback will only trigger when the sidepanel is visible and the tab is active.
|
||||
*/
|
||||
onSceneChangeHook: {
|
||||
appStateKeys?: (keyof AppState)[];
|
||||
trackElements?: boolean;
|
||||
triggerWhenInvisible?: boolean;
|
||||
callback: (
|
||||
elements: readonly ExcalidrawElement[],
|
||||
appState: AppState,
|
||||
files: BinaryFiles,
|
||||
view: ExcalidrawView,
|
||||
ea: ExcalidrawAutomate,
|
||||
) => void;
|
||||
} | null = null;
|
||||
\`\`\`
|
||||
`,
|
||||
"2.24.2": `
|
||||
## Fixed
|
||||
|
||||
@@ -1261,6 +1261,95 @@ export const EXCALIDRAW_AUTOMATE_INFO: SuggesterInfo[] = [
|
||||
desc: "Decompresses a base 64 compressed string using LZString",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "onSceneChangeHook",
|
||||
code: "onSceneChangeHook: { appStateKeys?: (keyof AppState)[]; trackElements?: boolean; triggerWhenInvisible?: boolean; callback: (elements: readonly ExcalidrawElement[], appState: AppState, files: BinaryFiles, view: ExcalidrawView, ea: ExcalidrawAutomate) => void; } | null;",
|
||||
desc:
|
||||
"If set, this callback is triggered when the scene changes in the target view.\n" +
|
||||
"You can use this to react to appState or element changes. Any script can sign up for updates via this hook.\n" +
|
||||
"Because this hook fires extremely frequently (dozens of times per second during drawing), you MUST specify the appState keys you want to track (e.g., ['zoom', 'scrollX', 'scrollY']) OR set trackElements to true.\n" +
|
||||
"If trackElements is falsy and appStateKeys is empty or undefined, the hook is ignored to prevent severe performance degradation.\n" +
|
||||
"For sidepanel tabs, there is an additional filter: if triggerWhenInvisible is false, the callback will only trigger when the sidepanel is visible and the tab is active.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "onViewUnloadHook",
|
||||
code: "onViewUnloadHook: (view: ExcalidrawView) => void;",
|
||||
desc: "If set, this callback is triggered when the user closes an Excalidraw view.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "onViewModeChangeHook",
|
||||
code: "onViewModeChangeHook: (isViewModeEnabled: boolean, view: ExcalidrawView, ea: ExcalidrawAutomate) => void;",
|
||||
desc: "If set, this callback is triggered when the user changes the view mode.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "onLinkHoverHook",
|
||||
code: "onLinkHoverHook: (element: NonDeletedExcalidrawElement, linkText: string, view: ExcalidrawView, ea: ExcalidrawAutomate) => boolean;",
|
||||
desc: "If set, this callback is triggered when the user hovers a link in the scene. Return false to prevent the native Excalidraw onLinkHover management flow.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "onLinkClickHook",
|
||||
code: "onLinkClickHook: (element: ExcalidrawElement, linkText: string, event: MouseEvent, view: ExcalidrawView, ea: ExcalidrawAutomate) => boolean;",
|
||||
desc: "If set, this callback is triggered when the user clicks a link in the scene. Return false to prevent the native Excalidraw onLinkClick management flow.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "onDropHook",
|
||||
code: "onDropHook: (data: {ea: ExcalidrawAutomate; event: React.DragEvent<HTMLDivElement>; draggable: ObsidianDraggable; type: 'file' | 'text' | 'unknown'; payload: {files: TFile[]; text: string;}; excalidrawFile: TFile; view: ExcalidrawView; pointerPosition: {x: number; y: number}; }) => boolean;",
|
||||
desc: "If set, this callback is triggered when Excalidraw receives an onDrop event. Return false to prevent the native Excalidraw onDrop management flow.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "onPasteHook",
|
||||
code: "onPasteHook: (data: {ea: ExcalidrawAutomate; payload: ClipboardData; event: ClipboardEvent; excalidrawFile: TFile; view: ExcalidrawView; pointerPosition: {x: number; y: number}; }) => boolean;",
|
||||
desc: "If set, this callback is triggered when Excalidraw receives an onPaste event. Return false to prevent the native Excalidraw onPaste management flow.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "onImageFilePathHook",
|
||||
code: "onImageFilePathHook: (data: {currentImageName: string; drawingFilePath: string;}) => string | null;",
|
||||
desc: "If set, this callback is triggered when an image is being saved in Excalidraw. You can use this to customize the naming and path of pasted images. Return null or undefined to continue with the default behavior. If a filepath is returned, it will be used.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "onImageExportPathHook",
|
||||
code: "onImageExportPathHook: (data: {exportFilepath: string; exportExtension: string; excalidrawFile: TFile; oldExcalidrawPath?: string; action: 'export' | 'move' | 'delete';}) => string | null;",
|
||||
desc: "If set, this callback is triggered when an image is exported to .svg, .png, or .excalidraw. Customize the naming and path for the exported image. Return null or undefined to use the default path.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "onTriggerAutoexportHook",
|
||||
code: "onTriggerAutoexportHook: (data: {autoexportConfig: AutoexportConfig; excalidrawFile: TFile;}) => AutoexportConfig | null;",
|
||||
desc: "If set, this callback is triggered when an Excalidraw file is being saved. Allows overriding auto-export settings on the fly. Return a modified AutoexportConfig to override, or null to use defaults.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "onFileOpenHook",
|
||||
code: "onFileOpenHook: (data: {ea: ExcalidrawAutomate; excalidrawFile: TFile; view: ExcalidrawView;}) => Promise<void>;",
|
||||
desc: "If set, this callback is triggered when an Excalidraw file is opened. It runs before the file-level script defined in the excalidraw-onload-script frontmatter.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "onFileCreateHook",
|
||||
code: "onFileCreateHook: (data: {ea: ExcalidrawAutomate; excalidrawFile: TFile; view: ExcalidrawView;}) => Promise<void>;",
|
||||
desc: "If set, this callback is triggered when a new Excalidraw file is created.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "onCanvasColorChangeHook",
|
||||
code: "onCanvasColorChangeHook: (ea: ExcalidrawAutomate, view: ExcalidrawView, color: string) => void;",
|
||||
desc: "If set, this callback is triggered whenever the active canvas color changes.",
|
||||
after: "",
|
||||
},
|
||||
{
|
||||
field: "onUpdateElementLinkForExportHook",
|
||||
code: "onUpdateElementLinkForExportHook: (data: {originalLink: string; obsidianLink: string; linkedFile: TFile | null; hostFile: TFile;}) => string;",
|
||||
desc: "If set, this callback is triggered whenever a drawing is exported to SVG. The string returned will replace the internal Obsidian link in the exported SVG.",
|
||||
after: "",
|
||||
},
|
||||
];
|
||||
|
||||
export const EXCALIDRAW_SCRIPTENGINE_INFO: SuggesterInfo[] = [
|
||||
|
||||
@@ -18,11 +18,8 @@ import {
|
||||
mainDocument,
|
||||
} from "../constants/constants";
|
||||
import { createSVG } from "src/utils/excalidrawAutomateUtils";
|
||||
import {
|
||||
EquationItem,
|
||||
ExcalidrawData,
|
||||
getTransclusion,
|
||||
} from "./ExcalidrawData";
|
||||
import type { EquationItem } from "./ExcalidrawData";
|
||||
import { ExcalidrawData, getTransclusion } from "./ExcalidrawData";
|
||||
import { t } from "../lang/helpers";
|
||||
import { tex2dataURL } from "./LaTeX";
|
||||
import ExcalidrawPlugin from "../core/main";
|
||||
@@ -78,7 +75,7 @@ import {
|
||||
isInstanceOfHTMLImageElement,
|
||||
isInstanceOfSVGElement,
|
||||
} from "src/utils/typechecks";
|
||||
import { strictArrayBuffer } from "src/utils/obsidianUtils";
|
||||
import { getSafeFrontmatter, 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
|
||||
@@ -1058,12 +1055,17 @@ export class EmbeddedFilesLoader {
|
||||
if (result?.files) {
|
||||
for (const key in result.files) {
|
||||
const fileData = {
|
||||
...result.files[key],
|
||||
...(result.files as Record<string, { dataURL: string }>)[
|
||||
key
|
||||
],
|
||||
id: element.fileId,
|
||||
created: Date.now(),
|
||||
hasSVGwithBitmap: false,
|
||||
shouldScale: true,
|
||||
size: await getImageSize(result.files[key].dataURL),
|
||||
size: await getImageSize(
|
||||
(result.files as Record<string, { dataURL: string }>)[key]
|
||||
.dataURL,
|
||||
),
|
||||
} as FileData;
|
||||
files[batch].push(fileData);
|
||||
}
|
||||
@@ -1080,7 +1082,7 @@ export class EmbeddedFilesLoader {
|
||||
depth,
|
||||
inFile: null,
|
||||
hasSVGwithBitmap: false,
|
||||
elements: result.elements,
|
||||
elements: result.elements as ExcalidrawElement[],
|
||||
});
|
||||
if (this.terminate) {
|
||||
return;
|
||||
@@ -1124,7 +1126,7 @@ export class EmbeddedFilesLoader {
|
||||
);
|
||||
try {
|
||||
addFiles(batchFiles, this.isDark, false);
|
||||
} catch (e) {
|
||||
} catch (e: unknown) {
|
||||
errorlog({ where: "EmbeddedFileLoader.loadSceneFiles", error: e });
|
||||
}
|
||||
files.push([]);
|
||||
@@ -1154,7 +1156,7 @@ export class EmbeddedFilesLoader {
|
||||
try {
|
||||
//in try block because by the time files are loaded the user may have closed the view
|
||||
addFiles(batchFiles, this.isDark, true);
|
||||
} catch (e) {
|
||||
} catch (e: unknown) {
|
||||
errorlog({ where: "EmbeddedFileLoader.loadSceneFiles", error: e });
|
||||
}
|
||||
} finally {
|
||||
@@ -1407,8 +1409,12 @@ export class EmbeddedFilesLoader {
|
||||
canvas.height = 0;
|
||||
return result;
|
||||
}
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
} catch (e: unknown) {
|
||||
errorlog({
|
||||
where: "EmbeddedFileLoader.pdfToDataURL",
|
||||
uid: this.uid,
|
||||
error: e,
|
||||
});
|
||||
return [null, null, null, null, false];
|
||||
}
|
||||
}
|
||||
@@ -1436,14 +1442,13 @@ export class EmbeddedFilesLoader {
|
||||
|
||||
//2.
|
||||
//get styles
|
||||
|
||||
const fileCache = plugin.app.metadataCache.getFileCache(file);
|
||||
let fontDef: string;
|
||||
let fontName = plugin.settings.mdFont;
|
||||
if (
|
||||
fileCache?.frontmatter &&
|
||||
Boolean(fileCache.frontmatter[FRONTMATTER_KEYS.font.name])
|
||||
) {
|
||||
fontName = fileCache.frontmatter[FRONTMATTER_KEYS.font.name];
|
||||
const safeFrontmatter = getSafeFrontmatter(fileCache?.frontmatter);
|
||||
if (safeFrontmatter[FRONTMATTER_KEYS.font.name]) {
|
||||
fontName = safeFrontmatter[FRONTMATTER_KEYS.font.name];
|
||||
}
|
||||
switch (fontName) {
|
||||
case "Virgil":
|
||||
@@ -1485,14 +1490,10 @@ export class EmbeddedFilesLoader {
|
||||
text = text.replace(/banner:\s*.*/, ""); //patch https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/814
|
||||
}
|
||||
|
||||
const fontColor = fileCache?.frontmatter
|
||||
? (fileCache.frontmatter[FRONTMATTER_KEYS["font-color"].name] ??
|
||||
plugin.settings.mdFontColor)
|
||||
: plugin.settings.mdFontColor;
|
||||
const fmFontColor = safeFrontmatter[FRONTMATTER_KEYS["font-color"].name];
|
||||
const fontColor = fmFontColor ?? plugin.settings.mdFontColor;
|
||||
let style: string = safeFrontmatter[FRONTMATTER_KEYS["md-css"].name] ?? "";
|
||||
|
||||
let style = fileCache?.frontmatter
|
||||
? (fileCache.frontmatter[FRONTMATTER_KEYS["md-css"].name] ?? "")
|
||||
: "";
|
||||
let frontmatterCSSisAfile = false;
|
||||
if (style && style !== "") {
|
||||
const f = plugin.app.metadataCache.getFirstLinkpathDest(style, file.path);
|
||||
@@ -1515,10 +1516,9 @@ export class EmbeddedFilesLoader {
|
||||
}
|
||||
}
|
||||
|
||||
const borderColor = fileCache?.frontmatter
|
||||
? (fileCache.frontmatter[FRONTMATTER_KEYS["border-color"].name] ??
|
||||
plugin.settings.mdBorderColor)
|
||||
: plugin.settings.mdBorderColor;
|
||||
const borderColor: string =
|
||||
safeFrontmatter[FRONTMATTER_KEYS["border-color"].name] ??
|
||||
plugin.settings.mdBorderColor;
|
||||
|
||||
if (borderColor && borderColor !== "" && !style.match(/svg/i)) {
|
||||
style += `svg{border:2px solid;color:${borderColor};transform:scale(.95)}`;
|
||||
@@ -1571,6 +1571,35 @@ export class EmbeddedFilesLoader {
|
||||
return { dataURL: "" as DataURL, hasSVGwithBitmap: false };
|
||||
}
|
||||
|
||||
// MathJax typesetting may complete asynchronously after MarkdownRenderer.render() resolves.
|
||||
// Awaiting typesetPromise ensures all mjx-container elements are fully populated before
|
||||
// we clone the DOM into the iframe or serialize to SVG.
|
||||
const mjx = window.MathJax;
|
||||
if (mjx?.typesetPromise) {
|
||||
try {
|
||||
await mjx.typesetPromise([mdDIV]);
|
||||
} catch (e: unknown) {
|
||||
errorlog({
|
||||
where: "EmbeddedFileLoader.convertMarkdownToSVG",
|
||||
message:
|
||||
"Non-fatal: proceed with whatever state MathJax left the DOM in.",
|
||||
error: e,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Capture the MathJax CHTML stylesheet AFTER typesetting so all per-glyph rules
|
||||
// are present. We pass the live <style> element (not textContent) because MathJax
|
||||
// adds rules via sheet.insertRule(), which updates sheet.cssRules but never
|
||||
// reflects in textContent — reading textContent would miss every glyph except
|
||||
// any that happened to be in the element's original authored content.
|
||||
const mjxCHtmlStyleContent = await scopeAndInlineMathJaxCSS(
|
||||
mainDocument.getElementById(
|
||||
"MJX-CHTML-styles",
|
||||
) as HTMLStyleElement | null,
|
||||
".excalidraw-md-host",
|
||||
);
|
||||
|
||||
mdDIV
|
||||
.querySelectorAll(":scope > *[class^='frontmatter']")
|
||||
.forEach((el) => mdDIV.removeChild(el));
|
||||
@@ -1626,10 +1655,16 @@ export class EmbeddedFilesLoader {
|
||||
const iframeDoc = iframe.contentWindow.document;
|
||||
if (style) {
|
||||
const styleEl = iframeDoc.createElement("style");
|
||||
styleEl.type = "text/css";
|
||||
setStyleText(styleEl, style);
|
||||
iframeDoc.head.appendChild(styleEl);
|
||||
}
|
||||
// Inject the MathJax CHTML stylesheet into the iframe so that mjx-* custom elements
|
||||
// are styled correctly when measuring scroll height and computing inline styles.
|
||||
if (mjxCHtmlStyleContent) {
|
||||
const mjxStyleEl = iframeDoc.createElement("style");
|
||||
setStyleText(mjxStyleEl, mjxCHtmlStyleContent);
|
||||
iframeDoc.head.appendChild(mjxStyleEl);
|
||||
}
|
||||
const stylingDIV = iframeDoc.importNode(mdDIV, true);
|
||||
iframeDoc.body.appendChild(stylingDIV);
|
||||
const footerDIV = createDiv();
|
||||
@@ -1704,10 +1739,15 @@ export class EmbeddedFilesLoader {
|
||||
}
|
||||
|
||||
const xml = new XMLSerializer().serializeToString(mdDIV);
|
||||
// Prepend the MathJax CHTML stylesheet to the SVG's embedded <style> block so that
|
||||
// mjx-container elements inside the <foreignObject> render correctly.
|
||||
const finalStyle = mjxCHtmlStyleContent
|
||||
? mjxCHtmlStyleContent + "\n" + style
|
||||
: style;
|
||||
const finalSVG = svg(
|
||||
xml,
|
||||
'<div class="excalidraw-md-footer"></div>',
|
||||
style,
|
||||
finalStyle,
|
||||
);
|
||||
plugin.ea.mostRecentMarkdownSVG = parser.parseFromString(
|
||||
finalSVG,
|
||||
@@ -1720,6 +1760,118 @@ export class EmbeddedFilesLoader {
|
||||
}
|
||||
}
|
||||
|
||||
// ─── MathJax CHTML stylesheet helpers ────────────────────────────────────────
|
||||
|
||||
// Cache keyed by "<rule-count>:<last-rule-text>" — cheap to compute and sufficient
|
||||
// for MathJax's append-only glyph stylesheet: every new character adds a new rule
|
||||
// at the end, so a change in count or last entry signals a cache miss.
|
||||
const mjxScopedStyleCache = new Map<string, Promise<string>>();
|
||||
|
||||
/**
|
||||
* Fetches a font file and returns it as a base64 data URI.
|
||||
* This is necessary because fonts referenced by relative/app:// URLs in
|
||||
* @font-face rules are blocked when the SVG is loaded as a data: URL.
|
||||
*/
|
||||
const fetchFontAsDataURI = async (url: string): Promise<string | null> => {
|
||||
if (url.startsWith("data:")) return url;
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) return null;
|
||||
const buf = await res.arrayBuffer();
|
||||
const bytes = new Uint8Array(buf);
|
||||
// Build base64 in 8 KB chunks to avoid call-stack overflow on large fonts.
|
||||
let binary = "";
|
||||
const chunk = 8192;
|
||||
for (let i = 0; i < bytes.length; i += chunk) {
|
||||
binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
||||
}
|
||||
const ext = url.split("?")[0].split(".").pop()?.toLowerCase() ?? "";
|
||||
const mime =
|
||||
ext === "woff2"
|
||||
? "font/woff2"
|
||||
: ext === "woff"
|
||||
? "font/woff"
|
||||
: ext === "ttf"
|
||||
? "font/ttf"
|
||||
: ext === "otf"
|
||||
? "font/otf"
|
||||
: "font/woff2";
|
||||
return `data:${mime};base64,${btoa(binary)}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Processes the live MathJax CHTML <style> element so it is safe to embed in the SVG.
|
||||
*
|
||||
* WHY we accept the element instead of its textContent: MathJax adds per-glyph CSS
|
||||
* rules via sheet.insertRule(), which updates sheet.cssRules but NOT the element's
|
||||
* textContent. Reading textContent would therefore miss every glyph rule added after
|
||||
* initial load, explaining why only the very last character in a formula appeared.
|
||||
*
|
||||
* What this function does:
|
||||
* 1. Scopes every style rule to `scope` (e.g. ".excalidraw-md-host") so that broad
|
||||
* selectors cannot bleed outside the math container and underline regular text.
|
||||
* 2. Inlines every @font-face src URL as a base64 data URI so the mathematical fonts
|
||||
* (needed for correct radical-bar vertical metrics) load inside a data: SVG, where
|
||||
* the browser blocks all external URL references for security reasons.
|
||||
*
|
||||
* Results are cached by rule-count + last-rule text to avoid re-fetching fonts on
|
||||
* every embed of the same formula set.
|
||||
*/
|
||||
const scopeAndInlineMathJaxCSS = (
|
||||
styleEl: HTMLStyleElement | null,
|
||||
scope: string,
|
||||
): Promise<string> => {
|
||||
const sheet = styleEl?.sheet;
|
||||
if (!sheet?.cssRules.length) return Promise.resolve("");
|
||||
|
||||
// Cheap cache key: rule count + last rule text (MathJax only ever appends rules).
|
||||
const lastRule = sheet.cssRules[sheet.cssRules.length - 1]?.cssText ?? "";
|
||||
const cacheKey = `${sheet.cssRules.length}:${lastRule.slice(0, 80)}`;
|
||||
|
||||
const cached = mjxScopedStyleCache.get(cacheKey) ?? null;
|
||||
if (cached !== null) return cached;
|
||||
|
||||
const work = (async (): Promise<string> => {
|
||||
// Snapshot the live rules array before any await so we process the state
|
||||
// that existed when typesetPromise resolved, not a later state.
|
||||
const rules = Array.from(sheet.cssRules);
|
||||
let result = "";
|
||||
for (const rule of rules) {
|
||||
if (rule instanceof CSSFontFaceRule) {
|
||||
// Inline each src URL as base64 so fonts work inside data: SVGs.
|
||||
let ruleText = rule.cssText;
|
||||
const urlRe = /url\(["']?([^"')]+)["']?\)/g;
|
||||
for (const m of [...ruleText.matchAll(urlRe)]) {
|
||||
const dataURI = await fetchFontAsDataURI(m[1]);
|
||||
if (dataURI) ruleText = ruleText.replace(m[0], `url("${dataURI}")`);
|
||||
}
|
||||
result += ruleText + "\n";
|
||||
} else if (rule instanceof CSSStyleRule) {
|
||||
// Prefix every selector with `scope` so rules cannot bleed to elements
|
||||
// outside the math container (e.g. causing underlines on regular text).
|
||||
const sr = rule;
|
||||
const scoped = sr.selectorText
|
||||
.split(",")
|
||||
.map((s) => `${scope} ${s.trim()}`)
|
||||
.join(", ");
|
||||
result += `${scoped} { ${sr.style.cssText} }\n`;
|
||||
} else {
|
||||
// @media, @keyframes, @supports, etc. — pass through unchanged.
|
||||
result += rule.cssText + "\n";
|
||||
}
|
||||
}
|
||||
return result;
|
||||
})();
|
||||
|
||||
mjxScopedStyleCache.set(cacheKey, work);
|
||||
return work;
|
||||
};
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const getSVGData = async (
|
||||
app: App,
|
||||
file: TFile,
|
||||
|
||||
@@ -4028,6 +4028,29 @@ export class ExcalidrawAutomate {
|
||||
excalidrawFile: TFile; // The Excalidraw file being auto-exported
|
||||
}) => AutoexportConfig | null = null;
|
||||
|
||||
/**
|
||||
* If set, this callback is triggered when the scene changes in the target view.
|
||||
* You can use this to react to appState or element changes.
|
||||
* Any script can sign up for updates via this hook.
|
||||
* Because this hook fires extremely frequently (on every mouse move during drawing),
|
||||
* you MUST specify which appState keys you are interested in OR set trackElements to true.
|
||||
* If trackElements is falsy and appStateKeys is empty or undefined, the callback will NOT be triggered to prevent performance issues.
|
||||
* For sidepanel tabs, there is an additional filter feature: if triggerWhenInvisible is false,
|
||||
* the callback will only trigger when the sidepanel is visible and the tab is active.
|
||||
*/
|
||||
onSceneChangeHook: {
|
||||
appStateKeys?: (keyof AppState)[];
|
||||
trackElements?: boolean;
|
||||
triggerWhenInvisible?: boolean;
|
||||
callback: (
|
||||
elements: readonly ExcalidrawElement[],
|
||||
appState: AppState,
|
||||
files: BinaryFiles,
|
||||
view: ExcalidrawView,
|
||||
ea: ExcalidrawAutomate,
|
||||
) => void;
|
||||
} | null = null;
|
||||
|
||||
/**
|
||||
* if set, this callback is triggered, when an Excalidraw file is opened
|
||||
* You can use this callback in case you want to do something additional when the file is opened.
|
||||
|
||||
@@ -409,7 +409,7 @@ class ImageCache {
|
||||
new Promise<undefined>((_, reject) =>
|
||||
window.setTimeout(() => {
|
||||
reject(new Error("Timeout while retrieving cache data"));
|
||||
}, 100),
|
||||
}, 200),
|
||||
),
|
||||
]);
|
||||
this.fullyInitialized = true;
|
||||
@@ -451,6 +451,7 @@ class ImageCache {
|
||||
console.error(
|
||||
"unexpected error in getResolvedCacheData",
|
||||
this.getResolvedCacheData.bind(this),
|
||||
key_,
|
||||
error,
|
||||
);
|
||||
return undefined;
|
||||
|
||||
@@ -70,4 +70,6 @@ export interface SidepanelTab {
|
||||
getHostEA(): ExcalidrawAutomate;
|
||||
/** Returns whether the tab is currently visible in the UI */
|
||||
isVisible(): boolean;
|
||||
/** Returns whether the tab is the currently active tab in the sidepanel */
|
||||
isActiveTab(): boolean;
|
||||
}
|
||||
Vendored
+3
@@ -171,6 +171,9 @@ declare global {
|
||||
React?: typeof import("react");
|
||||
ReactDOM?: typeof import("react-dom/client");
|
||||
ExcalidrawLib?: typeof ExcalidrawLib;
|
||||
MathJax?: {
|
||||
typesetPromise(elements: HTMLElement[]): Promise<void>;
|
||||
};
|
||||
}
|
||||
interface File {
|
||||
path?: string;
|
||||
|
||||
@@ -13,7 +13,7 @@ const REQUIRED_EXTRAS_VERSIONS: Record<
|
||||
string,
|
||||
{ min?: string; exact?: string }
|
||||
> = {
|
||||
plugin: { min: "0.0.14" },
|
||||
plugin: { min: "0.0.15" },
|
||||
mathjax: { min: "1.0.0" },
|
||||
mermaid: { exact: "2.2.2" },
|
||||
pdf: { min: "1.0.0" },
|
||||
|
||||
+140
-18
@@ -504,6 +504,8 @@ export default class ExcalidrawView
|
||||
reactDOM: null,
|
||||
excalidrawLib: null,
|
||||
};
|
||||
private lastAppState: AppState | null = null;
|
||||
private lastElementsVersion: number = -1;
|
||||
|
||||
constructor(leaf: WorkspaceLeaf, plugin: ExcalidrawPlugin) {
|
||||
super(leaf);
|
||||
@@ -1481,11 +1483,20 @@ export default class ExcalidrawView
|
||||
ef.resetImage(this.file.path, link);
|
||||
this.excalidrawData.setFile(fileId, ef);
|
||||
this.setDirty();
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
void this.loadSceneFiles(
|
||||
false,
|
||||
new Set([fileId]),
|
||||
resolve,
|
||||
new Set([fileId]),
|
||||
);
|
||||
});
|
||||
|
||||
if (originalAnchor !== nextAnchor) {
|
||||
await toggleImageAnchoring(el, this, nextAnchor, ef);
|
||||
}
|
||||
await this.save(false);
|
||||
await sleep(100);
|
||||
|
||||
if (!this.plugin.isExcalidrawFile(ef.file) && !link.endsWith("|100%")) {
|
||||
const ea = getEA(this);
|
||||
const imgEl = this.getViewElements().find(
|
||||
@@ -1496,10 +1507,12 @@ export default class ExcalidrawView
|
||||
return;
|
||||
}
|
||||
if (imgEl && (await ea.resetImageAspectRatio(imgEl))) {
|
||||
await ea.addElementsToView(false);
|
||||
await ea.addElementsToView(false, false);
|
||||
}
|
||||
ea.destroy();
|
||||
}
|
||||
|
||||
await this.save(false);
|
||||
};
|
||||
GenericInputPrompt.Prompt(
|
||||
this,
|
||||
@@ -4255,6 +4268,115 @@ export default class ExcalidrawView
|
||||
return t("NOFILE");
|
||||
}
|
||||
|
||||
private triggerSceneChangeHooks(
|
||||
et: readonly ExcalidrawElement[],
|
||||
st: AppState,
|
||||
files: BinaryFiles,
|
||||
) {
|
||||
if (this.semaphores.viewunload) return;
|
||||
|
||||
const hookServer = this.getHookServer();
|
||||
const sidepanel = ExcalidrawSidepanelView.getExisting(false);
|
||||
|
||||
const currentVersion = this.getSceneVersion(et);
|
||||
|
||||
if (
|
||||
!hookServer?.onSceneChangeHook &&
|
||||
!(sidepanel && sidepanel.hasEATargetingView(this))
|
||||
) {
|
||||
this.lastAppState = st;
|
||||
this.lastElementsVersion = currentVersion;
|
||||
return;
|
||||
}
|
||||
|
||||
const last = this.lastAppState;
|
||||
const elementsChanged = currentVersion !== this.lastElementsVersion;
|
||||
|
||||
this.lastAppState = st;
|
||||
this.lastElementsVersion = currentVersion;
|
||||
|
||||
if (!last && !elementsChanged) return;
|
||||
|
||||
if (hookServer && hookServer.onSceneChangeHook) {
|
||||
this.evaluateSceneChangeHook(
|
||||
hookServer,
|
||||
et,
|
||||
st,
|
||||
last,
|
||||
files,
|
||||
elementsChanged,
|
||||
);
|
||||
}
|
||||
|
||||
if (sidepanel) {
|
||||
sidepanel.forEachEATargetingView(this, (ea) => {
|
||||
if (ea.onSceneChangeHook) {
|
||||
this.evaluateSceneChangeHook(
|
||||
ea,
|
||||
et,
|
||||
st,
|
||||
last,
|
||||
files,
|
||||
elementsChanged,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private evaluateSceneChangeHook(
|
||||
ea: ExcalidrawAutomate,
|
||||
et: readonly ExcalidrawElement[],
|
||||
st: AppState,
|
||||
last: AppState | null,
|
||||
files: BinaryFiles,
|
||||
elementsChanged: boolean,
|
||||
) {
|
||||
const hook = ea.onSceneChangeHook;
|
||||
|
||||
// Strictly enforce appStateKeys or trackElements to protect performance
|
||||
if (!hook) return;
|
||||
if (
|
||||
!hook.trackElements &&
|
||||
(!hook.appStateKeys || hook.appStateKeys.length === 0)
|
||||
)
|
||||
return;
|
||||
|
||||
const tab = ea.sidepanelTab;
|
||||
if (tab) {
|
||||
const isActiveAndVisible = tab.isActiveTab() && tab.isVisible();
|
||||
if (!isActiveAndVisible && !hook.triggerWhenInvisible) return;
|
||||
}
|
||||
|
||||
let hasRelevantChange = false;
|
||||
|
||||
if (hook.trackElements && elementsChanged) {
|
||||
hasRelevantChange = true;
|
||||
}
|
||||
|
||||
if (!hasRelevantChange && hook.appStateKeys && last) {
|
||||
for (let i = 0; i < hook.appStateKeys.length; i++) {
|
||||
const key = hook.appStateKeys[i];
|
||||
if (st[key] !== last[key]) {
|
||||
hasRelevantChange = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasRelevantChange) return;
|
||||
|
||||
try {
|
||||
hook.callback(et, st, files, this, ea);
|
||||
} catch (e: unknown) {
|
||||
errorlog({
|
||||
where: "ExcalidrawView.evaluateSceneChangeHook",
|
||||
fn: hook.callback,
|
||||
error: e,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// the view type name
|
||||
getViewType() {
|
||||
return VIEW_TYPE_EXCALIDRAW;
|
||||
@@ -5615,7 +5737,7 @@ export default class ExcalidrawView
|
||||
});
|
||||
}
|
||||
|
||||
if (st.newElement?.type === "freedraw") {
|
||||
if ((st.newElement as ExcalidrawElement)?.type === "freedraw") {
|
||||
this.freedrawLastActiveTimestamp = Date.now();
|
||||
}
|
||||
if (
|
||||
@@ -5669,10 +5791,8 @@ export default class ExcalidrawView
|
||||
this.colorChangeTimer = null;
|
||||
}, 50); //just enough time if the user is playing with color picker, the change is not too frequent.
|
||||
}
|
||||
if (this.semaphores.dirty) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!this.semaphores.dirty &&
|
||||
st.editingTextElement === null &&
|
||||
//Removed because of
|
||||
//https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/565
|
||||
@@ -5683,6 +5803,8 @@ export default class ExcalidrawView
|
||||
) {
|
||||
this.checkSceneVersion(et);
|
||||
}
|
||||
|
||||
this.triggerSceneChangeHooks(et, st, files);
|
||||
}
|
||||
|
||||
private onLibraryChange(items: LibraryItems) {
|
||||
@@ -7403,17 +7525,17 @@ export default class ExcalidrawView
|
||||
: `${rank}: ${t("WELCOME_RANK_LEGENDARY")}`,
|
||||
children: title,
|
||||
}),
|
||||
React.createElement(WelcomeScreen.Center.Heading, {
|
||||
children: [
|
||||
t("WELCOME_COMMAND_PALETTE"),
|
||||
React.createElement("br"),
|
||||
t("WELCOME_OBSIDIAN_MENU"),
|
||||
React.createElement("br"),
|
||||
t("WELCOME_SCRIPT_LIBRARY"),
|
||||
React.createElement("br"),
|
||||
t("WELCOME_HELP_MENU"),
|
||||
],
|
||||
}),
|
||||
React.createElement(
|
||||
WelcomeScreen.Center.Heading,
|
||||
null,
|
||||
t("WELCOME_COMMAND_PALETTE"),
|
||||
React.createElement("br"),
|
||||
t("WELCOME_OBSIDIAN_MENU"),
|
||||
React.createElement("br"),
|
||||
t("WELCOME_SCRIPT_LIBRARY"),
|
||||
React.createElement("br"),
|
||||
t("WELCOME_HELP_MENU"),
|
||||
),
|
||||
React.createElement(
|
||||
WelcomeScreen.Center.Menu,
|
||||
{},
|
||||
|
||||
@@ -25,6 +25,7 @@ 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";
|
||||
import { errorlog } from "src/utils/coreUtils";
|
||||
|
||||
type PdfViewLike = {
|
||||
containerEl?: HTMLElement;
|
||||
@@ -285,8 +286,12 @@ function setupPdfViewEnhancements(
|
||||
setStyle(view.contentEl, {
|
||||
cursor: "grabbing",
|
||||
});
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "CustomEmbeddable.onPointerDownCapture",
|
||||
fn: "setStyle",
|
||||
error: error,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -323,8 +328,12 @@ function setupPdfViewEnhancements(
|
||||
setStyle(view.contentEl, {
|
||||
cursor: "",
|
||||
});
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "CustomEmbeddable.onPointerUp",
|
||||
fn: "setStyle",
|
||||
error: error,
|
||||
});
|
||||
}
|
||||
window.removeEventListener("pointermove", onPointerMove, true);
|
||||
window.removeEventListener("pointerup", onPointerUp, true);
|
||||
@@ -391,13 +400,21 @@ function setupPdfViewEnhancements(
|
||||
// Cleanup existing handlers/observers
|
||||
try {
|
||||
pdfObserverRef.currentCleanup?.();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "CustomEmbeddable.onPointerUp",
|
||||
fn: "pdfObserverRef.currentCleanup",
|
||||
error: error,
|
||||
});
|
||||
}
|
||||
try {
|
||||
pdfObserverRef.current?.disconnect();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "CustomEmbeddable.onPointerUp",
|
||||
fn: "pdfObserverRef.current.disconnect",
|
||||
error: error,
|
||||
});
|
||||
}
|
||||
|
||||
// Re-setup on next tick to allow DOM to settle
|
||||
@@ -421,18 +438,30 @@ function setupPdfViewEnhancements(
|
||||
pdfObserverRef.currentCleanup = () => {
|
||||
try {
|
||||
prevCleanup?.();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "CustomEmbeddable.onPointerUp",
|
||||
fn: "pdfObserverRef.currentCleanup",
|
||||
error: error,
|
||||
});
|
||||
}
|
||||
try {
|
||||
pdfObserverRef.current?.disconnect();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "CustomEmbeddable.onPointerUp",
|
||||
fn: "pdfObserverRef.current.disconnect",
|
||||
error: error,
|
||||
});
|
||||
}
|
||||
try {
|
||||
detachObserver?.disconnect();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "CustomEmbeddable.onPointerUp",
|
||||
fn: "detachObserver.disconnect",
|
||||
error: error,
|
||||
});
|
||||
}
|
||||
detachObserver = null;
|
||||
};
|
||||
@@ -563,6 +592,7 @@ function RenderObsidianView({
|
||||
null,
|
||||
) as React.MutableRefObject<EmbeddableLeafRef | null>;
|
||||
const isEditingRef = React.useRef(false);
|
||||
const isPreviewRef = React.useRef(false);
|
||||
const isActiveRef = React.useRef(false);
|
||||
const viewTypeRef = React.useRef("empty");
|
||||
const themeRef = React.useRef(theme);
|
||||
@@ -570,7 +600,7 @@ function RenderObsidianView({
|
||||
null,
|
||||
) as PdfObserverRef;
|
||||
const pdfObserverDisabledRef = React.useRef(false);
|
||||
const mobilePatchCleanupRef = React.useRef(null);
|
||||
const mobilePatchCleanupRef = React.useRef<(() => void) | null>(null);
|
||||
const initialViewFileRef = React.useRef(view.file);
|
||||
const mdPropsRef = React.useRef(mdProps);
|
||||
const fileRef = React.useRef(file);
|
||||
@@ -906,8 +936,12 @@ function RenderObsidianView({
|
||||
// cleanup persistent mobile patch if active
|
||||
try {
|
||||
mobilePatchCleanupRef.current?.();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "CustomEmbeddable.onPointerUp",
|
||||
fn: "mobilePatchCleanupRef.current",
|
||||
error: error,
|
||||
});
|
||||
}
|
||||
mobilePatchCleanupRef.current = null;
|
||||
|
||||
@@ -1179,23 +1213,28 @@ function RenderObsidianView({
|
||||
event?.stopPropagation();
|
||||
}
|
||||
|
||||
if (!isActiveRef.current || isEditingRef.current || !leafRef.current) {
|
||||
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) {
|
||||
if (!isActiveRef.current && isPreviewRef.current) {
|
||||
view.clearEmbeddableNodeIsEditing();
|
||||
isPreviewRef.current = false;
|
||||
}
|
||||
if (isActiveRef.current && currentFile?.path === view.file.path) {
|
||||
view.setPreventReload();
|
||||
void view.setEmbeddableNodeIsEditing();
|
||||
isPreviewRef.current = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isActiveRef.current || isEditingRef.current || !leafRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
/*if(isActiveRef.current && leafRef.current?.leaf) {
|
||||
setKeepOnTop();
|
||||
view.app.workspace.setActiveLeaf(leafRef.current.leaf, { focus: true });
|
||||
@@ -1205,9 +1244,11 @@ function RenderObsidianView({
|
||||
//Handle canvas node
|
||||
const newTheme = getTheme(view, themeRef.current);
|
||||
containerRef.current?.addClasses(["is-editing", "is-focused"]);
|
||||
const isEditingSelf = fileRef.current?.path === view.file.path;
|
||||
void view.canvasNodeFactory.startEditing(
|
||||
leafRef.current.node,
|
||||
newTheme,
|
||||
isEditingSelf,
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -1216,9 +1257,11 @@ function RenderObsidianView({
|
||||
const api: ExcalidrawImperativeAPI = view.excalidrawAPI;
|
||||
const el = api
|
||||
.getSceneElements()
|
||||
.filter((el) => el.id === element.id)[0];
|
||||
.filter(
|
||||
(el: ExcalidrawEmbeddableElement) => el.id === element.id,
|
||||
)[0] as ExcalidrawEmbeddableElement;
|
||||
if (!el || el.angle !== 0) {
|
||||
new Notice("Sorry, cannot edit rotated markdown documents");
|
||||
new Notice("Sorry, cannot edit rotated Markdown documents");
|
||||
return;
|
||||
}
|
||||
const modes = leafRef.current.leaf.view.modes;
|
||||
@@ -1238,6 +1281,7 @@ function RenderObsidianView({
|
||||
isActiveRef.current,
|
||||
isEditingRef.current,
|
||||
viewTypeRef.current,
|
||||
fileRef.current,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1323,26 +1367,39 @@ function RenderObsidianView({
|
||||
const node = leafRef.current?.node;
|
||||
if (node) {
|
||||
//Handle canvas node
|
||||
if (
|
||||
isActiveRef.current &&
|
||||
view.plugin.settings.markdownNodeOneClickEditing &&
|
||||
!containerRef.current?.hasClass("is-editing")
|
||||
) {
|
||||
if (mdPropsRef.current?.lockedReadingMode) {
|
||||
if (isActiveRef.current) {
|
||||
if (
|
||||
mdPropsRef.current?.lockedReadingMode ||
|
||||
(!view.plugin.settings.markdownNodeOneClickEditing &&
|
||||
!containerRef.current?.hasClass("is-editing"))
|
||||
) {
|
||||
if (fileRef.current?.path === view.file.path) {
|
||||
view.setPreventReload();
|
||||
void view.setEmbeddableNodeIsEditing();
|
||||
}
|
||||
} else {
|
||||
} else if (
|
||||
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);
|
||||
const isEditingSelf = fileRef.current?.path === view.file.path;
|
||||
void view.canvasNodeFactory.startEditing(
|
||||
node,
|
||||
newTheme,
|
||||
isEditingSelf,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if (
|
||||
fileRef.current?.path === view.file.path &&
|
||||
!containerRef.current?.hasClass("is-editing")
|
||||
) {
|
||||
view.clearEmbeddableNodeIsEditing(); //else it will be cleared in stopEditing right below
|
||||
}
|
||||
containerRef.current?.removeClasses(["is-editing", "is-focused"]);
|
||||
view.canvasNodeFactory.stopEditing(node);
|
||||
view.clearEmbeddableNodeIsEditing();
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1364,8 +1421,12 @@ function RenderObsidianView({
|
||||
// stop persistent observer when deactivated
|
||||
try {
|
||||
mobilePatchCleanupRef.current?.();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
} catch (error: unknown) {
|
||||
errorlog({
|
||||
where: "CustomEmbeddable.onPointerUp",
|
||||
fn: "mobilePatchCleanupRef.current",
|
||||
error: error,
|
||||
});
|
||||
}
|
||||
mobilePatchCleanupRef.current = null;
|
||||
}
|
||||
|
||||
@@ -23,38 +23,46 @@ import {
|
||||
import { ToolsPanel } from "./ToolsPanel";
|
||||
|
||||
export type ResetCustomPenState = {
|
||||
currentItemStrokeWidthKey?: string;
|
||||
currentItemStrokeWidth?: number;
|
||||
currentItemStrokeVariability?: string;
|
||||
currentItemBackgroundColor?: string;
|
||||
currentItemStrokeColor?: string;
|
||||
currentItemFillStyle?: string;
|
||||
currentItemRoughness?: number;
|
||||
currentItemStrokeWidthKey?: string | null;
|
||||
currentItemStrokeWidth?: number | null;
|
||||
currentItemStrokeVariability?: string | null;
|
||||
currentItemBackgroundColor?: string | null;
|
||||
currentItemStrokeColor?: string | null;
|
||||
currentItemFillStyle?: string | null;
|
||||
currentItemRoughness?: number | null;
|
||||
};
|
||||
|
||||
export function setPen(pen: PenStyle, api: ExcalidrawImperativeAPI) {
|
||||
const st = api.getAppState();
|
||||
const strokeWidthEntry =
|
||||
!pen.strokeWidth || pen.strokeWidth === 0
|
||||
? {}
|
||||
: getAppStateStrokeWidthEntry(undefined, pen.strokeWidth);
|
||||
|
||||
// Changed null to undefined so it neatly satisfies Partial<...>
|
||||
const currentItemStrokeWidthKey =
|
||||
"currentItemStrokeWidthKey" in strokeWidthEntry
|
||||
const hasStrokeWidth = pen.strokeWidth && pen.strokeWidth !== 0;
|
||||
const strokeWidthEntry = hasStrokeWidth
|
||||
? getAppStateStrokeWidthEntry(undefined, pen.strokeWidth)
|
||||
: {};
|
||||
|
||||
// If the pen has a stroke width, the omitted key MUST be set to null to clear it out in Excalidraw.
|
||||
// If no stroke width is defined, pass undefined to ignore it during the merge.
|
||||
const currentItemStrokeWidthKey = hasStrokeWidth
|
||||
? "currentItemStrokeWidthKey" in strokeWidthEntry
|
||||
? strokeWidthEntry.currentItemStrokeWidthKey
|
||||
: undefined;
|
||||
const currentItemStrokeWidth =
|
||||
"currentItemStrokeWidth" in strokeWidthEntry
|
||||
: null
|
||||
: undefined;
|
||||
|
||||
const currentItemStrokeWidth = hasStrokeWidth
|
||||
? "currentItemStrokeWidth" in strokeWidthEntry
|
||||
? strokeWidthEntry.currentItemStrokeWidth
|
||||
: undefined;
|
||||
: null
|
||||
: undefined;
|
||||
|
||||
// 1. Build the object and explicitly type it as your custom AppState
|
||||
const nextAppState: Partial<AppState> = {
|
||||
currentStrokeOptions: pen.penOptions,
|
||||
currentItemStrokeWidthKey,
|
||||
currentItemStrokeWidth,
|
||||
currentItemStrokeVariability: pen.penOptions.constantPressure
|
||||
currentStrokeOptions: pen.penOptions ?? null,
|
||||
...(currentItemStrokeWidthKey !== undefined
|
||||
? { currentItemStrokeWidthKey: currentItemStrokeWidthKey }
|
||||
: null),
|
||||
...(currentItemStrokeWidth !== undefined
|
||||
? { currentItemStrokeWidth: currentItemStrokeWidth }
|
||||
: null),
|
||||
currentItemStrokeVariability: pen.penOptions?.constantPressure
|
||||
? "constant"
|
||||
: "variable",
|
||||
...(pen.backgroundColor
|
||||
@@ -65,29 +73,31 @@ export function setPen(pen: PenStyle, api: ExcalidrawImperativeAPI) {
|
||||
...(pen.roughness !== null
|
||||
? { currentItemRoughness: pen.roughness }
|
||||
: null),
|
||||
...(pen.freedrawOnly && !st.resetCustomPen //switching from custom pen to next custom pen
|
||||
// Removed the pen.freedrawOnly restriction so that ALL pens can be correctly manually disabled
|
||||
...(!st.resetCustomPen
|
||||
? {
|
||||
resetCustomPen: {
|
||||
currentItemStrokeWidthKey: st.currentItemStrokeWidthKey as
|
||||
| "extraThin"
|
||||
| "thin"
|
||||
| "medium"
|
||||
| "bold"
|
||||
| "extraBold",
|
||||
currentItemStrokeWidth: st.currentItemStrokeWidth,
|
||||
currentItemStrokeVariability: st.currentItemStrokeVariability as
|
||||
| "constant"
|
||||
| "variable",
|
||||
currentItemBackgroundColor: st.currentItemBackgroundColor,
|
||||
currentItemStrokeColor: st.currentItemStrokeColor,
|
||||
currentItemFillStyle: st.currentItemFillStyle as ExtendedFillStyle,
|
||||
currentItemRoughness: st.currentItemRoughness,
|
||||
currentItemStrokeWidthKey:
|
||||
(st.currentItemStrokeWidthKey as
|
||||
| "extraThin"
|
||||
| "thin"
|
||||
| "medium"
|
||||
| "bold"
|
||||
| "extraBold") ?? null,
|
||||
currentItemStrokeWidth: st.currentItemStrokeWidth ?? null,
|
||||
currentItemStrokeVariability:
|
||||
(st.currentItemStrokeVariability as "constant" | "variable") ??
|
||||
null,
|
||||
currentItemBackgroundColor: st.currentItemBackgroundColor ?? null,
|
||||
currentItemStrokeColor: st.currentItemStrokeColor ?? null,
|
||||
currentItemFillStyle:
|
||||
(st.currentItemFillStyle as ExtendedFillStyle) ?? null,
|
||||
currentItemRoughness: st.currentItemRoughness ?? null,
|
||||
},
|
||||
}
|
||||
: null),
|
||||
};
|
||||
|
||||
// 2. Cast it back to Partial<AppState> here to satisfy Excalidraw's API
|
||||
api.updateScene({
|
||||
appState: nextAppState as Pick<AppState, keyof AppState>,
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
@@ -99,25 +109,25 @@ export function resetStrokeOptions(
|
||||
api: ExcalidrawImperativeAPI,
|
||||
clearCurrentStrokeOptions: boolean,
|
||||
) {
|
||||
// 1. Build the object and explicitly type it as your custom AppState
|
||||
const nextAppState: Partial<AppState> = {
|
||||
...(resetCustomPen
|
||||
? {
|
||||
currentItemStrokeWidthKey: resetCustomPen.currentItemStrokeWidthKey,
|
||||
currentItemStrokeWidth: resetCustomPen.currentItemStrokeWidth,
|
||||
currentItemBackgroundColor: resetCustomPen.currentItemBackgroundColor,
|
||||
currentItemStrokeColor: resetCustomPen.currentItemStrokeColor,
|
||||
currentItemFillStyle: resetCustomPen.currentItemFillStyle,
|
||||
currentItemRoughness: resetCustomPen.currentItemRoughness,
|
||||
currentItemStrokeWidthKey:
|
||||
resetCustomPen.currentItemStrokeWidthKey ?? null,
|
||||
currentItemStrokeWidth: resetCustomPen.currentItemStrokeWidth ?? null,
|
||||
currentItemBackgroundColor:
|
||||
resetCustomPen.currentItemBackgroundColor ?? null,
|
||||
currentItemStrokeColor: resetCustomPen.currentItemStrokeColor ?? null,
|
||||
currentItemFillStyle: resetCustomPen.currentItemFillStyle ?? null,
|
||||
currentItemRoughness: resetCustomPen.currentItemRoughness ?? null,
|
||||
currentItemStrokeVariability:
|
||||
resetCustomPen.currentItemStrokeVariability,
|
||||
resetCustomPen.currentItemStrokeVariability ?? null,
|
||||
}
|
||||
: null),
|
||||
resetCustomPen: null,
|
||||
...(clearCurrentStrokeOptions ? { currentStrokeOptions: null } : null),
|
||||
};
|
||||
|
||||
// 2. Cast it back to Partial<AppState> here to satisfy Excalidraw's API
|
||||
api.updateScene({
|
||||
appState: nextAppState as Pick<AppState, keyof AppState>,
|
||||
captureUpdate: CaptureUpdateAction.NEVER,
|
||||
@@ -131,7 +141,7 @@ export class ObsidianMenu {
|
||||
private prevClickTimestamp: number = 0;
|
||||
constructor(
|
||||
private plugin: ExcalidrawPlugin,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ref instance is injected from ToolsPanel and carries imperative methods.
|
||||
|
||||
private toolsRef: React.MutableRefObject<ToolsPanel>,
|
||||
private view: ExcalidrawView,
|
||||
) {
|
||||
@@ -158,11 +168,13 @@ export class ObsidianMenu {
|
||||
const api = this.view.excalidrawAPI;
|
||||
const st = api.getAppState();
|
||||
|
||||
// Deep compare objects to bypass Excalidraw's immutable reference updates
|
||||
const isPenActive =
|
||||
JSON.stringify(st.currentStrokeOptions ?? null) ===
|
||||
JSON.stringify(pen.penOptions ?? null);
|
||||
|
||||
//single second click to reset freedraw to default
|
||||
if (
|
||||
st.currentStrokeOptions === pen.penOptions &&
|
||||
st.activeTool.type === "freedraw"
|
||||
) {
|
||||
if (isPenActive && st.activeTool.type === "freedraw") {
|
||||
resetStrokeOptions(st.resetCustomPen as ResetCustomPenState, api, true);
|
||||
return;
|
||||
}
|
||||
@@ -254,11 +266,17 @@ export class ObsidianMenu {
|
||||
public renderCustomPens(isMobile: boolean, appState: AppState) {
|
||||
return appState.customPens?.map((_, index) => {
|
||||
const pen = this.plugin.settings.customPens[index];
|
||||
|
||||
const isPenActive =
|
||||
JSON.stringify(appState.currentStrokeOptions ?? null) ===
|
||||
JSON.stringify(pen.penOptions ?? null);
|
||||
|
||||
//Reset stroke setting when changing to a different tool
|
||||
if (
|
||||
pen.freedrawOnly && // Enforce freedrawOnly so global pens do not auto-reset upon changing tools
|
||||
appState.resetCustomPen &&
|
||||
appState.activeTool.type !== "freedraw" &&
|
||||
appState.currentStrokeOptions === pen.penOptions
|
||||
isPenActive
|
||||
) {
|
||||
window.setTimeout(() =>
|
||||
resetStrokeOptions(
|
||||
@@ -268,11 +286,12 @@ export class ObsidianMenu {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
//if Pen settings are loaded, select custom pen when activating the freedraw element
|
||||
if (
|
||||
!appState.resetCustomPen &&
|
||||
appState.activeTool.type === "freedraw" &&
|
||||
appState.currentStrokeOptions === pen.penOptions &&
|
||||
isPenActive &&
|
||||
pen.freedrawOnly
|
||||
) {
|
||||
window.setTimeout(() =>
|
||||
@@ -283,7 +302,7 @@ export class ObsidianMenu {
|
||||
if (
|
||||
appState.resetCustomPen &&
|
||||
appState.activeTool.type === "freedraw" &&
|
||||
appState.currentStrokeOptions === pen.penOptions &&
|
||||
isPenActive &&
|
||||
pen.freedrawOnly
|
||||
) {
|
||||
const activePen = this.activePens[index] ?? { ...pen };
|
||||
@@ -316,8 +335,7 @@ export class ObsidianMenu {
|
||||
className="ToolIcon__icon"
|
||||
aria-label={DEVICE.isDesktop ? pen.type : undefined}
|
||||
style={{
|
||||
...(appState.activeTool.type === "freedraw" &&
|
||||
appState.currentStrokeOptions === pen.penOptions
|
||||
...(appState.activeTool.type === "freedraw" && isPenActive
|
||||
? { background: "var(--color-primary)" }
|
||||
: {}),
|
||||
}}
|
||||
|
||||
@@ -280,10 +280,7 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
return;
|
||||
}
|
||||
if (!plugin.settings.taskboneEnabled) {
|
||||
new Notice(
|
||||
"Taskbone OCR is not enabled. Please go to plugins settings to enable it.",
|
||||
4000,
|
||||
);
|
||||
new Notice(t("TASKBON_NOT_ENABLED"), 4000);
|
||||
return;
|
||||
}
|
||||
void plugin.taskbone.getTextForView(view, {
|
||||
@@ -570,8 +567,8 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
>
|
||||
<div
|
||||
className="excalidraw-toolsPanel-dragHandle"
|
||||
onClick={this.islandOnClick.bind(this)}
|
||||
onPointerDown={this.islandOnPointerDown.bind(this)}
|
||||
onClick={(e) => this.islandOnClick(e)}
|
||||
onPointerDown={(e) => this.islandOnPointerDown(e)}
|
||||
>
|
||||
<svg
|
||||
aria-hidden="true"
|
||||
@@ -604,26 +601,26 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
<ActionButton
|
||||
key={"scriptEngine"}
|
||||
title={t("INSTALL_SCRIPT_BUTTON")}
|
||||
action={this.actionOpenScriptInstallDialog.bind(this)}
|
||||
action={() => this.actionOpenScriptInstallDialog()}
|
||||
icon={ICONS.scriptEngine}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"release-notes"}
|
||||
title={t("READ_RELEASE_NOTES")}
|
||||
action={this.actionOpenReleaseNotes.bind(this)}
|
||||
action={() => this.actionOpenReleaseNotes()}
|
||||
icon={ICONS.releaseNotes}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"about-excalidraw"}
|
||||
title={t("ABOUT_EXCALIDRAW")}
|
||||
action={this.actionOpenAboutExcalidraw.bind(this)}
|
||||
action={() => this.actionOpenAboutExcalidraw()}
|
||||
icon={ICONS.Info}
|
||||
/>
|
||||
{this.state.isPreviewMode === null ? (
|
||||
<ActionButton
|
||||
key={"convert"}
|
||||
title={t("CONVERT_FILE")}
|
||||
action={this.actionConvertExcalidrawToMD.bind(this)}
|
||||
action={() => this.actionConvertExcalidrawToMD()}
|
||||
icon={ICONS.convertFile}
|
||||
/>
|
||||
) : (
|
||||
@@ -633,7 +630,7 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
title={
|
||||
this.state.isPreviewMode ? t("PARSED") : t("RAW")
|
||||
}
|
||||
action={this.actionToggleViewMode.bind(this)}
|
||||
action={() => this.actionToggleViewMode()}
|
||||
icon={
|
||||
this.state.isPreviewMode
|
||||
? ICONS.rawMode
|
||||
@@ -645,7 +642,7 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
<ActionButton
|
||||
key={"ui-mode"}
|
||||
title={t("UI_MODE")}
|
||||
action={this.actionToggleTrayMode.bind(this)}
|
||||
action={() => this.actionToggleTrayMode()}
|
||||
icon={ICONS.tray}
|
||||
/>
|
||||
<ActionButton
|
||||
@@ -655,7 +652,7 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
? t("EXIT_FULLSCREEN")
|
||||
: t("GOTO_FULLSCREEN")
|
||||
}
|
||||
action={this.actionToggleFullscreen.bind(this)}
|
||||
action={() => this.actionToggleFullscreen()}
|
||||
icon={
|
||||
this.state.isFullscreen
|
||||
? ICONS.exitFullScreen
|
||||
@@ -667,31 +664,31 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
<ActionButton
|
||||
key={"search"}
|
||||
title={t("SEARCH")}
|
||||
action={this.actionSearch.bind(this)}
|
||||
action={() => this.actionSearch()}
|
||||
icon={ICONS.search}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"ocr"}
|
||||
title={t("RUN_OCR")}
|
||||
action={this.actionOCR.bind(this)}
|
||||
action={(e) => this.actionOCR(e)}
|
||||
icon={ICONS.ocr}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"openLink"}
|
||||
title={t("OPEN_LINK_CLICK")}
|
||||
action={this.actionOpenLink.bind(this)}
|
||||
action={(e) => this.actionOpenLink(e)}
|
||||
icon={ICONS.openLink}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"openLinkProperties"}
|
||||
title={t("OPEN_LINK_PROPS")}
|
||||
action={this.actionOpenLinkProperties.bind(this)}
|
||||
action={() => this.actionOpenLinkProperties()}
|
||||
icon={ICONS.openLinkProperties}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"save"}
|
||||
title={t("FORCE_SAVE")}
|
||||
action={this.actionForceSave.bind(this)}
|
||||
action={() => this.actionForceSave()}
|
||||
icon={saveIcon(this.state.isDirty)}
|
||||
/>
|
||||
</div>
|
||||
@@ -702,25 +699,25 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
<ActionButton
|
||||
key={"lib"}
|
||||
title={t("DOWNLOAD_LIBRARY")}
|
||||
action={this.actionExportLibrary.bind(this)}
|
||||
action={() => this.actionExportLibrary()}
|
||||
icon={ICONS.exportLibrary}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"exportIMG"}
|
||||
title={t("EXPORT_IMAGE")}
|
||||
action={this.actionExportImage.bind(this)}
|
||||
action={() => this.actionExportImage()}
|
||||
icon={ICONS.ExportImage}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"md"}
|
||||
title={t("OPEN_AS_MD")}
|
||||
action={this.actionOpenAsMarkdown.bind(this)}
|
||||
action={() => this.actionOpenAsMarkdown()}
|
||||
icon={ICONS.switchToMarkdown}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"link-to-element"}
|
||||
title={t("INSERT_LINK_TO_ELEMENT")}
|
||||
action={this.actionLinkToElement.bind(this)}
|
||||
action={(e) => this.actionLinkToElement(e)}
|
||||
icon={ICONS.copyElementLink}
|
||||
/>
|
||||
</div>
|
||||
@@ -731,55 +728,55 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
<ActionButton
|
||||
key={"anyfile"}
|
||||
title={t("UNIVERSAL_ADD_FILE")}
|
||||
action={this.actionAddAnyFile.bind(this)}
|
||||
action={() => this.actionAddAnyFile()}
|
||||
icon={ICONS["add-file"]}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"image"}
|
||||
title={t("INSERT_IMAGE")}
|
||||
action={this.actionInsertImage.bind(this)}
|
||||
action={() => this.actionInsertImage()}
|
||||
icon={ICONS.insertImage}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"pdf"}
|
||||
title={t("INSERT_PDF")}
|
||||
action={this.actionInsertPDF.bind(this)}
|
||||
action={() => this.actionInsertPDF()}
|
||||
icon={ICONS.insertPDF}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"insertMD"}
|
||||
title={t("INSERT_MD")}
|
||||
action={this.actionInsertMarkdown.bind(this)}
|
||||
action={() => this.actionInsertMarkdown()}
|
||||
icon={ICONS.insertMD}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"insertBackOfNote"}
|
||||
title={t("INSERT_CARD")}
|
||||
action={this.actionInsertBackOfNote.bind(this)}
|
||||
action={() => this.actionInsertBackOfNote()}
|
||||
icon={ICONS.BackOfNote}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"latex"}
|
||||
title={t("INSERT_LATEX")}
|
||||
action={this.actionInsertLaTeX.bind(this)}
|
||||
action={(e) => this.actionInsertLaTeX(e)}
|
||||
icon={ICONS.insertLaTeX}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"link"}
|
||||
title={t("INSERT_LINK")}
|
||||
action={this.actionInsertLink.bind(this)}
|
||||
action={() => this.actionInsertLink()}
|
||||
icon={ICONS.insertLink}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"import-svg"}
|
||||
title={t("IMPORT_SVG")}
|
||||
action={this.actionImportSVG.bind(this)}
|
||||
action={() => this.actionImportSVG()}
|
||||
icon={ICONS.importSVG}
|
||||
/>
|
||||
<ActionButton
|
||||
key={"crop-image"}
|
||||
title={t("CROP_IMAGE")}
|
||||
action={this.actionCropImage.bind(this)}
|
||||
action={() => this.actionCropImage()}
|
||||
icon={ICONS.Crop}
|
||||
/>
|
||||
</div>
|
||||
@@ -845,8 +842,8 @@ export class ToolsPanel extends React.Component<PanelProps, PanelState> {
|
||||
<ActionButton
|
||||
key={key}
|
||||
title={value.name}
|
||||
action={this.actionRunScript.bind(this, key)}
|
||||
longpress={this.actionPinScript.bind(this, key, value.name)}
|
||||
action={() => void this.actionRunScript(key)}
|
||||
longpress={() => void this.actionPinScript(key, value.name)}
|
||||
icon={new WeakRef(
|
||||
value.svgString
|
||||
? stringToSVG(value.svgString)
|
||||
|
||||
@@ -152,13 +152,19 @@ export class CanvasNodeFactory {
|
||||
this.observer.observe(editorEl, { attributes: true });
|
||||
}
|
||||
|
||||
public async startEditing(node: ObsidianCanvasNode, theme: string) {
|
||||
public async startEditing(
|
||||
node: ObsidianCanvasNode,
|
||||
theme: string,
|
||||
isEditingSelf: boolean,
|
||||
) {
|
||||
if (!this.initialized || !node || !node.isEditable()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.view.setEmbeddableNodeIsEditing();
|
||||
if (isEditingSelf) {
|
||||
await this.view.setEmbeddableNodeIsEditing();
|
||||
}
|
||||
|
||||
node.startEditing();
|
||||
node.isEditing = true;
|
||||
|
||||
@@ -369,6 +369,29 @@ export class ExcalidrawSidepanelView extends ItemView {
|
||||
this.updateEmptyStateVisibility();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if there are any ExcalidrawAutomate instances hosted by tabs targeting the specified view.
|
||||
*/
|
||||
public hasEATargetingView(view: ExcalidrawView): boolean {
|
||||
for (const ea of this.tabHosts.values()) {
|
||||
if (ea && ea.targetView === view) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes a callback for each ExcalidrawAutomate instance targeting the specified view.
|
||||
* Avoids allocating intermediate arrays for performance.
|
||||
*/
|
||||
public forEachEATargetingView(
|
||||
view: ExcalidrawView,
|
||||
cb: (ea: ExcalidrawAutomate) => void,
|
||||
): void {
|
||||
for (const ea of this.tabHosts.values()) {
|
||||
if (ea && ea.targetView === view) cb(ea);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a tab by its backing script name if present.
|
||||
*/
|
||||
|
||||
@@ -243,6 +243,13 @@ export class ExcalidrawSidepanelTab
|
||||
return this.host.isVisible();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether the tab is the currently active tab in the sidepanel
|
||||
*/
|
||||
public isActiveTab(): boolean {
|
||||
return this.isActive;
|
||||
}
|
||||
|
||||
public reveal(): void {
|
||||
if (!this.isActive) {
|
||||
this.open();
|
||||
|
||||
+2
-2
@@ -1039,7 +1039,7 @@ End Obsidian Sheets Plus support
|
||||
- standard left/right panel padding: ~1.5rem (0.75rem each side)
|
||||
- plus a tiny 0.1rem buffer to prevent accidental wrapping
|
||||
*/
|
||||
width: calc((var(--default-button-size) * 5) + 2.6rem);
|
||||
width: calc((var(--default-button-size) * 5) + 3rem);
|
||||
|
||||
height: fit-content;
|
||||
max-height: 400px;
|
||||
@@ -1061,7 +1061,7 @@ End Obsidian Sheets Plus support
|
||||
.excalidraw .Island.excalidraw-toolsPanel-island .buttonList>.ToolIcon_type_button,
|
||||
.excalidraw .Island.excalidraw-toolsPanel-island .buttonList>.ToolIcon,
|
||||
.excalidraw .Island.excalidraw-toolsPanel-island .buttonList>label {
|
||||
flex: 0 0 auto !important;
|
||||
flex: 0 0 auto;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user