Compare commits

...
Author SHA1 Message Date
zsviczian 3a953818b1 2.25.2-beta.1 2026-07-05 15:25:31 +02:00
zsviczian 9c034b9f51 2.25.2-beta.0 2026-07-05 11:57:14 +02:00
zsviczian 392088fed5 pen settings improvements 2026-07-05 11:23:16 +02:00
zsviczian e97f123a83 added save/cancel to PenSettingsModal, moved PenSettingsModal strings to en.ts 2026-07-05 10:03:43 +02:00
zsviczian a214941abc 2.25.1 2026-07-04 20:06:39 +02:00
zsviczian 48f1fbaf2c added onSceneChangeHook example 2026-07-04 18:59:28 +02:00
zsviczian 55a2672ed7 updated llm training file 2026-07-04 18:45:02 +02:00
zsviczian b198020b2d initialization message 2026-07-04 17:55:26 +02:00
zsviczian d164be8ee5 extra bottom padding for tablet controls 2026-07-04 08:05:05 +02:00
zsviczian 6aa7d1f75c excalidrawLoading viewtype fixed 2026-07-04 07:59:04 +02:00
zsviczian 3b8deb0bb1 2.25.1-beta.0 2026-07-03 22:05:06 +02:00
zsviczian d4e28f160e fixing color picker 2026-07-03 22:02:43 +02:00
zsviczian 6ccb91b5cb added version string to capture note 2026-07-03 06:04:03 +00:00
zsviczian cfacb224be moved capture note to sidepanel 2026-07-03 05:47:38 +00:00
zsviczian e2575fdfbb attempt at resolving fs access codescanner warning. 2026-07-02 18:41:43 +02:00
zsviczian a9ab0e24d1 2.25.0 2026-07-01 21:57:17 +02:00
zsviczian 5a72fca8c7 2.25.0 release candidate 2 2026-07-01 21:39:30 +02:00
zsviczian b974467439 2.25.0 release candidate 2026-07-01 21:35:57 +02:00
zsviczian e0cf351061 lint and some type fixes 2026-07-01 20:13:17 +02:00
zsviczian 1d3c6388b5 type errors 2026-07-01 17:53:33 +02:00
zsviczian 5946bdb481 fix mainDocument 2026-07-01 17:45:04 +02:00
zsviczian 725ee9f764 fixed eslint-obsidian 0.4.0 type issues 2026-07-01 13:55:43 +00:00
zsviczian 6c49d4f042 type fixes 2026-07-01 13:46:00 +00:00
zsviczian 0ebccfecf8 fixed MindMap Builder: 2827 2026-07-01 13:20:14 +00:00
zsviczian a16006be2c fixed 2826 source url malformed 2026-07-01 11:55:51 +00:00
zsviczian 65dc6391c5 updated messages 2026-07-01 00:23:45 +02:00
zsviczian aea9461ad0 bump excalidraw extras minimum requirement 2026-07-01 00:18:47 +02:00
zsviczian 16369deb00 2.25.0-beta.5 2026-07-01 00:18:00 +02:00
zsviczian 1c04f1b483 fixed state management for editing self in customEmbeddable.ts 2026-07-01 00:17:38 +02:00
zsviczian 214c7f5a47 onSceneChangeHook 2026-06-30 13:37:37 +00:00
zsviczian f81ab8b3eb custom pen restore fixed 2026-06-30 11:22:33 +00:00
zsviczian 2f2dee5295 addressing custom pen reset part 1 2026-06-30 10:51:04 +00:00
zsviczian 57c18446e1 fixed Default undefined 2026-06-29 20:58:45 +02:00
zsviczian 7b49bded34 2.25.0-beta.4 2026-06-29 20:46:57 +02:00
zsviczian cf916b0da9 LaTeX in markdown images type fixes 2026-06-29 19:24:17 +02:00
zsviczian d4a99e86a8 Merge pull request #2822 from Jmarcos13/fix/mathjax-chtml-markdown-embed
fix: render MathJax CHTML formulas in markdown-embed SVG (#2818)
2026-06-29 18:35:25 +02:00
zsviczian c024f1cfa3 mindmap builder, presets, task date and link relative position change 2026-06-29 18:13:32 +02:00
zsviczian 3c95990d7a WIP MindMap Builder Preset changes 2026-06-29 17:53:56 +02:00
zsviczian b225dd77fe Capture Note update 2026-06-29 17:09:44 +02:00
Jmarcos13 08bbe656ff fix: render MathJax CHTML formulas in markdown-embed SVG (#2818)
Obsidian renders LaTeX via MathJax CHTML output, which relies on a
shared <style id=MJX-CHTML-styles> element injected into the document
head. When convertMarkdownToSVG captures the markdown note as an SVG,
that stylesheet was never included, so all math elements appeared blank.

- After MarkdownRenderer.render(), call mjx.typesetPromise() to ensure
  MathJax has finished typesetting the embedded note.
- Read MathJax CSS rules from the live CSSStyleSheet.cssRules (not
  textContent, which misses per-glyph rules added via insertRule()).
- Scope every CSSStyleRule selector with .excalidraw-md-host to prevent
  MathJax styles from bleeding into surrounding text.
- Inline all @font-face src URLs as base64 data URIs so fonts load
  correctly inside the data:image/svg+xml context.
- Cache the processed stylesheet by rule-count+last-rule fingerprint to
  avoid redundant work across multiple embeds in the same session.
- Inject the scoped stylesheet into both the measurement iframe and the
  final SVG <style> block.

Fixes #2818. Relates to #2282.
2026-06-29 07:05:47 -03:00
zsviczian 395b9591bd fix !important 2026-06-28 22:45:11 +02:00
zsviczian 3137ebc08b resolving type issues 2026-06-28 20:59:23 +02:00
81 changed files with 6313 additions and 2901 deletions

No files matched your search

+87 -1
View File
@@ -37,6 +37,92 @@ 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 using desktop only objects and functions such as Node Buffer, SharedArrayBuffer, etc. For the special case when this is required, make proper mobile safe guards.
- 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 +669,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.
@@ -1651,7 +1667,7 @@ export type ImageInfo = {
isHyperLink?: boolean;
hyperlink?: string;
file?: string | TFile;
hasSVGwithBitmap: boolean;
hasSVGwithBitmap?: boolean;
latex?: string;
size?: Size;
colorMap?: ColorMap;
@@ -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
@@ -725,3 +725,160 @@ ea.onTriggerAutoexportHook = (data) => {
// const decodedObsidianURI = decodeURIComponent(data.obsidianLink);
//};
/**
* 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.
*
* ⚠️ WARNING: PERFORMANCE IMPACT ⚠️
* Because this hook fires extremely frequently (dozens of times per second during drawing/panning),
* you MUST specify the appState keys you want to track (e.g., ['zoom', 'scrollX', 'scrollY'])
* OR set trackElements to true.
* If trackElements is falsy and appStateKeys is empty or undefined, the hook is ignored to prevent severe performance degradation.
*
* 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.
*
* Signature:
* onSceneChangeHook: {
* appStateKeys?: (keyof AppState)[];
* trackElements?: boolean;
* triggerWhenInvisible?: boolean;
* callback: (
* elements: readonly ExcalidrawElement[],
* appState: AppState,
* files: BinaryFiles,
* //Note: the ea object will not be set to the view and might be dirty
* //best practice: `ea.setView(view); ea.clear();`
* view: ExcalidrawView,
* ea: ExcalidrawAutomate
* ) => void;
* } | null = null;
*/
// ea.onSceneChangeHook = {
// appStateKeys: ["zoom", "scrollX", "scrollY"],
// trackElements: true,
// triggerWhenInvisible: false,
// callback: (elements, appState, files, view, hookEA) => {
// console.log(`Scene changed in ${view.file?.basename}:`, {
// zoom: appState.zoom.value,
// scrollX: appState.scrollX,
// scrollY: appState.scrollY,
// elementCount: elements.length
// });
// }
// };
// 1. Define the tools that should remember their own distinct styles.
// (We exclude tools like "selection", "eraser", or "laser" where persistent styling doesn't apply)
const STYLED_TOOLS = [
"freedraw",
"arrow",
"line",
"rectangle",
"ellipse",
"diamond",
"text"
];
// 2. Define all the specific AppState style properties we want to track and persist
const STYLES_TO_TRACK = [
"currentItemStrokeColor",
"currentItemBackgroundColor",
"currentItemFillStyle",
"currentItemStrokeWidth",
"currentItemStrokeWidthKey",
"currentItemStrokeStyle",
"currentItemRoughness",
"currentItemStrokeVariability",
"currentItemOpacity",
"currentItemFontFamily",
"currentItemFontSize",
"currentItemTextAlign",
"currentItemStartArrowhead",
"currentItemEndArrowhead",
"currentItemRoundness",
"currentItemArrowType",
"currentStrokeOptions" // Used by Custom Pens
];
// 3. Initialize the global cache, loading from localStorage so settings survive app restarts
if (!window.ExcalidrawToolStyleCache) {
const saved = localStorage.getItem("ExcalidrawToolStyleCache");
window.ExcalidrawToolStyleCache = saved ? JSON.parse(saved) : {};
}
// 4. Register the Hook
ea.onSceneChangeHook = {
// Only trigger the hook when the active tool or one of our tracked styles changes
appStateKeys: ["activeTool", ...STYLES_TO_TRACK],
trackElements: false,
triggerWhenInvisible: false,
callback: (elements, appState, files, view, ea) => {
const activeTool = appState.activeTool?.type;
if (!activeTool) return;
ea.setView(view);
ea.clear();
const cache = window.ExcalidrawToolStyleCache;
// We store the "last tool" state locally on the view instance.
// This prevents bugs if you have multiple Excalidraw panes open side-by-side.
const lastTool = view.excalidrawToolStyle_lastActiveTool;
// --- SCENARIO A: The User Switched Tools ---
if (activeTool !== lastTool) {
view.excalidrawToolStyle_lastActiveTool = activeTool;
// If the new tool is one of our managed drawing tools, restore its stored style
if (STYLED_TOOLS.includes(activeTool)) {
const storedStyle = cache[activeTool];
if (storedStyle) {
// Flag that we are applying a style programmatically so we don't treat it as a user modification
view.excalidrawToolStyle_applyingStyle = true;
ea.getExcalidrawAPI().updateScene({
appState: storedStyle
});
}
}
}
// --- SCENARIO B: The Tool Stayed the Same (User is tweaking styles) ---
else {
// Ignore the onSceneChange that gets fired immediately after we programmatically restore a style
if (view.excalidrawToolStyle_applyingStyle) {
view.excalidrawToolStyle_applyingStyle = false;
return;
}
// If we are actively using a drawing tool, track its style changes and update the cache
if (STYLED_TOOLS.includes(activeTool)) {
const currentStyle = {};
let styleChanged = false;
const storedStyle = cache[activeTool] || {};
for (const key of STYLES_TO_TRACK) {
currentStyle[key] = appState[key];
const val1 = currentStyle[key];
const val2 = storedStyle[key];
// Deep compare objects (like Roundness or Custom Pens settings), direct compare primitives
if (typeof val1 === "object" || typeof val2 === "object") {
if (JSON.stringify(val1) !== JSON.stringify(val2)) {
styleChanged = true;
}
} else if (val1 !== val2) {
styleChanged = true;
}
}
// If a change was detected, update the cache and persist it to localStorage
if (styleChanged) {
cache[activeTool] = currentStyle;
localStorage.setItem("ExcalidrawToolStyleCache", JSON.stringify(cache));
}
}
}
}
};
+378 -118
View File
@@ -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 = "v.260703";
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"));
@@ -571,15 +585,28 @@ async function ensureTargetFileExists(folder, filename, fname, opt, noteType) {
// Resolves the Obsidian leaf behavior and explicitly waits for load instantiation
async function openAndResolveTargetLeaf(file, originView, openNoteBBehavior) {
let noteBWorkspaceLeaf;
if (openNoteBBehavior === "adjacent pane") {
noteBWorkspaceLeaf = ea.openFileInNewOrAdjacentLeaf(file);
} else if (openNoteBBehavior === "new tab") {
noteBWorkspaceLeaf = app.workspace.getLeaf("tab");
await noteBWorkspaceLeaf.openFile(file, { active: true });
let noteBWorkspaceLeaf = null;
// Check if the file is already open in any existing leaf
app.workspace.iterateAllLeaves((leaf) => {
if (leaf.view && leaf.view.file && leaf.view.file.path === file.path) {
noteBWorkspaceLeaf = leaf;
}
});
if (noteBWorkspaceLeaf) {
app.workspace.setActiveLeaf(noteBWorkspaceLeaf, { focus: true });
} else {
noteBWorkspaceLeaf = originView.leaf;
await noteBWorkspaceLeaf.openFile(file, { active: true });
// Standard logic if it is not open yet
if (openNoteBBehavior === "adjacent pane") {
noteBWorkspaceLeaf = ea.openFileInNewOrAdjacentLeaf(file);
} else if (openNoteBBehavior === "new tab") {
noteBWorkspaceLeaf = app.workspace.getLeaf("tab");
await noteBWorkspaceLeaf.openFile(file, { active: true });
} else {
noteBWorkspaceLeaf = originView.leaf;
await noteBWorkspaceLeaf.openFile(file, { active: true });
}
}
// Explicitly wait until the target leaf has fully instantiated its File representation
@@ -704,7 +731,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 +876,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 +1105,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}]])`;
}
}
}
@@ -1302,16 +1329,35 @@ async function start() {
const captureData = await openCaptureModal(initialLinkText);
if (!captureData) return;
const { filename, noteType, format, ontologyAction, actionType, openNoteBBehavior, folder: customFolder } = captureData;
const { filename, noteType, format, ontologyAction, actionType, openNoteBBehavior, folder: customFolder, sidepanelWasVisible } = captureData;
// Inline cleanup helper attached to visibility flag
const closeSidepanelIfNeeded = () => {
if (!sidepanelWasVisible) {
const sidepanelLeaf = ea.getSidepanelLeaf();
if (sidepanelLeaf && sidepanelLeaf.view.containerEl.offsetParent !== null) {
ea.toggleSidepanelView();
}
}
};
const opt = settings.noteTypes[noteType];
if (!opt) {
new Notice("Error: Note Type configuration is missing. Open Settings to configure Note Types.");
closeSidepanelIfNeeded();
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,15 +1389,18 @@ 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;
if (!conflictDecision) {
closeSidepanelIfNeeded();
return;
}
if (conflictDecision.action === "CREATE_NEW") {
fileTarget = null;
@@ -1379,9 +1428,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;
@@ -1396,10 +1445,11 @@ async function start() {
ea.addText(0, 0, targetWikiLink);
await ea.addElementsToView(true, true, true);
ea.clear();
closeSidepanelIfNeeded();
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") {
@@ -1410,6 +1460,7 @@ async function start() {
ea.clear();
}
new Notice(`Created file: ${file.basename}`);
closeSidepanelIfNeeded();
return;
}
@@ -1430,7 +1481,10 @@ async function start() {
// 9. Ensure Target View is Excalidraw and get API
const target_ea = await prepareTargetExcalidrawView(noteBWorkspaceLeaf);
if (!target_ea) return;
if (!target_ea) {
closeSidepanelIfNeeded();
return;
}
// 10. Calculate insertion bounds on Target Note
const bElements = target_ea.getViewElements();
@@ -1453,39 +1507,15 @@ async function start() {
// 12. Final Focus / Zoom
await handleFinalActionFocus(actionType, originView, noteBWorkspaceLeaf, embeddedElementId, target_ea, format, preGeneratedFrameID, clonedTemplateElementIds, mmAPI);
// 13. Sidepanel cleanup
closeSidepanelIfNeeded();
}
// -------------------------------------------------------------
// 5. UI: Capture Note Modal (Refactored)
// -------------------------------------------------------------
function setupCaptureModalEscapeHandler(modal) {
const escapeKey = modal.scope.keys.find(k => k.key === "Escape");
if (escapeKey) {
const originalFunc = escapeKey.func;
escapeKey.func = (e) => {
// Block modal closure if a child suggester was just closed
if (suppressEscape) return false;
// Block modal closure if custom dropdown is open
const customDropdown = modal.modalEl.querySelector(".mindmap-search-results");
if (customDropdown && customDropdown.style.display === "block") {
customDropdown.style.display = "none";
return false;
}
// Block modal closure if any standard Obsidian suggester is currently open
const suggests = document.body.querySelectorAll('.suggestion-container');
for (const s of suggests) {
if (s.style.display !== "none") {
return false;
}
}
return originalFunc(e);
};
}
}
function injectCaptureModalStyles(contentEl) {
contentEl.createEl("style", {
text: `
@@ -1500,42 +1530,31 @@ function injectCaptureModalStyles(contentEl) {
.mindmap-search-item.is-selected { background-color: var(--background-modifier-hover); }
.link-type-row-control { display: flex; align-items: center; gap: 8px; width: 100%; justify-content: flex-end; }
/* Modal Restyling for single-row / responsive layouts */
/* Fluid Container-Agnostic Layout (No @media queries needed) */
.excalidraw-capture-note-modal .setting-item {
display: flex;
flex-wrap: wrap;
flex-wrap: wrap; /* Allows wrapping when sidepanel is thin */
align-items: center;
justify-content: space-between;
gap: 12px;
gap: 8px;
padding: 8px 0; /* Shrink vertical padding */
min-height: auto; /* Override native Obsidian large min-height on mobile */
border-top: none;
}
.excalidraw-capture-note-modal .setting-item-info {
flex: 0 1 auto;
white-space: nowrap;
min-width: max-content;
flex: 1 1 120px; /* Base width of 120px, grows if space permits */
white-space: normal;
margin-top: 4px;
}
.excalidraw-capture-note-modal .setting-item-control {
flex: 1 1 200px;
flex: 2 1 200px; /* Base width of 200px. If container < 320px, it wraps to next line */
justify-content: flex-end;
min-width: 200px;
width: 100%; /* Expands to full width when wrapped */
}
.excalidraw-capture-note-modal .setting-item-control input[type="text"],
.excalidraw-capture-note-modal .setting-item-control select {
width: 100%;
}
@media (max-width: 450px) {
.excalidraw-capture-note-modal .setting-item {
flex-direction: column;
align-items: flex-start;
gap: 4px;
}
.excalidraw-capture-note-modal .setting-item-control {
width: 100%;
justify-content: stretch;
}
.excalidraw-capture-note-modal .setting-item-info {
white-space: normal;
}
}
`
});
}
@@ -1546,15 +1565,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 +1586,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) {
@@ -1739,7 +1805,7 @@ function buildCaptureSearchBox(contentEl, state, callbacks) {
}
}
function buildCaptureLinkTypeSelector(contentEl, state, callbacks) {
function buildCaptureLinkTypeSelector(contentEl, state, callbacks, tab) {
const noteTypeKeys = Object.keys(settings.noteTypes).sort();
let selectedNoteType = state.selectedNoteType;
if (!selectedNoteType || !noteTypeKeys.includes(selectedNoteType)) {
@@ -1747,12 +1813,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 +1838,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 +1851,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 +1860,48 @@ 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;
state.selectedNoteType = targetName;
settings.lastSelectedNoteType = targetName;
if(tab && typeof tab.onOpen === "function") {
tab.onOpen(); // Re-render the capture tab inline
}
}, true);
});
});
callbacks.updateIconPreview();
}
@@ -1846,12 +1953,16 @@ function buildCaptureOntologySelector(contentEl, state, callbacks) {
});
}
function buildCaptureFooter(contentEl, state, modal) {
function buildCaptureFooter(contentEl, state, tab) {
// Footer is a normal non-wrapping flex row. `align-items: flex-end` forces the cog down when the button group expands vertically.
const footer = contentEl.createDiv({
attr: { style: "display: flex; justify-content: space-between; align-items: center; margin-top: 20px; flex-direction: row-reverse;" }
attr: { style: "display: flex; justify-content: space-between; align-items: flex-end; margin-top: 20px; gap: 10px; margin-bottom: 30px;" }
});
const buttonGroup = footer.createDiv({ attr: { style: "display: flex; gap: 8px; flex-direction: row-reverse;" } });
// buttonGroup gets CSS order 2 so it sits on the right visually
const buttonGroup = footer.createDiv({
attr: { style: "display: flex; gap: 8px; flex-wrap: wrap; justify-content: flex-end; flex: 1 1 auto; order: 2;" }
});
const handleAction = (actionType) => {
const val = state.ui.searchInput.getValue().trim();
@@ -1862,49 +1973,95 @@ function buildCaptureFooter(contentEl, state, modal) {
state.finalData = {
filename: val,
folder: folderVal,
useRelativeFolder: state.useRelativeFolder,
noteType: state.selectedNoteType,
format: state.selectedFormat,
ontologyAction: state.selectedOntology,
actionType,
openNoteBBehavior: state.openNoteBBehavior
openNoteBBehavior: state.openNoteBBehavior,
sidepanelWasVisible: state.sidepanelWasVisible
};
modal.close();
tab.close();
};
const captureBtn = buttonGroup.createEl("button", { text: "Capture Note", cls: "mod-cta" });
// Assign CSS `order` so visual LTR layout matches standard wrap behavior
// (Items with higher order appear further right, and will drop to the bottom line first when wrapped)
const captureBtn = buttonGroup.createEl("button", {
text: "Capture",
cls: "mod-cta",
attr: {
style: "order: 4;",
"aria-label": "Create the note, add backlinks/embeds, and open it for editing."
}
});
captureBtn.addEventListener("click", () => handleAction("CAPTURE"));
const linkOnlyBtn = buttonGroup.createEl("button", { text: "Link Only" });
const linkOnlyBtn = buttonGroup.createEl("button", {
text: "Link",
attr: {
style: "order: 3;",
"aria-label": "Link to an item without creating the note and without opening it for editing."
}
});
linkOnlyBtn.addEventListener("click", () => handleAction("ADD_LINK_ONLY"));
const linkCreateBtn = buttonGroup.createEl("button", { text: "Link & Create" });
const linkCreateBtn = buttonGroup.createEl("button", {
text: "Link + File",
attr: {
style: "order: 2;",
"aria-label": "Link to the item and create its note/file in the background (but do not open for note taking)."
}
});
linkCreateBtn.addEventListener("click", () => handleAction("ADD_LINK_CREATE"));
const captureHereBtn = buttonGroup.createEl("button", { text: "Capture Here" });
const captureHereBtn = buttonGroup.createEl("button", { text: "Capture Here", attr: { style: "order: 1;" } });
captureHereBtn.style.display = state.selectedFormat === "Markdown" ? "" : "none";
captureHereBtn.addEventListener("click", () => handleAction("CAPTURE_HERE"));
state.ui.captureHereBtnReference = captureHereBtn;
const cogBtn = footer.createEl("button", { cls: "clickable-icon" });
// Cog gets CSS order 1 in the main footer container so it sits on the left visually
const cogBtn = footer.createEl("button", { cls: "clickable-icon", attr: { style: "order: 1; margin: auto;" } });
cogBtn.innerHTML = ea.obsidian.getIcon("settings").outerHTML;
cogBtn.addEventListener("click", () => {
window.ExcalidrawCaptureNoteScript.tempSearchValue = state.ui.searchInput.getValue().trim();
modal.close();
openSettingsModal();
// Crucially: Do not call tab.close() here.
openSettingsModal(tab);
});
}
async function openCaptureModal(initialSearchValue) {
return new Promise(resolve => {
const modal = new ea.FloatingModal(app);
modal.enableKeyCapture();
return new Promise(async resolve => {
setupCaptureModalEscapeHandler(modal);
// Assess visibility state before grabbing the tab
const sidepanelLeaf = ea.getSidepanelLeaf();
let sidepanelWasVisible = false;
if (sidepanelLeaf && sidepanelLeaf.view.containerEl.offsetParent !== null) {
sidepanelWasVisible = true;
}
modal.modalEl.style.width = "480px";
modal.modalEl.style.maxWidth = "100%";
modal.modalEl.classList.add("excalidraw-capture-note-modal");
modal.titleEl.setText("Capture Contextual Note");
const tab = await ea.createSidepanelTab("Capture Contextual Note", false, true);
if (!tab) {
resolve(null);
return;
}
tab.containerEl.classList.add("excalidraw-capture-note-modal");
// Clear default title text and convert to a flex container to align elements
tab.titleEl.empty();
tab.titleEl.style.display = "flex";
tab.titleEl.style.justifyContent = "space-between";
tab.titleEl.style.alignItems = "center";
tab.titleEl.style.width = "100%";
// Add Main Title
tab.titleEl.createSpan({ text: "Capture Contextual Note" });
// Add right-aligned Version string
tab.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 +2127,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,
@@ -1980,6 +2138,7 @@ async function openCaptureModal(initialSearchValue) {
selectedOntology: "",
allFiles: allFiles,
searchItems: searchItems,
sidepanelWasVisible: sidepanelWasVisible, // Include visibility state
ui: {}
};
@@ -2041,6 +2200,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;
}
}
@@ -2050,25 +2214,34 @@ async function openCaptureModal(initialSearchValue) {
}
};
modal.onOpen = () => {
const { contentEl } = modal;
tab.onOpen = () => {
const { contentEl } = tab;
contentEl.empty();
injectCaptureModalStyles(contentEl);
buildCaptureFolderBox(contentEl, state);
buildCaptureSearchBox(contentEl, state, callbacks);
buildCaptureLinkTypeSelector(contentEl, state, callbacks);
buildCaptureLinkTypeSelector(contentEl, state, callbacks, tab);
buildCaptureFormatSelector(contentEl, state);
buildCaptureOpenBehaviorSelector(contentEl, state);
buildCaptureOntologySelector(contentEl, state, callbacks);
buildCaptureFooter(contentEl, state, modal);
buildCaptureFooter(contentEl, state, tab);
// Allow normal folder resets to happen on subsequent typing
state.isInitializing = false;
};
modal.onClose = () => resolve(state.finalData);
modal.open();
tab.onClose = () => {
// Clean up the sidepanel if we revealed it just for this script but it didn't complete
if (!state.finalData && !state.sidepanelWasVisible) {
const sidepanelLeaf = ea.getSidepanelLeaf();
if (sidepanelLeaf && sidepanelLeaf.view.containerEl.offsetParent !== null) {
ea.toggleSidepanelView();
}
}
resolve(state.finalData);
};
tab.open();
});
}
@@ -2076,7 +2249,7 @@ async function openCaptureModal(initialSearchValue) {
// 6. UI: Settings & Multi-tier Configuration Modal (Refactored)
// -------------------------------------------------------------
function buildSettingsHeader(contentEl, modal) {
function buildSettingsHeader(contentEl, modal, captureTab) {
const headerContainer = contentEl.createDiv({ cls: "settings-header-container" });
headerContainer.createEl("h2", { text: "DNP Workflows Configuration Panel", attr: { style: "margin:0;" } });
@@ -2084,7 +2257,14 @@ function buildSettingsHeader(contentEl, modal) {
topSaveBtn.addEventListener("click", () => {
ea.setScriptSettings(settings);
modal.close();
start();
// Instead of calling start() and creating an orphaned secondary sidepanel context,
// we instruct the current sidepanel to safely re-paint itself inline.
if (captureTab && typeof captureTab.onOpen === "function") {
captureTab.onOpen();
} else {
start();
}
});
}
@@ -2393,6 +2573,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 +2596,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();
@@ -2422,7 +2617,7 @@ function buildNoteTypesSection(contentEl) {
// -------------------------------------------------------------
// Settings Orchestrator
// -------------------------------------------------------------
function openSettingsModal() {
function openSettingsModal(captureTab = null) {
const modal = new ea.obsidian.Modal(app);
modal.titleEl.setText("");
@@ -2444,7 +2639,7 @@ function openSettingsModal() {
`
});
buildSettingsHeader(contentEl, modal);
buildSettingsHeader(contentEl, modal, captureTab);
buildVisualSizingSection(contentEl);
buildVisualTemplateSection(contentEl);
buildPropertyInjectionSection(contentEl);
@@ -2462,12 +2657,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 +2720,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 +2791,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 +2928,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();
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1
View File
@@ -77,6 +77,7 @@ const precision = [1,2,2,3];
const minLigtness = 1/Math.pow(10,precision[2]);
const maxLightness = 100 - minLigtness;
const minSaturation = 1/Math.pow(10,precision[2]);
let dirty = false;
let settings = ea.getScriptSettings();
//set default values on first run
+2 -2
View File
@@ -649,7 +649,7 @@
},
{
"fname": "Mindmap Builder.md",
"mtime": 1781460603530
"mtime": 1782911969336
},
{
"fname": "Mindmap Builder.svg",
@@ -665,7 +665,7 @@
},
{
"fname": "Capture Note.md",
"mtime": 1780986335837
"mtime": 1783058611857
},
{
"fname": "Capture Note.svg",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.25.0-beta.3",
"version": "2.25.2-beta.1",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "obsidian-excalidraw-plugin",
"name": "Excalidraw",
"version": "2.24.2",
"version": "2.25.1",
"minAppVersion": "1.8.7",
"description": "Sketch Your Mind. Edit and view Excalidraw drawings. Enter the world of 4D Visual PKM.",
"author": "Zsolt Viczian",
+41 -26
View File
@@ -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.112",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -28,7 +28,6 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"roughjs": "^4.5.2",
"woff2sfnt-sfnt2woff": "^1.0.0",
"yaml": "^2.9.0"
},
"devDependencies": {
@@ -60,7 +59,7 @@
"cssnano": "^6.0.2",
"eslint": "^9.39.4",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-obsidianmd": "^0.3.0",
"eslint-plugin-obsidianmd": "^0.4.0",
"eslint-plugin-prettier": "^5.0.0",
"jiti": "^2.6.1",
"jsesc": "^3.0.2",
@@ -1840,6 +1839,36 @@
"w3c-keyname": "^2.2.4"
}
},
"node_modules/@eslint-community/eslint-plugin-eslint-comments": {
"version": "4.7.2",
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-plugin-eslint-comments/-/eslint-plugin-eslint-comments-4.7.2.tgz",
"integrity": "sha512-LF03qURSwEWm2dz5wtdDCzNk+7Opl0X7q6I3undsaIuNsEiNvRV3BCtqu14Q/6Pzg1tBj44LcxpW2EpSLZStZw==",
"dev": true,
"license": "MIT",
"dependencies": {
"escape-string-regexp": "^4.0.0",
"ignore": "^7.0.5"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": {
"url": "https://opencollective.com/eslint"
},
"peerDependencies": {
"eslint": "^6.0.0 || ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0"
}
},
"node_modules/@eslint-community/eslint-plugin-eslint-comments/node_modules/ignore": {
"version": "7.0.5",
"resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz",
"integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 4"
}
},
"node_modules/@eslint-community/eslint-utils": {
"version": "4.9.1",
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz",
@@ -5232,9 +5261,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.112",
"resolved": "https://registry.npmjs.org/@zsviczian/excalidraw/-/excalidraw-0.18.112.tgz",
"integrity": "sha512-2DkMToE6L6yxgbEQJNWYZQLUVlt9DUACPHcFIX0Cy6pV2kUS27EPW+2fNaZsWHu3ihnyreaUeqUxk1VzQ4qIRA==",
"license": "MIT",
"dependencies": {
"@braintree/sanitize-url": "6.0.2",
@@ -7967,12 +7996,13 @@
}
},
"node_modules/eslint-plugin-obsidianmd": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-obsidianmd/-/eslint-plugin-obsidianmd-0.3.0.tgz",
"integrity": "sha512-QvGDI6B2nxJBrsZKGTg31da2A/fEJNlnwN+fRZkaoPIu1QL3fYXUdpP7ThyMdr/0iTYQxifb9lt2X9cpydQx1w==",
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-obsidianmd/-/eslint-plugin-obsidianmd-0.4.0.tgz",
"integrity": "sha512-qZsh8ydaeO7bC+XADWHGG9+CEwiKjoL7arZo1I93e0UHdQ863Jzt+xRk5VI0vo97SIJrA4vWwuz9K9/fggO35g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/eslint-plugin-eslint-comments": "^4.7.2",
"@eslint/config-helpers": "^0.4.2",
"@eslint/js": "^9.30.1",
"@eslint/json": "0.14.0",
@@ -7981,7 +8011,7 @@
"@types/node": "20.12.12",
"@typescript-eslint/types": "^8.33.1",
"@typescript-eslint/utils": "^8.33.1",
"eslint": ">=9.0.0",
"eslint": ">=9.19.0",
"eslint-plugin-depend": "1.3.1",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-json-schema-validator": "5.1.0",
@@ -8002,7 +8032,7 @@
"peerDependencies": {
"@eslint/js": "^9.30.1",
"@eslint/json": "0.14.0",
"eslint": ">=9.0.0",
"eslint": ">=9.19.0",
"obsidian": "1.8.7",
"typescript-eslint": "^8.35.1"
}
@@ -13432,21 +13462,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/woff2sfnt-sfnt2woff": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/woff2sfnt-sfnt2woff/-/woff2sfnt-sfnt2woff-1.0.0.tgz",
"integrity": "sha512-edK4COc1c1EpRfMqCZO1xJOvdUtM5dbVb9iz97rScvnTevqEB3GllnLWCmMVp1MfQBdF1DFg/11I0rSyAdS4qQ==",
"license": "MIT",
"dependencies": {
"pako": "^1.0.7"
}
},
"node_modules/woff2sfnt-sfnt2woff/node_modules/pako": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
"integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
"license": "(MIT AND Zlib)"
},
"node_modules/word-wrap": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz",
+2 -3
View File
@@ -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.112",
"chroma-js": "^3.1.2",
"clsx": "^2.0.0",
"es6-promise-pool": "2.5.0",
@@ -44,7 +44,6 @@
"react": "^18.2.0",
"react-dom": "^18.2.0",
"roughjs": "^4.5.2",
"woff2sfnt-sfnt2woff": "^1.0.0",
"yaml": "^2.9.0"
},
"devDependencies": {
@@ -76,7 +75,7 @@
"cssnano": "^6.0.2",
"eslint": "^9.39.4",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-obsidianmd": "^0.3.0",
"eslint-plugin-obsidianmd": "^0.4.0",
"eslint-plugin-prettier": "^5.0.0",
"jiti": "^2.6.1",
"jsesc": "^3.0.2",
+33 -10
View File
@@ -132,8 +132,8 @@ if (!isLib) {
}
const packageString = isLib
? ""
: ';const INITIAL_TIMESTAMP=Date.now();\n' +
? ""
: ';const INITIAL_TIMESTAMP=Date.now();\n' +
'const pako = (function() {\n' +
' const module = { exports: {} };\n' +
' const exports = module.exports;\n' +
@@ -156,7 +156,22 @@ const packageString = isLib
'let {react, reactDOM } = new Function(`${REACT_PACKAGES}; return {react: React, reactDOM: ReactDOM};`)();\n' +
'let excalidrawLib = {};\n' +
`const PLUGIN_LANGUAGES = {${LANGUAGES.map(lang => `"${lang}": "${compressLanguageFile(lang)}"`).join(",")}};\n` +
'const PLUGIN_VERSION="' + manifest.version + '";';
//These declarations were moved here because Obsidian code scanner incorrectly flags them with a warning,
//but without offering a proper resolution, or a stepout process to remove them from scanner results.
//for context you can read different issues I raised with the Obsidian team about these.
//Once there is a workable resolution I am moving them back to their original locations, since having them here
//is not at all ideal.
//https://github.com/obsidianmd/eslint-plugin/issues/175
`const getCaretRangeFromPoint = (doc, x, y) => doc.caretRangeFromPoint?.(x, y);\n` +
//There isn't a process for flagging deliberate use of main document instead of activeDocument
//The blanket rule by the eslint-plugin makes sense for many cases, but does not address special case needs
`const mainDocument = document;\n` +
//Fetch is the only valid approach in case of loading binary data such as fonts to dataURL (i.e. not network related)
//I've also had cases in the past where requestUrl failed with certain endpoints, for those cases I have
//fetch in the codebase as a fallback from requestUrl.
//https://github.com/obsidianmd/eslint-plugin/issues/176
`const deliberateFetch = async (payload, init) => await fetch(payload, init);\n` +
`const PLUGIN_VERSION="${manifest.version}";\n`;
const BASE_CONFIG = {
input: 'src/core/main.ts',
@@ -186,6 +201,14 @@ const getRollupPlugins = (tsconfig, ...plugins) => [
preventAssignment: true,
"process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
}),
replace({ //This is a workaround to silence Obsidian codescanner complain about fs module usage in the plugin code. The plugin does not use fs module, but it is used by some dependencies.
preventAssignment: true,
delimiters: ['', ''],
values: {
"require('fs')": "null",
'require("fs")': "null"
}
}),
commonjs(),
nodeResolve({ browser: true, preferBuiltins: false }),
].concat(plugins);
@@ -219,16 +242,16 @@ const BUILD_CONFIG = {
],
]),
/*visualizer({
filename: 'bundle-analysis.html',
open: true, // Automatically opens in your browser when the build finishes
gzipSize: true,
brotliSize: true,
}),*/
filename: 'bundle-analysis.html',
open: true, // Automatically opens in your browser when the build finishes
gzipSize: true,
brotliSize: true,
}),*/
] : [
postprocess([ [/var React = require\('react'\);/, packageString] ]),
postprocess([[/var React = require\('react'\);/, packageString]]),
]),
copy({
targets: [ { src: 'manifest.json', dest: DIST_FOLDER } ],
targets: [{ src: 'manifest.json', dest: DIST_FOLDER }],
verbose: true,
}),
),
+1 -2
View File
@@ -1,9 +1,8 @@
import { getIcon, sanitizeHTMLToDom } from "obsidian";
import { PenStyle } from "src/types/penTypes";
import React from "react";
import { mainDocument } from "./constants";
import { isInstanceOfSVGSVGElement } from "src/utils/typechecks";
declare const mainDocument: Document;
const BLOCKED_SVG_TAGS = new Set([
"script",
"foreignobject",
+41
View File
@@ -277,3 +277,44 @@
* ) => void = null;
*/
//ea.onCanvasColorChangeHook = (ea, view, color) => {};
/**
* If set, this callback is triggered when the scene changes in any of the Excalidraw Views.
* You can use this to react to appState or element changes.
* Note, the ea object the callback receives is not guaranteed to have its targetView set to view, and the EA workbench might be dirty.
* As best practice, if you want to write back to the sending view, I recommend initializing ExcalidrawView first inside the callback:
* ea.setView(view); ea.clear();
*
* WARNING: PERFORMANCE IMPACT
* Because this hook fires extremely frequently (dozens of times per second during drawing/panning),
* you MUST specify the appState keys you want to track (e.g., ['zoom', 'scrollX', 'scrollY'])
* OR set trackElements to true.
* If trackElements is falsy and appStateKeys is empty or undefined, the hook is ignored to prevent severe performance degradation.
*
* Signature:
* onSceneChangeHook: {
* appStateKeys?: (keyof AppState)[];
* trackElements?: boolean;
* triggerWhenInvisible?: boolean;
* callback: (
* elements: readonly ExcalidrawElement[],
* appState: AppState,
* files: BinaryFiles,
* view: ExcalidrawView,
* ea: ExcalidrawAutomate
* ) => void;
* } | null = null;
*/
// ea.onSceneChangeHook = {
// appStateKeys: ["zoom", "scrollX", "scrollY"],
// trackElements: true,
// triggerWhenInvisible: false,
// callback: (elements, appState, files, view, hookEA) => {
// console.log(`Scene changed in ${view.file?.basename}:`, {
// zoom: appState.zoom.value,
// scrollX: appState.scrollX,
// scrollY: appState.scrollY,
// elementCount: elements.length
// });
// }
// };
+4 -6
View File
@@ -9,8 +9,7 @@ import { setStyle } from "src/utils/styleUtils";
//This is only for backward compatibility because an early version of obsidian included an encoding to avoid fantom links from littering Obsidian graph view
declare const PLUGIN_VERSION: string;
export let EXCALIDRAW_PLUGIN: ExcalidrawPlugin = null;
// eslint-disable-next-line obsidianmd/prefer-active-doc
export const mainDocument = document; //signals deliberate use of main document instead of activeDocument
declare const mainDocument: Document; //signals deliberate use of main document instead of activeDocument
export const setExcalidrawPlugin = (plugin: ExcalidrawPlugin) => {
EXCALIDRAW_PLUGIN = plugin;
};
@@ -239,8 +238,6 @@ export const ROUNDNESS = {
ADAPTIVE_RADIUS: 3,
} as const;
export const THEME_FILTER = "invert(93%) hue-rotate(180deg) saturate(1.25)";
export const GITHUB_RELEASES =
URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG;
export const URLFETCHTIMEOUT = 3000;
export const PLUGIN_ID = "obsidian-excalidraw-plugin";
export const SCRIPT_INSTALL_CODEBLOCK = "excalidraw-script-install";
@@ -460,8 +457,9 @@ export const ICON_NAME = "excalidraw-icon";
export const MAX_COLORS = 5;
export const COLOR_FREQ = 6;
export const RERENDER_EVENT = "excalidraw-embed-rerender";
export const BLANK_DRAWING = `{"type":"excalidraw","version":2,"source":"${GITHUB_RELEASES + PLUGIN_VERSION}","elements":[],"appState":{"gridSize":null,"viewBackgroundColor":"#ffffff"}}`;
export const DARK_BLANK_DRAWING = `{"type":"excalidraw","version":2,"source":"${GITHUB_RELEASES + PLUGIN_VERSION}","elements":[],"appState":{"theme":"dark","gridSize":null,"viewBackgroundColor":"#ffffff"}}`;
const blankDrawingBase = `{"type":"excalidraw","version":2,"source":"${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/${PLUGIN_VERSION}","elements":[],"appState":{"gridSize":null,"viewBackgroundColor":"#ffffff"`;
export const BLANK_DRAWING = `${blankDrawingBase}}}`;
export const DARK_BLANK_DRAWING = `${blankDrawingBase},"theme":"dark"}}`;
export const FRONTMATTER = [
"---",
"",
+1 -10
View File
@@ -164,11 +164,6 @@ export const URL_REGISTRY = {
"https://youtube.com/shorts/O_1ls9c6wBY?feature=share",
UrlPurpose.VIDEO,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG_1_6_23:
defineUrl(
"https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.6.23",
UrlPurpose.RELEASE_LOG,
),
EN_WIKIPEDIA_ORG_WIKI_SCALABLE_VECTOR_GRAPHICS: defineUrl(
"https://en.wikipedia.org/wiki/Scalable_Vector_Graphics",
UrlPurpose.DOCS,
@@ -219,7 +214,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,
@@ -301,10 +296,6 @@ export const URL_REGISTRY = {
"https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag",
UrlPurpose.RELEASE_LOG,
),
GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG_1_9_9: defineUrl(
"https://github.com/zsviczian/obsidian-excalidraw-plugin/releases/tag/1.9.9",
UrlPurpose.RELEASE_LOG,
),
TRANSLATE_GOOGLE_COM: defineUrl(
"https://translate.google.com/?sl=en&tl=zh-CN&text=This%20file%20contains%20embedded%20frames%20which%20will%20be%20migrated%20to%20a%20newer%20version%20for%20compatibility%20with%20excalidraw.com.%0A%0AIf%20you%27re%20using%20Obsidian%20on%20multiple%20devices%2C%20you%20may%20proceed%20now%2C%20but%20please%2C%20before%20opening%20this%20file%20on%20your%20other%20devices%2C%20update%20Excalidraw%20on%20those%20as%20well.%0A%0AMore%20info%20is%20available%20here%3A%20https%3A%2F%2Fgithub.com%2Fzsviczian%2Fobsidian-excalidraw-plugin%2Freleases%2Ftag%2F1.9.9%27%3Ehere%3C%2Fa%3E.&op=translate",
UrlPurpose.TRANSLATION,
+1 -1
View File
@@ -9,5 +9,5 @@ console.log("String copied to clipboard");
export const startupScript = () =>
atob(
"LyoKI2V4Y2x1ZGUKYGBganMqLwovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCB3aGVuIHRoZSB1c2VyIGNsb3NlcyBhbiBFeGNhbGlkcmF3IHZpZXcuCiAqICAgb25WaWV3VW5sb2FkSG9vazogKHZpZXc6IEV4Y2FsaWRyYXdWaWV3KSA9PiB2b2lkID0gbnVsbDsKICovCi8vZWEub25WaWV3VW5sb2FkSG9vayA9ICh2aWV3KSA9PiB7fTsKCi8qKgogKiBJZiBzZXQsIHRoaXMgY2FsbGJhY2sgaXMgdHJpZ2dlcmVkLCB3aGVuIHRoZSB1c2VyIGNoYW5nZXMgdGhlIHZpZXcgbW9kZS4KICogWW91IGNhbiB1c2UgdGhpcyBjYWxsYmFjayBpbiBjYXNlIHlvdSB3YW50IHRvIGRvIHNvbWV0aGluZyBhZGRpdGlvbmFsIHdoZW4gdGhlIHVzZXIgc3dpdGNoZXMgdG8gdmlldyBtb2RlIGFuZCBiYWNrLgogKiAgIG9uVmlld01vZGVDaGFuZ2VIb29rOiAoaXNWaWV3TW9kZUVuYWJsZWQ6Ym9vbGVhbiwgdmlldzogRXhjYWxpZHJhd1ZpZXcsIGVhOiBFeGNhbGlkcmF3QXV0b21hdGUpID0+IHZvaWQgPSBudWxsOwogKi8KLy9lYS5vblZpZXdNb2RlQ2hhbmdlSG9vayA9IChpc1ZpZXdNb2RlRW5hYmxlZCwgdmlldywgZWEpID0+IHt9OwoKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gdGhlIHVzZXIgaG92ZXJzIGEgbGluayBpbiB0aGUgc2NlbmUuCiAqIFlvdSBjYW4gdXNlIHRoaXMgY2FsbGJhY2sgaW4gY2FzZSB5b3Ugd2FudCB0byBkbyBzb21ldGhpbmcgYWRkaXRpb25hbCB3aGVuIHRoZSBvbkxpbmtIb3ZlciBldmVudCBvY2N1cnMuCiAqIFRoaXMgY2FsbGJhY2sgbXVzdCByZXR1cm4gYSBib29sZWFuIHZhbHVlLgogKiBJbiBjYXNlIHlvdSB3YW50IHRvIHByZXZlbnQgdGhlIGV4Y2FsaWRyYXcgb25MaW5rSG92ZXIgYWN0aW9uIHlvdSBtdXN0IHJldHVybiBmYWxzZSwgaXQgd2lsbCBzdG9wIHRoZSBuYXRpdmUgZXhjYWxpZHJhdyBvbkxpbmtIb3ZlciBtYW5hZ2VtZW50IGZsb3cuCiAqICAgb25MaW5rSG92ZXJIb29rOiAoCiAqICAgICBlbGVtZW50OiBOb25EZWxldGVkRXhjYWxpZHJhd0VsZW1lbnQsCiAqICAgICBsaW5rVGV4dDogc3RyaW5nLAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXcsCiAqICAgICBlYTogRXhjYWxpZHJhd0F1dG9tYXRlCiAqICAgKSA9PiBib29sZWFuID0gbnVsbDsKICovCi8vZWEub25MaW5rSG92ZXJIb29rID0gKGVsZW1lbnQsIGxpbmtUZXh0LCB2aWV3LCBlYSkgPT4ge307CiAgIAovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCwgd2hlbiB0aGUgdXNlciBjbGlja3MgYSBsaW5rIGluIHRoZSBzY2VuZS4KICogWW91IGNhbiB1c2UgdGhpcyBjYWxsYmFjayBpbiBjYXNlIHlvdSB3YW50IHRvIGRvIHNvbWV0aGluZyBhZGRpdGlvbmFsIHdoZW4gdGhlIG9uTGlua0NsaWNrIGV2ZW50IG9jY3Vycy4KICogVGhpcyBjYWxsYmFjayBtdXN0IHJldHVybiBhIGJvb2xlYW4gdmFsdWUuCiAqIEluIGNhc2UgeW91IHdhbnQgdG8gcHJldmVudCB0aGUgZXhjYWxpZHJhdyBvbkxpbmtDbGljayBhY3Rpb24geW91IG11c3QgcmV0dXJuIGZhbHNlLCBpdCB3aWxsIHN0b3AgdGhlIG5hdGl2ZSBleGNhbGlkcmF3IG9uTGlua0NsaWNrIG1hbmFnZW1lbnQgZmxvdy4KICogICBvbkxpbmtDbGlja0hvb2s6KAogKiAgICAgZWxlbWVudDogRXhjYWxpZHJhd0VsZW1lbnQsCiAqICAgICBsaW5rVGV4dDogc3RyaW5nLAogKiAgICAgZXZlbnQ6IE1vdXNlRXZlbnQsCiAqICAgICB2aWV3OiBFeGNhbGlkcmF3VmlldywKICogICAgIGVhOiBFeGNhbGlkcmF3QXV0b21hdGUKICogICApID0+IGJvb2xlYW4gPSBudWxsOwogKi8KLy9lYS5vbkxpbmtDbGlja0hvb2sgPSAoZWxlbWVudCxsaW5rVGV4dCxldmVudCwgdmlldywgZWEpID0+IHt9OwogICAKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gRXhjYWxpZHJhdyByZWNlaXZlcyBhbiBvbkRyb3AgZXZlbnQuIAogKiBZb3UgY2FuIHVzZSB0aGlzIGNhbGxiYWNrIGluIGNhc2UgeW91IHdhbnQgdG8gZG8gc29tZXRoaW5nIGFkZGl0aW9uYWwgd2hlbiB0aGUgb25Ecm9wIGV2ZW50IG9jY3Vycy4KICogVGhpcyBjYWxsYmFjayBtdXN0IHJldHVybiBhIGJvb2xlYW4gdmFsdWUuCiAqIEluIGNhc2UgeW91IHdhbnQgdG8gcHJldmVudCB0aGUgZXhjYWxpZHJhdyBvbkRyb3AgYWN0aW9uIHlvdSBtdXN0IHJldHVybiBmYWxzZSwgaXQgd2lsbCBzdG9wIHRoZSBuYXRpdmUgZXhjYWxpZHJhdyBvbkRyb3AgbWFuYWdlbWVudCBmbG93LgogKiAgIG9uRHJvcEhvb2s6IChkYXRhOiB7CiAqICAgICBlYTogRXhjYWxpZHJhd0F1dG9tYXRlOwogKiAgICAgZXZlbnQ6IFJlYWN0LkRyYWdFdmVudDxIVE1MRGl2RWxlbWVudD47CiAqICAgICBkcmFnZ2FibGU6IGFueTsgLy9PYnNpZGlhbiBkcmFnZ2FibGUgb2JqZWN0CiAqICAgICB0eXBlOiAiZmlsZSIgfCAidGV4dCIgfCAidW5rbm93biI7CiAqICAgICBwYXlsb2FkOiB7CiAqICAgICAgIGZpbGVzOiBURmlsZVtdOyAvL1RGaWxlW10gYXJyYXkgb2YgZHJvcHBlZCBmaWxlcwogKiAgICAgICB0ZXh0OiBzdHJpbmc7IC8vc3RyaW5nCiAqICAgICB9OwogKiAgICAgZXhjYWxpZHJhd0ZpbGU6IFRGaWxlOyAvL3RoZSBmaWxlIHJlY2VpdmluZyB0aGUgZHJvcCBldmVudAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXc7IC8vdGhlIGV4Y2FsaWRyYXcgdmlldyByZWNlaXZpbmcgdGhlIGRyb3AKICogICAgIHBvaW50ZXJQb3NpdGlvbjogeyB4OiBudW1iZXI7IHk6IG51bWJlciB9OyAvL3RoZSBwb2ludGVyIHBvc2l0aW9uIG9uIGNhbnZhcyBhdCB0aGUgdGltZSBvZiBkcm9wCiAqICAgfSkgPT4gYm9vbGVhbiA9IG51bGw7CiAqLwovL2VhLm9uRHJvcEhvb2sgPSAoZGF0YSkgPT4ge307CiAKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gRXhjYWxpZHJhdyByZWNlaXZlcyBhbiBvblBhc3RlIGV2ZW50LgogKiBZb3UgY2FuIHVzZSB0aGlzIGNhbGxiYWNrIGluIGNhc2UgeW91IHdhbnQgdG8gZG8gc29tZXRoaW5nIGFkZGl0aW9uYWwgd2hlbiB0aGUKICogb25QYXN0ZSBldmVudCBvY2N1cnMuCiAqIFRoaXMgY2FsbGJhY2sgbXVzdCByZXR1cm4gYSBib29sZWFuIHZhbHVlLgogKiBJbiBjYXNlIHlvdSB3YW50IHRvIHByZXZlbnQgdGhlIGV4Y2FsaWRyYXcgb25QYXN0ZSBhY3Rpb24geW91IG11c3QgcmV0dXJuIGZhbHNlLAogKiBpdCB3aWxsIHN0b3AgdGhlIG5hdGl2ZSBleGNhbGlkcmF3IG9uUGFzdGUgbWFuYWdlbWVudCBmbG93LgogKiAgIG9uUGFzdGVIb29rOiAoZGF0YTogewogKiAgICAgZWE6IEV4Y2FsaWRyYXdBdXRvbWF0ZTsKICogICAgIHBheWxvYWQ6IENsaXBib2FyZERhdGE7CiAqICAgICBldmVudDogQ2xpcGJvYXJkRXZlbnQ7CiAqICAgICBleGNhbGlkcmF3RmlsZTogVEZpbGU7IC8vdGhlIGZpbGUgcmVjZWl2aW5nIHRoZSBwYXN0ZSBldmVudAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXc7IC8vdGhlIGV4Y2FsaWRyYXcgdmlldyByZWNlaXZpbmcgdGhlIHBhc3RlCiAqICAgICBwb2ludGVyUG9zaXRpb246IHsgeDogbnVtYmVyOyB5OiBudW1iZXIgfTsgLy90aGUgcG9pbnRlciBwb3NpdGlvbiBvbiBjYW52YXMKICogICB9KSA9PiBib29sZWFuID0gbnVsbDsKICovCi8vZWEub25QYXN0ZUhvb2sgPSAoZGF0YSkgPT4ge307CgovKioKICogaWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCwgd2hlbiBhbiBFeGNhbGlkcmF3IGZpbGUgaXLine truncated
"LyoKI2V4Y2x1ZGUKYGBganMqLwovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCB3aGVuIHRoZSB1c2VyIGNsb3NlcyBhbiBFeGNhbGlkcmF3IHZpZXcuCiAqICAgb25WaWV3VW5sb2FkSG9vazogKHZpZXc6IEV4Y2FsaWRyYXdWaWV3KSA9PiB2b2lkID0gbnVsbDsKICovCi8vZWEub25WaWV3VW5sb2FkSG9vayA9ICh2aWV3KSA9PiB7fTsKCi8qKgogKiBJZiBzZXQsIHRoaXMgY2FsbGJhY2sgaXMgdHJpZ2dlcmVkLCB3aGVuIHRoZSB1c2VyIGNoYW5nZXMgdGhlIHZpZXcgbW9kZS4KICogWW91IGNhbiB1c2UgdGhpcyBjYWxsYmFjayBpbiBjYXNlIHlvdSB3YW50IHRvIGRvIHNvbWV0aGluZyBhZGRpdGlvbmFsIHdoZW4gdGhlIHVzZXIgc3dpdGNoZXMgdG8gdmlldyBtb2RlIGFuZCBiYWNrLgogKiAgIG9uVmlld01vZGVDaGFuZ2VIb29rOiAoaXNWaWV3TW9kZUVuYWJsZWQ6Ym9vbGVhbiwgdmlldzogRXhjYWxpZHJhd1ZpZXcsIGVhOiBFeGNhbGlkcmF3QXV0b21hdGUpID0+IHZvaWQgPSBudWxsOwogKi8KLy9lYS5vblZpZXdNb2RlQ2hhbmdlSG9vayA9IChpc1ZpZXdNb2RlRW5hYmxlZCwgdmlldywgZWEpID0+IHt9OwoKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gdGhlIHVzZXIgaG92ZXJzIGEgbGluayBpbiB0aGUgc2NlbmUuCiAqIFlvdSBjYW4gdXNlIHRoaXMgY2FsbGJhY2sgaW4gY2FzZSB5b3Ugd2FudCB0byBkbyBzb21ldGhpbmcgYWRkaXRpb25hbCB3aGVuIHRoZSBvbkxpbmtIb3ZlciBldmVudCBvY2N1cnMuCiAqIFRoaXMgY2FsbGJhY2sgbXVzdCByZXR1cm4gYSBib29sZWFuIHZhbHVlLgogKiBJbiBjYXNlIHlvdSB3YW50IHRvIHByZXZlbnQgdGhlIGV4Y2FsaWRyYXcgb25MaW5rSG92ZXIgYWN0aW9uIHlvdSBtdXN0IHJldHVybiBmYWxzZSwgaXQgd2lsbCBzdG9wIHRoZSBuYXRpdmUgZXhjYWxpZHJhdyBvbkxpbmtIb3ZlciBtYW5hZ2VtZW50IGZsb3cuCiAqICAgb25MaW5rSG92ZXJIb29rOiAoCiAqICAgICBlbGVtZW50OiBOb25EZWxldGVkRXhjYWxpZHJhd0VsZW1lbnQsCiAqICAgICBsaW5rVGV4dDogc3RyaW5nLAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXcsCiAqICAgICBlYTogRXhjYWxpZHJhd0F1dG9tYXRlCiAqICAgKSA9PiBib29sZWFuID0gbnVsbDsKICovCi8vZWEub25MaW5rSG92ZXJIb29rID0gKGVsZW1lbnQsIGxpbmtUZXh0LCB2aWV3LCBlYSkgPT4ge307CiAgIAovKioKICogSWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCwgd2hlbiB0aGUgdXNlciBjbGlja3MgYSBsaW5rIGluIHRoZSBzY2VuZS4KICogWW91IGNhbiB1c2UgdGhpcyBjYWxsYmFjayBpbiBjYXNlIHlvdSB3YW50IHRvIGRvIHNvbWV0aGluZyBhZGRpdGlvbmFsIHdoZW4gdGhlIG9uTGlua0NsaWNrIGV2ZW50IG9jY3Vycy4KICogVGhpcyBjYWxsYmFjayBtdXN0IHJldHVybiBhIGJvb2xlYW4gdmFsdWUuCiAqIEluIGNhc2UgeW91IHdhbnQgdG8gcHJldmVudCB0aGUgZXhjYWxpZHJhdyBvbkxpbmtDbGljayBhY3Rpb24geW91IG11c3QgcmV0dXJuIGZhbHNlLCBpdCB3aWxsIHN0b3AgdGhlIG5hdGl2ZSBleGNhbGlkcmF3IG9uTGlua0NsaWNrIG1hbmFnZW1lbnQgZmxvdy4KICogICBvbkxpbmtDbGlja0hvb2s6KAogKiAgICAgZWxlbWVudDogRXhjYWxpZHJhd0VsZW1lbnQsCiAqICAgICBsaW5rVGV4dDogc3RyaW5nLAogKiAgICAgZXZlbnQ6IE1vdXNlRXZlbnQsCiAqICAgICB2aWV3OiBFeGNhbGlkcmF3VmlldywKICogICAgIGVhOiBFeGNhbGlkcmF3QXV0b21hdGUKICogICApID0+IGJvb2xlYW4gPSBudWxsOwogKi8KLy9lYS5vbkxpbmtDbGlja0hvb2sgPSAoZWxlbWVudCxsaW5rVGV4dCxldmVudCwgdmlldywgZWEpID0+IHt9OwogICAKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gRXhjYWxpZHJhdyByZWNlaXZlcyBhbiBvbkRyb3AgZXZlbnQuIAogKiBZb3UgY2FuIHVzZSB0aGlzIGNhbGxiYWNrIGluIGNhc2UgeW91IHdhbnQgdG8gZG8gc29tZXRoaW5nIGFkZGl0aW9uYWwgd2hlbiB0aGUgb25Ecm9wIGV2ZW50IG9jY3Vycy4KICogVGhpcyBjYWxsYmFjayBtdXN0IHJldHVybiBhIGJvb2xlYW4gdmFsdWUuCiAqIEluIGNhc2UgeW91IHdhbnQgdG8gcHJldmVudCB0aGUgZXhjYWxpZHJhdyBvbkRyb3AgYWN0aW9uIHlvdSBtdXN0IHJldHVybiBmYWxzZSwgaXQgd2lsbCBzdG9wIHRoZSBuYXRpdmUgZXhjYWxpZHJhdyBvbkRyb3AgbWFuYWdlbWVudCBmbG93LgogKiAgIG9uRHJvcEhvb2s6IChkYXRhOiB7CiAqICAgICBlYTogRXhjYWxpZHJhd0F1dG9tYXRlOwogKiAgICAgZXZlbnQ6IFJlYWN0LkRyYWdFdmVudDxIVE1MRGl2RWxlbWVudD47CiAqICAgICBkcmFnZ2FibGU6IGFueTsgLy9PYnNpZGlhbiBkcmFnZ2FibGUgb2JqZWN0CiAqICAgICB0eXBlOiAiZmlsZSIgfCAidGV4dCIgfCAidW5rbm93biI7CiAqICAgICBwYXlsb2FkOiB7CiAqICAgICAgIGZpbGVzOiBURmlsZVtdOyAvL1RGaWxlW10gYXJyYXkgb2YgZHJvcHBlZCBmaWxlcwogKiAgICAgICB0ZXh0OiBzdHJpbmc7IC8vc3RyaW5nCiAqICAgICB9OwogKiAgICAgZXhjYWxpZHJhd0ZpbGU6IFRGaWxlOyAvL3RoZSBmaWxlIHJlY2VpdmluZyB0aGUgZHJvcCBldmVudAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXc7IC8vdGhlIGV4Y2FsaWRyYXcgdmlldyByZWNlaXZpbmcgdGhlIGRyb3AKICogICAgIHBvaW50ZXJQb3NpdGlvbjogeyB4OiBudW1iZXI7IHk6IG51bWJlciB9OyAvL3RoZSBwb2ludGVyIHBvc2l0aW9uIG9uIGNhbnZhcyBhdCB0aGUgdGltZSBvZiBkcm9wCiAqICAgfSkgPT4gYm9vbGVhbiA9IG51bGw7CiAqLwovL2VhLm9uRHJvcEhvb2sgPSAoZGF0YSkgPT4ge307CiAKLyoqCiAqIElmIHNldCwgdGhpcyBjYWxsYmFjayBpcyB0cmlnZ2VyZWQsIHdoZW4gRXhjYWxpZHJhdyByZWNlaXZlcyBhbiBvblBhc3RlIGV2ZW50LgogKiBZb3UgY2FuIHVzZSB0aGlzIGNhbGxiYWNrIGluIGNhc2UgeW91IHdhbnQgdG8gZG8gc29tZXRoaW5nIGFkZGl0aW9uYWwgd2hlbiB0aGUKICogb25QYXN0ZSBldmVudCBvY2N1cnMuCiAqIFRoaXMgY2FsbGJhY2sgbXVzdCByZXR1cm4gYSBib29sZWFuIHZhbHVlLgogKiBJbiBjYXNlIHlvdSB3YW50IHRvIHByZXZlbnQgdGhlIGV4Y2FsaWRyYXcgb25QYXN0ZSBhY3Rpb24geW91IG11c3QgcmV0dXJuIGZhbHNlLAogKiBpdCB3aWxsIHN0b3AgdGhlIG5hdGl2ZSBleGNhbGlkcmF3IG9uUGFzdGUgbWFuYWdlbWVudCBmbG93LgogKiAgIG9uUGFzdGVIb29rOiAoZGF0YTogewogKiAgICAgZWE6IEV4Y2FsaWRyYXdBdXRvbWF0ZTsKICogICAgIHBheWxvYWQ6IENsaXBib2FyZERhdGE7CiAqICAgICBldmVudDogQ2xpcGJvYXJkRXZlbnQ7CiAqICAgICBleGNhbGlkcmF3RmlsZTogVEZpbGU7IC8vdGhlIGZpbGUgcmVjZWl2aW5nIHRoZSBwYXN0ZSBldmVudAogKiAgICAgdmlldzogRXhjYWxpZHJhd1ZpZXc7IC8vdGhlIGV4Y2FsaWRyYXcgdmlldyByZWNlaXZpbmcgdGhlIHBhc3RlCiAqICAgICBwb2ludGVyUG9zaXRpb246IHsgeDogbnVtYmVyOyB5OiBudW1iZXIgfTsgLy90aGUgcG9pbnRlciBwb3NpdGlvbiBvbiBjYW52YXMKICogICB9KSA9PiBib29sZWFuID0gbnVsbDsKICovCi8vZWEub25QYXN0ZUhvb2sgPSAoZGF0YSkgPT4ge307CgovKioKICogaWYgc2V0LCB0aGlzIGNhbGxiYWNrIGlzIHRyaWdnZXJlZCwgd2hlbiBhbiBFeGNhbGlkcmF3IGZpbGUgaXLine truncated
);
+2 -2
View File
@@ -17,11 +17,11 @@ export type { Point } from "src/types/types";
export const getEA = (view?: ExcalidrawView): ExcalidrawAutomate | null => {
try {
return window.ExcalidrawAutomate.getAPI(view);
} catch (error) {
} catch (error: unknown) {
errorlog({
message: "Excalidraw not available",
fn: getEA,
error: error as unknown,
error: error,
});
return null;
}
+7 -6
View File
@@ -36,7 +36,6 @@ import {
FONTS_STYLE_ID,
CJK_STYLE_ID,
setRootElementSize,
mainDocument,
} from "../constants/constants";
import {
ExcalidrawSettings,
@@ -127,6 +126,7 @@ import { insertLaTeXToView } from "src/utils/excalidrawViewHelpers";
declare const PLUGIN_VERSION: string;
declare const INITIAL_TIMESTAMP: number;
declare const mainDocument: Document;
type FileMasterInfo = {
isHyperLink: boolean;
@@ -912,7 +912,7 @@ export default class ExcalidrawPlugin extends Plugin {
}
this.logStartupEvent("Styles manager initialized");
this.updatePhoneFooterSafeAreaPadding();
this.updateFooterSafeAreaPadding();
try {
this.scriptEngine = new ScriptEngine(this);
@@ -1162,13 +1162,14 @@ export default class ExcalidrawPlugin extends Plugin {
});
}
public updatePhoneFooterSafeAreaPadding() {
public updateFooterSafeAreaPadding() {
const documents = new Set<Document>([
mainDocument,
...this.getOpenObsidianDocuments(),
]);
const shouldEnable =
DEVICE.isPhone && this.settings?.phoneFooterSafeAreaPadding;
(DEVICE.isPhone && this.settings?.phoneFooterSafeAreaPadding) ||
(DEVICE.isTablet && this.settings?.tabletFooterSafeAreaPadding);
documents.forEach((ownerDocument) => {
const existingStylesheet = ownerDocument.getElementById(
@@ -1277,11 +1278,11 @@ export default class ExcalidrawPlugin extends Plugin {
setButtonBgColor(b, "success");
hideElement(b);
});
} catch (e) {
} catch (e: unknown) {
errorlog({
where: "this.registerInstallCodeblockProcessor",
source,
error: e as unknown,
error: e,
});
}
+3 -2
View File
@@ -25,7 +25,6 @@ import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import {
FRONTMATTER_KEYS,
ICON_NAME,
mainDocument,
VIEW_TYPE_EXCALIDRAW,
} from "src/constants/constants";
import ExcalidrawView from "src/view/ExcalidrawView";
@@ -36,6 +35,8 @@ import {
} from "src/utils/excalidrawViewUtils";
import { setStyle } from "src/utils/styleUtils";
declare const mainDocument: Document;
/**
* Registers event listeners for the plugin
* Must be constructed after the workspace is ready (onLayoutReady)
@@ -258,7 +259,7 @@ export class EventManager {
} catch (error) {
console.error(
"Error parsing pasted Excalidraw element",
this.onPasteHandler.bind(this),
"EventManager.onPasteHandler",
error,
);
}
+2 -2
View File
@@ -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",
+4 -6
View File
@@ -6,11 +6,7 @@ import {
TFile,
Vault,
} from "obsidian";
import {
DEVICE,
mainDocument,
RERENDER_EVENT,
} from "../../constants/constants";
import { DEVICE, RERENDER_EVENT } from "../../constants/constants";
import { EmbeddedFilesLoader } from "../../shared/EmbeddedFileLoader";
import { createPNG, createSVG } from "../../utils/excalidrawAutomateUtils";
import ExcalidrawPlugin from "../main";
@@ -55,6 +51,8 @@ interface imgElementAttributes {
imgstyle: string[]; //css style to apply to IMG element
}
declare const mainDocument: Document;
let plugin: ExcalidrawPlugin;
let app: App;
let vault: Vault;
@@ -552,7 +550,7 @@ const getIMG = async (
break;
}
case PreviewImageType.SVG: {
const img = createEl("div");
const img = createDiv();
setImgStyle({
element: img,
imgAttributes,
+3 -7
View File
@@ -110,7 +110,7 @@ export class MonkeyPatchManager {
delete plugin.excalidrawFileModes[leafKey];
}
return next.apply(this) as ReturnType<WorkspaceLeaf["detach"]>;
return next.apply(this);
};
},
@@ -141,9 +141,7 @@ export class MonkeyPatchManager {
plugin.excalidrawFileModes[filePath] = VIEW_TYPE_EXCALIDRAW;
return next.apply(this, [newState, ...rest]) as ReturnType<
WorkspaceLeaf["setViewState"]
>;
return next.apply(this, [newState, ...rest]);
}
plugin.forceToOpenInMarkdownFilepath = null;
}
@@ -161,9 +159,7 @@ export class MonkeyPatchManager {
}, 500);
}
return next.apply(this, [state, ...rest]) as ReturnType<
WorkspaceLeaf["setViewState"]
>;
return next.apply(this, [state, ...rest]);
};
},
}),
+2 -1
View File
@@ -1,7 +1,7 @@
import { DEBUGGING } from "src/utils/debugHelper";
import ExcalidrawPlugin from "src/core/main";
import { CustomMutationObserver } from "src/utils/debugHelper";
import { DEVICE, mainDocument } from "src/constants/constants";
import { DEVICE } from "src/constants/constants";
import {
getExcalidrawViews,
isObsidianThemeDark,
@@ -12,6 +12,7 @@ import {
isInstanceOfElement,
} from "src/utils/typechecks";
declare const mainDocument: Document;
export class ObserverManager {
private plugin: ExcalidrawPlugin;
private app: App;
+1 -1
View File
@@ -2,8 +2,8 @@ import { WorkspaceWindow } from "obsidian";
import ExcalidrawPlugin from "src/core/main";
import { getAllWindowDocuments } from "../../utils/obsidianUtils";
import { setStyleText } from "src/utils/htmlUtils";
import { mainDocument } from "src/constants/constants";
declare const mainDocument: Document;
export let REM_VALUE = 16;
const STYLE_VARIABLES = [
+29 -20
View File
@@ -10,9 +10,7 @@ import {
TFile,
} from "obsidian";
import {
GITHUB_RELEASES,
LOGO_EXCALIDRAW_MASTERY,
mainDocument,
setRootElementSize,
} from "src/constants/constants";
import { t } from "src/lang/helpers";
@@ -72,12 +70,15 @@ import { getGeminiSupportedSizes } from "src/utils/geminiImageModelUtils";
import { URLs } from "src/constants/safeUrls";
import { hideElement, setStyle, showElement } from "src/utils/styleUtils";
declare const mainDocument: Document;
export interface ExcalidrawSettings {
showTabTitlebarButtons: boolean;
copyLinkToElemenetAnchorTo100: boolean;
copyFrameLinkByName: boolean;
disableDoubleClickTextEditing: boolean;
phoneFooterSafeAreaPadding: boolean;
tabletFooterSafeAreaPadding: boolean;
folder: string;
cropFolder: string;
annotateFolder: string;
@@ -562,6 +563,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
copyFrameLinkByName: false,
disableDoubleClickTextEditing: false,
phoneFooterSafeAreaPadding: false,
tabletFooterSafeAreaPadding: false,
folder: "Excalidraw",
cropFolder: "",
annotateFolder: "",
@@ -679,7 +681,7 @@ export const DEFAULT_SETTINGS: ExcalidrawSettings = {
library2: {
type: "excalidrawlib",
version: 2,
source: GITHUB_RELEASES + PLUGIN_VERSION,
source: `${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/${PLUGIN_VERSION}`,
libraryItems: [],
},
//patchCommentBlock: true,
@@ -1316,19 +1318,13 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
cls: "excalidraw-mastery-promo__summary",
},
);
const excalidrawMasterySummaryTitle = excalidrawMasterySummary.createEl(
"span",
{
cls: "excalidraw-mastery-promo__summary-title",
text: t("EXCALIDRAW_MASTERY"),
},
);
const excalidrawMasterySummaryState = excalidrawMasterySummary.createEl(
"span",
{
cls: "excalidraw-mastery-promo__summary-state",
},
);
const excalidrawMasterySummaryTitle = excalidrawMasterySummary.createSpan({
cls: "excalidraw-mastery-promo__summary-title",
text: t("EXCALIDRAW_MASTERY"),
});
const excalidrawMasterySummaryState = excalidrawMasterySummary.createSpan({
cls: "excalidraw-mastery-promo__summary-state",
});
const excalidrawMasteryLink = URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM;
const updateExcalidrawMasteryPromoState = (persist: boolean) => {
@@ -2545,7 +2541,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
text: t("HOTKEY_OVERRIDE_HEAD"),
cls: "excalidraw-setting-h3",
});
detailsEl.createEl("span", {}, (el) => {
detailsEl.createSpan({}, (el) => {
setSanitizedHtml(el, t("HOTKEY_OVERRIDE_DESC"));
});
@@ -2669,7 +2665,20 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
.setValue(this.plugin.settings.phoneFooterSafeAreaPadding)
.onChange(async (value) => {
this.plugin.settings.phoneFooterSafeAreaPadding = value;
this.plugin.updatePhoneFooterSafeAreaPadding();
this.plugin.updateFooterSafeAreaPadding();
this.applySettingsUpdate();
}),
);
new Setting(detailsEl)
.setName(t("TABLET_FOOTER_SAFE_AREA_PADDING_NAME"))
.setDesc(fragWithHTML(t("TABLET_FOOTER_SAFE_AREA_PADDING_DESC")))
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.tabletFooterSafeAreaPadding)
.onChange(async (value) => {
this.plugin.settings.tabletFooterSafeAreaPadding = value;
this.plugin.updateFooterSafeAreaPadding();
this.applySettingsUpdate();
}),
);
@@ -3092,7 +3101,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
cls: "excalidraw-setting-h1",
});
detailsEl.createEl("span", undefined, (el) =>
detailsEl.createSpan(undefined, (el) =>
setSanitizedHtml(el, t("LINKS_DESC")),
);
@@ -3892,7 +3901,7 @@ export class ExcalidrawSettingTab extends PluginSettingTab {
);
detailsEl.createEl("hr", { cls: "excalidraw-setting-hr" });
detailsEl.createEl("span", {}, (el) => {
detailsEl.createSpan({}, (el) => {
setSanitizedHtml(el, t("MD_EMBED_CUSTOMDATA_HEAD_DESC"));
});
+100 -1
View File
@@ -16,6 +16,8 @@ declare const PLUGIN_VERSION: string;
// English
export default {
INITIALIZATION_MESSAGE:
"Excalidraw is waiting for Obsidian to initialize all of your plugins...",
// Sugester
SELECT_FILE_TO_INSERT: "Select a file to insert",
// main.ts
@@ -621,6 +623,10 @@ export default {
"Extra bottom padding for phone controls",
PHONE_FOOTER_SAFE_AREA_PADDING_DESC:
"Adds extra bottom padding to the Excalidraw footer controls so zoom and undo buttons stay above the system navigation bar on phones. This setting only applies on phones.",
TABLET_FOOTER_SAFE_AREA_PADDING_NAME:
"Extra bottom padding for tablet controls",
TABLET_FOOTER_SAFE_AREA_PADDING_DESC:
"Adds extra bottom padding to the Excalidraw footer controls so zoom and undo buttons stay above the system navigation bar on tablets. This setting only applies on tablets.",
DEFAULT_PEN_MODE_NAME: "Pen mode",
DEFAULT_PEN_MODE_DESC:
"Should pen mode be automatically enabled when opening Excalidraw?",
@@ -935,7 +941,7 @@ export default {
`is available, use that image instead of generating a preview image on the fly. This will result in faster previews especially when you have many embedded objects in the drawing, however, ` +
`it may happen that your latest changes are not displayed and that the image will not automatically match your Obsidian theme in case you have changed the ` +
`Obsidian theme since the export was created. This setting only applies to embedding images into markdown documents. ` +
`For a number of reasons, the same approach cannot be used to expedite the loading of drawings with many embedded objects. See demonstration <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG_1_6_23}" target='_blank'>here</a>.`,
`For a number of reasons, the same approach cannot be used to expedite the loading of drawings with many embedded objects. See demonstration <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/1.6.23" target='_blank'>here</a>.`,
EMBED_PREVIEW_IMAGETYPE_NAME: "Image type in markdown preview",
EMBED_PREVIEW_IMAGETYPE_DESC:
"<b><u>Native SVG</u></b>: High Image Quality. Embedded Websites, YouTube videos, Obsidian Links, and external images embedded via a URL will all work. Embedded Obsidian pages will not<br>" +
@@ -1197,6 +1203,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:
@@ -1612,4 +1622,93 @@ Thank you & Enjoy!
EXTRAS_GATEWAY_UPDATE_TITLE:
"Excalidraw requires a new version of the Extras plugin",
EXTRAS_GATEWAY_UPDATE_BTN: "Open Community Plugins",
// PenSettingsModal.ts
PEN_SETTINGS_TITLE: "Pen Settings",
PEN_SETTINGS_HEADING: "Pen settings",
PEN_SETTINGS_TYPE_NAME: "Pen type",
PEN_SETTINGS_TYPE_DESC: "Select type of pen",
PEN_SETTINGS_TYPE_DEFAULT: "Excalidraw Default",
PEN_SETTINGS_TYPE_HIGHLIGHTER: "Highlighter",
PEN_SETTINGS_TYPE_FINETIP: "Fine tip pen",
PEN_SETTINGS_TYPE_FOUNTAIN: "Fountain pen",
PEN_SETTINGS_TYPE_MARKER: "Marker with Outline",
PEN_SETTINGS_TYPE_THICK_THIN: "Mindmap Thick-Thin",
PEN_SETTINGS_TYPE_THIN_THICK_THIN: "Mindmap Thin-Thick-Thin",
PEN_SETTINGS_APPLY: "Apply New Template",
PEN_SETTINGS_SCOPE_FREEDRAW_ONLY:
"Stroke & fill applies to: <b>Freedraw only</b>",
PEN_SETTINGS_SCOPE_ALL_SHAPES: "Stroke & fill applies to: <b>All shapes</b>",
PEN_SETTINGS_SCOPE_DESC: `<b>"All shapes"</b> means that if for example, you select a blue pen with dashed fill and then switch to a different tool (e.g. to a line, a circle, an arrow - i.e. not the freedraw tool), those will all have the same blue line and dashed fill.<br><b>"Only applies to the freedraw line"</b> means that if for example you are writing black text, and you select a custom pen (e.g. a yellow highlighter), then after using the highlighter you switch to another tool, the previous settings (e.g. black stroke color) will apply to the new shape.`,
PEN_SETTINGS_STROKE_CURRENT: "Stroke color: <b>Current</b>",
PEN_SETTINGS_STROKE_PRESET: "Stroke color: <b>Preset color</b>",
PEN_SETTINGS_STROKE_DESC:
"Use <b>current</b> stroke color of the canvas, or set a specific <b>preset color</b> for the pen",
PEN_SETTINGS_STROKE_SELECT: "Select stroke color",
PEN_SETTINGS_USE_CANVAS_CURRENT: "Use Canvas Current",
PEN_SETTINGS_BG_CURRENT: "Background color: <b>Current</b>",
PEN_SETTINGS_BG_PRESET: "Background color: <b>Preset color</b>",
PEN_SETTINGS_BG_DESC:
"Toggle to use the <b>current background color</b> of the canvas; or a <b>preset color</b>",
PEN_SETTINGS_BG_TRANSPARENT: "Background: <b>Transparent</b>",
PEN_SETTINGS_BG_COLOR_PRESET: "Color: <b>Preset color</b>",
PEN_SETTINGS_BG_TRANSPARENT_DESC: "Background has color or is transparent",
PEN_SETTINGS_BG_COLOR: "Background color",
PEN_SETTINGS_FILL_STYLE: "Fill Style",
PEN_SETTINGS_FILL_UNSET: "Unset",
PEN_SETTINGS_FILL_DOTS: "Dots (⚠ VERY SLOW performance on large objects!)",
PEN_SETTINGS_FILL_ZIGZAG: "Zigzag",
PEN_SETTINGS_FILL_ZIGZAG_LINE: "Zigzag-line",
PEN_SETTINGS_FILL_DASHED: "Dashed",
PEN_SETTINGS_FILL_HACHURE: "Hachure",
PEN_SETTINGS_FILL_CROSS_HATCH: "Cross-hatch",
PEN_SETTINGS_FILL_SOLID: "Solid",
PEN_SETTINGS_SLOPPINESS: "Sloppiness:",
PEN_SETTINGS_NOT_SET: "Not Set",
PEN_SETTINGS_SLOPPINESS_ARCHITECT: "Architect",
PEN_SETTINGS_SLOPPINESS_ARTIST: "Artist",
PEN_SETTINGS_SLOPPINESS_CARTOONIST: "Cartoonist",
PEN_SETTINGS_SLOPPINESS_DESC: "Line sloppiness of the shape fill pattern",
PEN_SETTINGS_STROKE_WIDTH: "Stroke Width",
PEN_SETTINGS_STROKE_PRESET_UNSET: "---",
PEN_SETTINGS_STROKE_PRESET_EXTRA_THIN: "Extra thin",
PEN_SETTINGS_STROKE_PRESET_THIN: "Thin",
PEN_SETTINGS_STROKE_PRESET_MEDIUM: "Medium",
PEN_SETTINGS_STROKE_PRESET_BOLD: "Bold",
PEN_SETTINGS_STROKE_PRESET_EXTRA_BOLD: "Extra bold",
PEN_SETTINGS_HIGHLIGHTER: "Highlighter pen?",
PEN_SETTINGS_PRESSURE: "Pressure sensitive pen?",
PEN_SETTINGS_PRESSURE_DESC:
"<b>toggle on</b>: pressure sensitive<br><b>toggle off</b>: constant pressure",
PEN_SETTINGS_OUTLINE_NONE: "No outline",
PEN_SETTINGS_OUTLINE_WIDTH: "Outline width",
PEN_SETTINGS_OUTLINE_DESC:
"If the stroke has an outline, this will mean the stroke color is the outline color, and the background color is the pen stroke's fill color. If the pen does not have an outline then the pen color is the stroke color. The Fill Style setting applies to the fill style of the enclosed shape, not of the line itself. The line can only have solid fill.",
PEN_SETTINGS_PF_HEADING: "Perfect Freehand settings",
PEN_SETTINGS_PF_DOCS: `Read the Perfect Freehand documentation following <a href="${URLs.GITHUB_COM_STEVERUIZOK_PERFECT_FREEHAND}" target="_blank">this link</a>.`,
PEN_SETTINGS_PF_THINNING: "Thinning",
PEN_SETTINGS_PF_THINNING_DESC: `The effect of pressure on the stroke's size.<br>To create a stroke with a steady line, set the thinning option to 0.<br>To create a stroke that gets thinner with pressure instead of thicker, use a negative number for the thinning option.`,
PEN_SETTINGS_PF_SMOOTHING: "Smoothing",
PEN_SETTINGS_PF_SMOOTHING_DESC: "How much to soften the stroke's edges.",
PEN_SETTINGS_PF_STREAMLINE: "Streamline",
PEN_SETTINGS_PF_STREAMLINE_DESC: "How much to streamline the stroke.",
PEN_SETTINGS_EASING: "Easing function",
PEN_SETTINGS_EASING_DESC: `An easing function for the tapering effect. For more info <a href="${URLs.EASINGS_NET}" target="_blank">click here</a>`,
PEN_SETTINGS_SIMULATE_PRESSURE: "Simulate Pressure",
PEN_SETTINGS_SIMULATE_PRESSURE_DESC:
"Whether to simulate pressure based on velocity.",
PEN_SETTINGS_SIMULATE_PRESSURE_ALWAYS: "Always",
PEN_SETTINGS_SIMULATE_PRESSURE_NEVER: "Never",
PEN_SETTINGS_SIMULATE_PRESSURE_MOUSE: "Yes for mouse, No for pen",
PEN_SETTINGS_START_HEADING: "Start",
PEN_SETTINGS_START_DESC: "Tapering options for the start of the line.",
PEN_SETTINGS_CAP_START: "Cap Start",
PEN_SETTINGS_CAP_DESC: "Whether to draw a cap",
PEN_SETTINGS_TAPER: "Taper:",
PEN_SETTINGS_TAPER_DESC:
"The distance to taper. If set to true, the taper will be the total length of the stroke.",
PEN_SETTINGS_END_HEADING: "End",
PEN_SETTINGS_END_DESC: "Tapering options for the end of the line.",
PEN_SETTINGS_CAP_END: "Cap End",
PEN_SETTINGS_SAVE: "Save Changes",
PEN_SETTINGS_CANCEL: "Cancel",
};
+1 -1
View File
@@ -859,7 +859,7 @@ export default {
`disponible, se usará esa imagen en lugar de generar una vista previa al momento. Esto resultará en vistas previas más rápidas, especialmente si tienes muchos objetos incrustados en el bosquejo. Sin embargo, ` +
`puede que tus últimos cambios no se muestren y la imagen no coincida automáticamente con el ` +
`tema de Obsidian si lo has cambiado desde que se creó la exportación. Esta configuración solo se aplica a la incrustación de imágenes en documentos Markdown. ` +
`Por diversas razones, el mismo enfoque no se puede usar para acelerar la carga de bosquejos con muchos objetos incrustados. Puedes ver una demostración <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG_1_6_23}" target='_blank'>aquí</a>.`,
`Por diversas razones, el mismo enfoque no se puede usar para acelerar la carga de bosquejos con muchos objetos incrustados. Puedes ver una demostración <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/1.6.23" target='_blank'>aquí</a>.`,
EMBED_PREVIEW_IMAGETYPE_NAME: "Tipo de imagen en la vista previa de Markdown",
EMBED_PREVIEW_IMAGETYPE_DESC:
"<b><u>SVG Nativo</u></b>: Alta calidad de imagen. Los sitios web incrustados, videos de YouTube, enlaces de Obsidian e imágenes externas incrustadas a través de una URL funcionarán. Las páginas de Obsidian incrustadas no<br>" +
+1 -1
View File
@@ -765,7 +765,7 @@ export default {
"чтобы генерировать изображение предварительного просмотра на лету. Однако это позволит ускорить предварительный просмотр, особенно если в чертеже много встроенных объектов, " +
"может случиться так, что последние изменения не будут отображаться, а изображение не будет автоматически соответствовать вашей теме Obsidian, " +
"если вы изменили тему Obsidian с момента создания экспорта. Эта настройка применяется только для вставки изображений в документы markdown. " +
`По ряду причин этот же подход не может быть использован для ускорения загрузки чертежей с большим количеством встроенных объектов. Смотрите демонстрацию <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG_1_6_23}" target='_blank'>здесь</a>.`,
`По ряду причин этот же подход не может быть использован для ускорения загрузки чертежей с большим количеством встроенных объектов. Смотрите демонстрацию <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/1.6.23" target='_blank'>здесь</a>.`,
EMBED_PREVIEW_IMAGETYPE_NAME:
"Тип изображения в предварительном просмотре разметки (markdown)",
EMBED_PREVIEW_IMAGETYPE_DESC:
+1 -1
View File
@@ -797,7 +797,7 @@ export default {
`该项能够提高 Markdown 文档的打开速度,尤其是当嵌入到 Markdown 文档中的绘图文件中含有大量图片或 MD-Embed 时。` +
`但是,该项也可能导致预览图无法立即响应绘图文件或者 Obsidian 主题的修改。<br>` +
`该项仅作用于嵌入到 Markdown 文档中的绘图。` +
`该项无法提升绘图文件的打开速度。详见 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG_1_6_23}" target='_blank'>此说明</a>。`,
`该项无法提升绘图文件的打开速度。详见 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/1.6.23" target='_blank'>此说明</a>。`,
EMBED_PREVIEW_IMAGETYPE_NAME: "预览图的格式",
EMBED_PREVIEW_IMAGETYPE_DESC:
`<b>Native SVG:</b>高品质、可交互。<br>` +
+1 -1
View File
@@ -797,7 +797,7 @@ export default {
`該項能夠提高 Markdown 文件的開啟速度,尤其是當嵌入到 Markdown 文件中的繪圖檔案中含有大量圖片或 MD-Embed 時。` +
`但是,該項也可能導致預覽圖無法立即響應繪圖檔案或者 Obsidian 主題的修改。<br>` +
`該項僅作用於嵌入到 Markdown 文件中的繪圖。` +
`該項無法提升繪圖檔案的開啟速度。詳見 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG_1_6_23}" target='_blank'>此說明</a>。`,
`該項無法提升繪圖檔案的開啟速度。詳見 <a href="${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/1.6.23" target='_blank'>此說明</a>。`,
EMBED_PREVIEW_IMAGETYPE_NAME: "預覽圖的格式",
EMBED_PREVIEW_IMAGETYPE_DESC:
`<b>Native SVG:</b>高品質、可互動。<br>` +
+5 -8
View File
@@ -1,17 +1,14 @@
import {
ExcalidrawElement,
FileId,
} from "@zsviczian/excalidraw/types/element/src/types";
import { BinaryFileData } from "@zsviczian/excalidraw/types/excalidraw/types";
import { ExcalidrawElement } from "@zsviczian/excalidraw/types/element/src/types";
import type { BinaryFiles } from "@zsviczian/excalidraw/types/excalidraw/types";
import { Notice } from "obsidian";
import { getEA } from "src/core";
import { ExcalidrawAutomate } from "src/shared/ExcalidrawAutomate";
import { cloneElement } from "src/utils/excalidrawViewHelpers";
import { mainDocument, nanoid } from "src/constants/constants";
import { svgToBase64 } from "../utils/utils";
import { ExportSettings } from "src/types/exportUtilTypes";
import { nanoid } from "src/constants/constants";
declare const mainDocument: Document;
/**
* Creates a masked image from an Excalidraw scene.
*
@@ -43,7 +40,7 @@ export class CropImage {
constructor(
private elements: ExcalidrawElement[],
files: Map<FileId, BinaryFileData>,
files: BinaryFiles, // Record<ExcalidrawElement["id"], BinaryFileData>
) {
const imageEA = getEA();
this.imageEA = imageEA;
+6 -3
View File
@@ -1,6 +1,5 @@
import { App, Modal } from "obsidian";
import { clamp } from "@radix-ui/number";
import { mainDocument } from "src/constants/constants";
import { setStyle } from "src/utils/styleUtils";
import {
isInstanceOfHTMLButtonElement,
@@ -9,6 +8,8 @@ import {
isInstanceOfHTMLTextAreaElement,
} from "src/utils/typechecks";
declare const mainDocument: Document;
function getClientPoint(e: PointerEvent | TouchEvent) {
if (e.type.startsWith("touch")) {
const t =
@@ -32,6 +33,8 @@ function pointInRect(
);
}
declare const getCaretRangeFromPoint: (doc: Document, x: number, y: number) => Range | null;
function isPointOnText(e: PointerEvent | TouchEvent, doc: Document): boolean {
const pt = getClientPoint(e);
if (!pt) {
@@ -47,8 +50,8 @@ function isPointOnText(e: PointerEvent | TouchEvent, doc: Document): boolean {
offsetNode = caretPos.offsetNode;
offset = typeof caretPos.offset === "number" ? caretPos.offset : null;
} else {
// Safari/WebKit
const caretRange = doc.caretRangeFromPoint?.(pt.x, pt.y);
// Safari/WebKit - see rollup.config.mjs for the declaration of getCaretRangeFromPoint
const caretRange = getCaretRangeFromPoint(doc, pt.x, pt.y);
if (caretRange?.startContainer) {
offsetNode = caretRange.startContainer;
offset =
+2 -2
View File
@@ -29,8 +29,8 @@ export class HotkeyEditor extends BaseComponent {
this.applySettingsUpdate = applySettingsUpdate;
// Bind the event handlers once in the constructor
this.boundKeydownHandler = this.onKeydown.bind(this);
this.boundKeyupHandler = this.onKeyup.bind(this);
this.boundKeydownHandler = (e) => this.onKeydown(e);
this.boundKeyupHandler = (e) => this.onKeyup(e);
}
onload(): void {
+50
View File
@@ -16,8 +16,26 @@ export const RELEASE_NOTES: { [k: string]: string } = {
I build this plugin as a labor of love. Curious about the philosophy behind it? Check out [📕 Sketch Your Mind](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_SYM}). Want to master Excalidraw? Join [Excalidraw Mastery](${URLs.COMMUNITY_SKETCH_YOUR_MIND_COM_EM}). If you find it valuable, say "Thank you", and
<div class="ex-coffee-div"><a href="${URLs.KO_FI_COM_ZSOLT}"><img src="${URLs.CDN_KO_FI_COM_CDN_KOFI3_PNG}" border="0" alt="Buy Me a Coffee at ko-fi.com" height=45></a></div>
`,
"2.25.2": `
## Fixed
- YouTube embeddables did not render on Android devices
- Changing custom pen settings did not save correctly. Added Save and Cancel buttons to the Pen Settings page.
- Error generating image ID on mobile devices when uploading / pasting images to the scene
`,
"2.25.1": `
This is a very minor update to fix a small regression in 2.25.0
## Fixed
- Excalidraw Automate Color Picker component used in Shade Master broke in 2.25.0. It is now restored.
## New
- Separate setting to enable extra bottom padding for tablet controls. This is useful for tablets with a system navigation bar that overlaps the Excalidraw footer controls. [#2833](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2833)
- Added \`onSceneChangeHook\` to Excalidraw Startup Script template.
`,
"2.25.0": `
${getYouTubeDiv("aqt5NJE2sJ8")}
## New from Excalidraw.com
- Significantly improved ink flow for freedraw pen. You can now toggle between pressure sensitive and constant mode for the default excalidraw.com freedraw pen. [#11507](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11507), [#11551](${URLs.GITHUB_COM_EXCALIDRAW_EXCALIDRAW_PULL}/11551)
@@ -29,6 +47,38 @@ 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.
- LaTeX and Mermaid did not work on iOS. Released updated Excalidraw Extras and bumped the minimum required version to 0.0.15. [#2825](${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2825)
- Malformed "Source" URL in ExcalidrawLib and Excalidraw Data json. [#2826]${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_ISSUES}/2826)
## 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
+1 -1
View File
@@ -80,7 +80,7 @@ export class ModifierKeySettingsComponent {
this.isMacOS ? "OPT" : "ALT",
this.isMacOS ? "CTRL" : "META",
].forEach((key) => {
headerSetting.controlEl.createEl("span", {
headerSetting.controlEl.createSpan({
text: key,
cls: "modifier-key-col-header",
});
+280 -198
View File
@@ -1,23 +1,26 @@
import { ExcalidrawImperativeAPI } from "@zsviczian/excalidraw/types/excalidraw/types";
import {
ColorComponent,
DropdownComponent,
Modal,
Setting,
SliderComponent,
TextComponent,
ToggleComponent,
} from "obsidian";
import type { StrokeWidthKey } from "@zsviczian/excalidraw/types/common/src/constants";
import { COLOR_NAMES } from "src/constants/constants";
import ExcalidrawView from "src/view/ExcalidrawView";
import ExcalidrawPlugin from "src/core/main";
import { setPen } from "src/view/components/menu/ObsidianMenu";
import { ExtendedFillStyle, PenType } from "src/types/penTypes";
import { ExtendedFillStyle, PenType, PenStyle } from "src/types/penTypes";
import { getExcalidrawViews } from "src/utils/obsidianUtils";
import { PENS } from "src/utils/pens";
import { fragWithHTML } from "src/utils/utils";
import { setSanitizedHtml } from "src/utils/htmlUtils";
import { showColorPicker } from "./ColorPicker";
import { URLs } from "src/constants/safeUrls";
import { hideElement, showElement } from "src/utils/styleUtils";
import { t } from "src/lang/helpers";
const EASINGFUNCTIONS: Record<string, string> = {
linear: "linear",
@@ -53,9 +56,28 @@ const EASINGFUNCTIONS: Record<string, string> = {
easeInOutBounce: "easeInOutBounce",
};
const FREEDRAW_STROKE_WIDTH_PRESETS: Readonly<Record<StrokeWidthKey, number>> =
{
extraThin: 0.25,
thin: 0.5,
medium: 1,
bold: 2,
extraBold: 4,
};
const getStrokeWidthPresetKey = (strokeWidth: number): StrokeWidthKey | "" => {
const normalizedStrokeWidth = Math.round(strokeWidth * 100) / 100;
const matchedPreset = (
Object.entries(FREEDRAW_STROKE_WIDTH_PRESETS) as [StrokeWidthKey, number][]
).find(([, value]) => value === normalizedStrokeWidth);
return matchedPreset?.[0] ?? "";
};
export class PenSettingsModal extends Modal {
private api: ExcalidrawImperativeAPI;
private dirty: boolean = false;
private shouldSave: boolean = false;
private isDirty: boolean = false;
private tempPenSettings: PenStyle;
constructor(
private plugin: ExcalidrawPlugin,
@@ -64,20 +86,28 @@ export class PenSettingsModal extends Modal {
) {
super(plugin.app);
this.api = view.excalidrawAPI;
// Clone the settings so changes aren't applied unless saved
this.tempPenSettings = JSON.parse(
JSON.stringify(this.plugin.settings.customPens[this.pen]),
) as PenStyle;
}
onOpen(): void {
this.containerEl.classList.add("excalidraw-release");
this.titleEl.setText(`Pen Settings`);
this.titleEl.setText(t("PEN_SETTINGS_TITLE"));
void this.createForm();
}
onClose() {
if (this.dirty) {
if (this.shouldSave && this.isDirty) {
// Overwrite actual settings with temp settings
this.plugin.settings.customPens[this.pen] = this.tempPenSettings;
void this.plugin.saveSettings();
getExcalidrawViews(this.app, true).forEach((excalidrawView) =>
excalidrawView.updatePinnedCustomPens(),
);
const pen = this.plugin.settings.customPens[this.pen];
const api = this.view.excalidrawAPI;
setPen(pen, api);
@@ -85,6 +115,27 @@ export class PenSettingsModal extends Modal {
}
}
private addActionButtons(container: HTMLElement) {
const actionContainer = container.createDiv(
"excalidraw-pen-settings-floating-actions",
);
new Setting(actionContainer)
.addButton((bt) =>
bt
.setButtonText(t("PEN_SETTINGS_SAVE"))
.setCta()
.onClick(() => {
this.shouldSave = true;
this.close();
}),
)
.addButton((bt) =>
bt.setButtonText(t("PEN_SETTINGS_CANCEL")).onClick(() => {
this.close();
}),
);
}
async createForm() {
const hexColor = (color: string): [string, string] => {
let opacity = "";
@@ -119,39 +170,39 @@ export class PenSettingsModal extends Modal {
return [null, opacity];
};
const ps = this.plugin.settings.customPens[this.pen];
const ps = this.tempPenSettings;
const ce = this.contentEl;
ce.empty();
ce.createEl("h1", { text: "Pen settings" });
ce.createEl("h1", { text: t("PEN_SETTINGS_HEADING") });
new Setting(ce)
.setName("Pen type")
.setDesc("Select type of pen")
.setName(t("PEN_SETTINGS_TYPE_NAME"))
.setDesc(t("PEN_SETTINGS_TYPE_DESC"))
.addDropdown((dropdown) => {
dropdown
.addOption("default", "Excalidraw Default")
.addOption("highlighter", "Highlighter")
.addOption("finetip", "Fine tip pen")
.addOption("fountain", "Fountain pen")
.addOption("marker", "Marker with Outline")
.addOption("thick-thin", "Mindmap Thick-Thin")
.addOption("thin-thick-thin", "Mindmap Thin-Thick-Thin")
.addOption("default", t("PEN_SETTINGS_TYPE_DEFAULT"))
.addOption("highlighter", t("PEN_SETTINGS_TYPE_HIGHLIGHTER"))
.addOption("finetip", t("PEN_SETTINGS_TYPE_FINETIP"))
.addOption("fountain", t("PEN_SETTINGS_TYPE_FOUNTAIN"))
.addOption("marker", t("PEN_SETTINGS_TYPE_MARKER"))
.addOption("thick-thin", t("PEN_SETTINGS_TYPE_THICK_THIN"))
.addOption("thin-thick-thin", t("PEN_SETTINGS_TYPE_THIN_THICK_THIN"))
.setValue(ps.type)
.onChange((value: PenType) => {
this.dirty = true;
this.isDirty = true;
ps.type = value;
});
})
.addButton((button) =>
button.setButtonText("Apply").onClick(() => {
this.dirty = true;
button.setButtonText(t("PEN_SETTINGS_APPLY")).onClick(() => {
this.isDirty = true;
ps.strokeColor = PENS[ps.type].strokeColor;
ps.backgroundColor = PENS[ps.type].backgroundColor;
ps.fillStyle = PENS[ps.type].fillStyle;
ps.strokeWidth = PENS[ps.type].strokeWidth;
ps.roughness = PENS[ps.type].roughness;
ps.penOptions = { ...PENS[ps.type].penOptions };
ce.empty();
void this.createForm();
}),
);
@@ -160,23 +211,19 @@ export class PenSettingsModal extends Modal {
.setName(
fragWithHTML(
ps.freedrawOnly
? "Stroke & fill applies to: <b>Freedraw only</b>"
: "Stroke & fill applies to: <b>All shapes</b>",
),
)
.setDesc(
fragWithHTML(
`<b>"All shapes"</b> means that if for example, you select a blue pen with dashed fill and then switch to a different tool (e.g. to a line, a circle, an arrow - i.e. not the freedraw tool), those will all have the same blue line and dashed fill.<br><b>"Only applies to the freedraw line"</b> means that if for example you are writing black text, and you select a custom pen (e.g. a yellow highlighter), then after using the highlighter you switch to another tool, the previous settings (e.g. black stroke color) will apply to the new shape.`,
? t("PEN_SETTINGS_SCOPE_FREEDRAW_ONLY")
: t("PEN_SETTINGS_SCOPE_ALL_SHAPES"),
),
)
.setDesc(fragWithHTML(t("PEN_SETTINGS_SCOPE_DESC")))
.addToggle((toggle) =>
toggle.setValue(ps.freedrawOnly).onChange((value) => {
this.dirty = true;
this.isDirty = true;
scopeSetting.setName(
fragWithHTML(
value
? "Stroke & fill applies to: <b>Freedraw only</b>"
: "Stroke & fill applies to: <b>All shapes</b>",
? t("PEN_SETTINGS_SCOPE_FREEDRAW_ONLY")
: t("PEN_SETTINGS_SCOPE_ALL_SHAPES"),
),
);
ps.freedrawOnly = value;
@@ -193,19 +240,15 @@ export class PenSettingsModal extends Modal {
.setName(
fragWithHTML(
!ps.strokeColor
? "Stroke color: <b>Current</b>"
: "Stroke color: <b>Preset color</b>",
),
)
.setDesc(
fragWithHTML(
"Use <b>current</b> stroke color of the canvas, or set a specific <b>preset color</b> for the pen",
? t("PEN_SETTINGS_STROKE_CURRENT")
: t("PEN_SETTINGS_STROKE_PRESET"),
),
)
.setDesc(fragWithHTML(t("PEN_SETTINGS_STROKE_DESC")))
.addToggle((toggle) => {
strokeUseCurrentToggle = toggle;
toggle.setValue(!ps.strokeColor).onChange((value) => {
this.dirty = true;
this.isDirty = true;
if (value) {
hideElement(scSetting.settingEl);
} else {
@@ -214,8 +257,8 @@ export class PenSettingsModal extends Modal {
strokeSetting.setName(
fragWithHTML(
value
? "Stroke color: <b>Current</b>"
: "Stroke color: <b>Preset color</b>",
? t("PEN_SETTINGS_STROKE_CURRENT")
: t("PEN_SETTINGS_STROKE_PRESET"),
),
);
if (value) {
@@ -232,26 +275,28 @@ export class PenSettingsModal extends Modal {
});
const scSetting = new Setting(ce)
.setName("Select stroke color")
.setName(t("PEN_SETTINGS_STROKE_SELECT"))
.addButton((button) =>
button.setButtonText("Use Canvas Current").onClick(() => {
const st = this.api.getAppState();
const color =
st.resetCustomPen?.currentItemStrokeColor ??
st.currentItemStrokeColor;
[sHex, sOpacity] = hexColor(color);
ps.strokeColor = color;
this.dirty = true;
sctComponent.setValue(color);
sChangeBounce = true;
sccpComponent.setValue(sHex);
}),
button
.setButtonText(t("PEN_SETTINGS_USE_CANVAS_CURRENT"))
.onClick(() => {
const st = this.api.getAppState();
const color =
st.resetCustomPen?.currentItemStrokeColor ??
st.currentItemStrokeColor;
[sHex, sOpacity] = hexColor(color);
ps.strokeColor = color;
this.isDirty = true;
sctComponent.setValue(color);
sChangeBounce = true;
sccpComponent.setValue(sHex);
}),
)
.addText((text) => {
sctComponent = text;
text.setValue(ps.strokeColor).onChange((value) => {
sChangeBounce = true;
this.dirty = true;
this.isDirty = true;
ps.strokeColor = value;
[sHex, sOpacity] = hexColor(value);
if (sHex) {
@@ -266,7 +311,7 @@ export class PenSettingsModal extends Modal {
sChangeBounce = false;
return;
}
this.dirty = true;
this.isDirty = true;
ps.strokeColor = value + sOpacity;
sctComponent.setValue(value + sOpacity);
});
@@ -282,6 +327,7 @@ export class PenSettingsModal extends Modal {
if (!selected) {
return;
}
this.isDirty = true;
strokeUseCurrentToggle?.setValue(false);
sChangeBounce = true;
[sHex, sOpacity] = hexColor(selected);
@@ -309,24 +355,20 @@ export class PenSettingsModal extends Modal {
.setName(
fragWithHTML(
!ps.backgroundColor
? "Background color: <b>Current</b>"
: "Background color: <b>Preset color</b>",
),
)
.setDesc(
fragWithHTML(
"Toggle to use the <b>current background color</b> of the canvas; or a <b>preset color</b>",
? t("PEN_SETTINGS_BG_CURRENT")
: t("PEN_SETTINGS_BG_PRESET"),
),
)
.setDesc(fragWithHTML(t("PEN_SETTINGS_BG_DESC")))
.addToggle((toggle) => {
bgUseCurrentToggle = toggle;
toggle.setValue(!ps.backgroundColor).onChange((value) => {
this.dirty = true;
this.isDirty = true;
bgSetting.setName(
fragWithHTML(
value
? "Background color: <b>Current</b>"
: "Background color: <b>Preset color</b>",
? t("PEN_SETTINGS_BG_CURRENT")
: t("PEN_SETTINGS_BG_PRESET"),
),
);
@@ -358,17 +400,17 @@ export class PenSettingsModal extends Modal {
.setName(
fragWithHTML(
ps.backgroundColor === "transparent"
? "Background: <b>Transparent</b>"
: "Color: <b>Preset color</b>",
? t("PEN_SETTINGS_BG_TRANSPARENT")
: t("PEN_SETTINGS_BG_COLOR_PRESET"),
),
)
.setDesc("Background has color or is transparent")
.setDesc(t("PEN_SETTINGS_BG_TRANSPARENT_DESC"))
.addToggle((toggle) => {
bgtComponent = toggle;
toggle
.setValue(ps.backgroundColor === "transparent")
.onChange((value) => {
this.dirty = true;
this.isDirty = true;
if (value) {
hideElement(bgcSetting.settingEl);
hideElement(fsSetting.settingEl);
@@ -379,8 +421,8 @@ export class PenSettingsModal extends Modal {
bgctSetting.setName(
fragWithHTML(
value
? "Background: <b>Transparent</b>"
: "Color: <b>Preset color</b>",
? t("PEN_SETTINGS_BG_TRANSPARENT")
: t("PEN_SETTINGS_BG_COLOR_PRESET"),
),
);
ps.backgroundColor = value
@@ -396,26 +438,28 @@ export class PenSettingsModal extends Modal {
}
let bgChangeBounce: boolean = false;
const bgcSetting = new Setting(ce)
.setName("Background color")
.setName(t("PEN_SETTINGS_BG_COLOR"))
.addButton((button) =>
button.setButtonText("Use Canvas Current").onClick(() => {
const st = this.api.getAppState();
const color =
st.resetCustomPen?.currentItemBackgroundColor ??
st.currentItemBackgroundColor;
[bgHex, bgOpacity] = hexColor(color);
ps.backgroundColor = color;
this.dirty = true;
bgctComponent.setValue(color);
bgChangeBounce = true;
bgcpComponent.setValue(bgHex);
}),
button
.setButtonText(t("PEN_SETTINGS_USE_CANVAS_CURRENT"))
.onClick(() => {
const st = this.api.getAppState();
const color =
st.resetCustomPen?.currentItemBackgroundColor ??
st.currentItemBackgroundColor;
[bgHex, bgOpacity] = hexColor(color);
ps.backgroundColor = color;
this.isDirty = true;
bgctComponent.setValue(color);
bgChangeBounce = true;
bgcpComponent.setValue(bgHex);
}),
)
.addText((text) => {
bgctComponent = text;
text.setValue(ps.backgroundColor).onChange((value) => {
bgChangeBounce = true;
this.dirty = true;
this.isDirty = true;
ps.backgroundColor = value;
[bgHex, bgOpacity] = hexColor(value);
if (bgHex) {
@@ -430,7 +474,7 @@ export class PenSettingsModal extends Modal {
bgChangeBounce = false;
return;
}
this.dirty = true;
this.isDirty = true;
ps.backgroundColor = value + bgOpacity;
bgctComponent.setValue(value + bgOpacity);
});
@@ -446,6 +490,7 @@ export class PenSettingsModal extends Modal {
if (!selected) {
return;
}
this.isDirty = true;
bgUseCurrentToggle?.setValue(false);
bgtComponent?.setValue(false);
bgChangeBounce = true;
@@ -465,20 +510,20 @@ export class PenSettingsModal extends Modal {
}
const fsSetting = new Setting(ce)
.setName("Fill Style")
.setName(t("PEN_SETTINGS_FILL_STYLE"))
.addDropdown((dropdown) =>
dropdown
.addOption("", "Unset")
.addOption("dots", "Dots (⚠ VERY SLOW performance on large objects!)")
.addOption("zigzag", "Zigzag")
.addOption("zigzag-line", "Zigzag-line")
.addOption("dashed", "Dashed")
.addOption("hachure", "Hachure")
.addOption("cross-hatch", "Cross-hatch")
.addOption("solid", "Solid")
.addOption("", t("PEN_SETTINGS_FILL_UNSET"))
.addOption("dots", t("PEN_SETTINGS_FILL_DOTS"))
.addOption("zigzag", t("PEN_SETTINGS_FILL_ZIGZAG"))
.addOption("zigzag-line", t("PEN_SETTINGS_FILL_ZIGZAG_LINE"))
.addOption("dashed", t("PEN_SETTINGS_FILL_DASHED"))
.addOption("hachure", t("PEN_SETTINGS_FILL_HACHURE"))
.addOption("cross-hatch", t("PEN_SETTINGS_FILL_CROSS_HATCH"))
.addOption("solid", t("PEN_SETTINGS_FILL_SOLID"))
.setValue(ps.fillStyle)
.onChange((value: ExtendedFillStyle) => {
this.dirty = true;
this.isDirty = true;
ps.fillStyle = value;
}),
);
@@ -488,66 +533,111 @@ export class PenSettingsModal extends Modal {
showElement(fsSetting.settingEl);
}
const getSloppinessName = (roughness: number | null) => {
if (roughness === null) return t("PEN_SETTINGS_NOT_SET");
if (roughness <= 0.5)
return `${t("PEN_SETTINGS_SLOPPINESS_ARCHITECT")} (${roughness})`;
if (roughness <= 1.5)
return `${t("PEN_SETTINGS_SLOPPINESS_ARTIST")} (${roughness})`;
return `${t("PEN_SETTINGS_SLOPPINESS_CARTOONIST")} (${roughness})`;
};
const rSetting = new Setting(ce)
.setName(
fragWithHTML(
`Sloppiness: <b>${ps.roughness === null ? "Not Set" : ps.roughness <= 0.5 ? "Architect (" : ps.roughness <= 1.5 ? "Artist (" : "Cartoonist ("}${ps.roughness === null ? "" : `${ps.roughness})`}</b>`,
`${t("PEN_SETTINGS_SLOPPINESS")} <b>${getSloppinessName(ps.roughness)}</b>`,
),
)
.setDesc("Line sloppiness of the shape fill pattern")
.setDesc(t("PEN_SETTINGS_SLOPPINESS_DESC"))
.addSlider((slider) =>
slider
.setLimits(-0.5, 3, 0.5)
.setValue(ps.roughness === null ? -0.5 : ps.roughness)
.onChange((value) => {
this.dirty = true;
this.isDirty = true;
ps.roughness = value === -0.5 ? null : value;
rSetting.setName(
fragWithHTML(
`Sloppiness: <b>${ps.roughness === null ? "Not Set" : ps.roughness <= 0.5 ? "Architect (" : ps.roughness <= 1.5 ? "Artist (" : "Cartoonist ("}${ps.roughness === null ? "" : `${ps.roughness})`}</b>`,
`${t("PEN_SETTINGS_SLOPPINESS")} <b>${getSloppinessName(ps.roughness)}</b>`,
),
);
}),
);
let strokeWidthSlider: SliderComponent;
let strokeWidthPresetDropdown: DropdownComponent;
let strokeWidthPresetUpdateInProgress = false;
const swSetting = new Setting(ce)
.setName(
fragWithHTML(
`Stroke Width <b>${ps.strokeWidth === 0 ? "Not Set" : ps.strokeWidth}</b>`,
`${t("PEN_SETTINGS_STROKE_WIDTH")} <b>${ps.strokeWidth === 0 ? t("PEN_SETTINGS_NOT_SET") : ps.strokeWidth}</b>`,
),
)
.addSlider((slider) =>
slider
.setLimits(0.1, 8, 0.1)
.setValue(ps.strokeWidth)
.onChange((value) => {
this.dirty = true;
ps.strokeWidth = value;
.addDropdown((dropdown) => {
strokeWidthPresetDropdown = dropdown;
dropdown
.addOption("", t("PEN_SETTINGS_STROKE_PRESET_UNSET"))
.addOption("extraThin", t("PEN_SETTINGS_STROKE_PRESET_EXTRA_THIN"))
.addOption("thin", t("PEN_SETTINGS_STROKE_PRESET_THIN"))
.addOption("medium", t("PEN_SETTINGS_STROKE_PRESET_MEDIUM"))
.addOption("bold", t("PEN_SETTINGS_STROKE_PRESET_BOLD"))
.addOption("extraBold", t("PEN_SETTINGS_STROKE_PRESET_EXTRA_BOLD"))
.setValue(getStrokeWidthPresetKey(ps.strokeWidth))
.onChange((value: StrokeWidthKey | "") => {
this.isDirty = true;
if (!value) {
return;
}
const presetStrokeWidth = FREEDRAW_STROKE_WIDTH_PRESETS[value];
ps.strokeWidth = presetStrokeWidth;
strokeWidthPresetUpdateInProgress = true;
strokeWidthSlider?.setValue(presetStrokeWidth);
swSetting.setName(
fragWithHTML(
`Stroke Width <b>${ps.strokeWidth === 0 ? "Not Set" : ps.strokeWidth}</b>`,
`${t("PEN_SETTINGS_STROKE_WIDTH")} <b>${ps.strokeWidth === 0 ? t("PEN_SETTINGS_NOT_SET") : ps.strokeWidth}</b>`,
),
);
}),
);
});
})
.addSlider((slider) => {
strokeWidthSlider = slider;
slider
.setLimits(0.05, 8, 0.05)
.setValue(ps.strokeWidth)
.onChange((value) => {
this.isDirty = true;
ps.strokeWidth = value;
new Setting(ce).setName("Highlighter pen?").addToggle((toggle) =>
if (strokeWidthPresetUpdateInProgress) {
strokeWidthPresetUpdateInProgress = false;
} else {
strokeWidthPresetDropdown.setValue(
getStrokeWidthPresetKey(value),
);
}
swSetting.setName(
fragWithHTML(
`${t("PEN_SETTINGS_STROKE_WIDTH")} <b>${ps.strokeWidth === 0 ? t("PEN_SETTINGS_NOT_SET") : ps.strokeWidth}</b>`,
),
);
});
});
new Setting(ce).setName(t("PEN_SETTINGS_HIGHLIGHTER")).addToggle((toggle) =>
toggle.setValue(ps.penOptions.highlighter).onChange((value) => {
this.dirty = true;
this.isDirty = true;
ps.penOptions.highlighter = value;
}),
);
new Setting(ce)
.setName("Pressure sensitive pen?")
.setDesc(
fragWithHTML(
`<b>toggle on</b>: pressure sensitive<br><b>toggle off</b>: constant pressure`,
),
)
.setName(t("PEN_SETTINGS_PRESSURE"))
.setDesc(fragWithHTML(t("PEN_SETTINGS_PRESSURE_DESC")))
.addToggle((toggle) =>
toggle.setValue(!ps.penOptions.constantPressure).onChange((value) => {
this.dirty = true;
this.isDirty = true;
ps.penOptions.constantPressure = !value;
if (ps.penOptions.constantPressure) {
hideElement(spSetting.settingEl);
@@ -559,127 +649,128 @@ export class PenSettingsModal extends Modal {
if (ps.penOptions.hasOutline && ps.penOptions.outlineWidth === 0) {
ps.penOptions.outlineWidth = 0.5;
this.dirty = true;
this.isDirty = true;
}
if (!ps.penOptions.hasOutline && ps.penOptions.outlineWidth > 0) {
ps.penOptions.outlineWidth = 0;
this.dirty = true;
this.isDirty = true;
}
const owSetting = new Setting(ce)
.setName(
fragWithHTML(
ps.penOptions.outlineWidth === 0
? `No outline`
: `Outline width <b>${ps.penOptions.outlineWidth}</b>`,
? t("PEN_SETTINGS_OUTLINE_NONE")
: `${t("PEN_SETTINGS_OUTLINE_WIDTH")} <b>${ps.penOptions.outlineWidth}</b>`,
),
)
.setDesc(
"If the stroke has an outline, this will mean the stroke color is the outline color, and the background color is the pen stroke's fill color. If the pen does not have an outline then the pen color is the stroke color. The Fill Style setting applies to the fill style of the enclosed shape, not of the line itself. The line can only have solid fill.",
)
.setDesc(t("PEN_SETTINGS_OUTLINE_DESC"))
.addSlider((slider) =>
slider
.setLimits(0, 8, 0.1)
.setValue(ps.penOptions.outlineWidth)
.onChange((value) => {
this.dirty = true;
this.isDirty = true;
ps.penOptions.outlineWidth = value;
ps.penOptions.hasOutline = value > 0;
owSetting.setName(
fragWithHTML(
ps.penOptions.outlineWidth === 0
? `No outline`
: `Outline width <b>${ps.penOptions.outlineWidth}</b>`,
? t("PEN_SETTINGS_OUTLINE_NONE")
: `${t("PEN_SETTINGS_OUTLINE_WIDTH")} <b>${ps.penOptions.outlineWidth}</b>`,
),
);
}),
);
ce.createEl("h2", { text: "Perfect Freehand settings" });
ce.createEl("h2", { text: t("PEN_SETTINGS_PF_HEADING") });
const p = ce.createEl("p");
setSanitizedHtml(
p,
`Read the Perfect Freehand documentation following <a href="${URLs.GITHUB_COM_STEVERUIZOK_PERFECT_FREEHAND}" target="_blank">this link</a>.`,
);
setSanitizedHtml(p, t("PEN_SETTINGS_PF_DOCS"));
const tSetting = new Setting(ce)
.setName(
fragWithHTML(`Thinnning <b>${ps.penOptions.options.thinning}</b>`),
)
.setDesc(
fragWithHTML(
`The effect of pressure on the stroke's size.<br>To create a stroke with a steady line, set the thinning option to 0.<br>To create a stroke that gets thinner with pressure instead of thicker, use a negative number for the thinning option.`,
`${t("PEN_SETTINGS_PF_THINNING")} <b>${ps.penOptions.options.thinning}</b>`,
),
)
.setDesc(fragWithHTML(t("PEN_SETTINGS_PF_THINNING_DESC")))
.addSlider((slider) =>
slider
.setLimits(-1, 1, 0.05)
.setValue(ps.penOptions.options.thinning)
.onChange((value) => {
this.dirty = true;
tSetting.setName(fragWithHTML(`Thinnning <b>${value}</b>`));
this.isDirty = true;
tSetting.setName(
fragWithHTML(`${t("PEN_SETTINGS_PF_THINNING")} <b>${value}</b>`),
);
ps.penOptions.options.thinning = value;
}),
);
const sSetting = new Setting(ce)
.setName(
fragWithHTML(`Smoothing <b>${ps.penOptions.options.smoothing}</b>`),
fragWithHTML(
`${t("PEN_SETTINGS_PF_SMOOTHING")} <b>${ps.penOptions.options.smoothing}</b>`,
),
)
.setDesc(fragWithHTML(`How much to soften the stroke's edges.`))
.setDesc(fragWithHTML(t("PEN_SETTINGS_PF_SMOOTHING_DESC")))
.addSlider((slider) =>
slider
.setLimits(0, 1, 0.05)
.setValue(ps.penOptions.options.smoothing)
.onChange((value) => {
this.dirty = true;
sSetting.setName(fragWithHTML(`Smoothing <b>${value}</b>`));
this.isDirty = true;
sSetting.setName(
fragWithHTML(`${t("PEN_SETTINGS_PF_SMOOTHING")} <b>${value}</b>`),
);
ps.penOptions.options.smoothing = value;
}),
);
const slSetting = new Setting(ce)
.setName(
fragWithHTML(`Streamline <b>${ps.penOptions.options.streamline}</b>`),
fragWithHTML(
`${t("PEN_SETTINGS_PF_STREAMLINE")} <b>${ps.penOptions.options.streamline}</b>`,
),
)
.setDesc(fragWithHTML(` How much to streamline the stroke.`))
.setDesc(fragWithHTML(t("PEN_SETTINGS_PF_STREAMLINE_DESC")))
.addSlider((slider) =>
slider
.setLimits(0, 1, 0.05)
.setValue(ps.penOptions.options.streamline)
.onChange((value) => {
this.dirty = true;
slSetting.setName(fragWithHTML(`Streamline <b>${value}</b>`));
this.isDirty = true;
slSetting.setName(
fragWithHTML(
`${t("PEN_SETTINGS_PF_STREAMLINE")} <b>${value}</b>`,
),
);
ps.penOptions.options.streamline = value;
}),
);
new Setting(ce)
.setName("Easing function")
.setDesc(
fragWithHTML(
`An easing function for the tapering effect. For more info <a href="${URLs.EASINGS_NET}" target="_blank">click here</a>`,
),
)
.setName(t("PEN_SETTINGS_EASING"))
.setDesc(fragWithHTML(t("PEN_SETTINGS_EASING_DESC")))
.addDropdown((dropdown) =>
dropdown
.addOptions(EASINGFUNCTIONS)
.setValue(ps.penOptions.options.easing)
.onChange((value) => {
this.dirty = true;
this.isDirty = true;
ps.penOptions.options.easing = value;
}),
);
const spSetting = new Setting(ce)
.setName("Simulate Pressure")
.setDesc("Whether to simulate pressure based on velocity.")
.setName(t("PEN_SETTINGS_SIMULATE_PRESSURE"))
.setDesc(t("PEN_SETTINGS_SIMULATE_PRESSURE_DESC"))
.addDropdown((dropdown) =>
dropdown
.addOption("true", "Always")
.addOption("false", "Never")
.addOption("", "Yes for mouse, No for pen")
.addOption("true", t("PEN_SETTINGS_SIMULATE_PRESSURE_ALWAYS"))
.addOption("false", t("PEN_SETTINGS_SIMULATE_PRESSURE_NEVER"))
.addOption("", t("PEN_SETTINGS_SIMULATE_PRESSURE_MOUSE"))
.setValue(
ps.penOptions.options.simulatePressure === true
? "true"
@@ -688,7 +779,7 @@ export class PenSettingsModal extends Modal {
: "",
)
.onChange((value) => {
this.dirty = true;
this.isDirty = true;
switch (value) {
case "true":
ps.penOptions.options.simulatePressure = true;
@@ -708,15 +799,15 @@ export class PenSettingsModal extends Modal {
showElement(spSetting.settingEl);
}
ce.createEl("h3", { text: "Start" });
ce.createEl("p", { text: "Tapering options for the start of the line." });
ce.createEl("h3", { text: t("PEN_SETTINGS_START_HEADING") });
ce.createEl("p", { text: t("PEN_SETTINGS_START_DESC") });
new Setting(ce)
.setName("Cap Start")
.setDesc("Whether to draw a cap")
.setName(t("PEN_SETTINGS_CAP_START"))
.setDesc(t("PEN_SETTINGS_CAP_DESC"))
.addToggle((toggle) =>
toggle.setValue(ps.penOptions.options.start.cap).onChange((value) => {
this.dirty = true;
this.isDirty = true;
ps.penOptions.options.start.cap = value;
}),
);
@@ -724,12 +815,10 @@ export class PenSettingsModal extends Modal {
const stSetting = new Setting(ce)
.setName(
fragWithHTML(
`Taper: <b>${ps.penOptions.options.start.taper === true ? "true" : ps.penOptions.options.start.taper}</b>`,
`${t("PEN_SETTINGS_TAPER")} <b>${ps.penOptions.options.start.taper === true ? "true" : ps.penOptions.options.start.taper}</b>`,
),
)
.setDesc(
"The distance to taper. If set to true, the taper will be the total length of the stroke.",
)
.setDesc(t("PEN_SETTINGS_TAPER_DESC"))
.addSlider((slider) =>
slider
.setLimits(0, 151, 1)
@@ -739,42 +828,38 @@ export class PenSettingsModal extends Modal {
: ps.penOptions.options.start.taper,
)
.onChange((value) => {
this.dirty = true;
this.isDirty = true;
ps.penOptions.options.start.taper = value === 151 ? true : value;
stSetting.setName(
fragWithHTML(
`Taper: <b>${ps.penOptions.options.start.taper === true ? "true" : ps.penOptions.options.start.taper}</b>`,
`${t("PEN_SETTINGS_TAPER")} <b>${ps.penOptions.options.start.taper === true ? "true" : ps.penOptions.options.start.taper}</b>`,
),
);
}),
);
new Setting(ce)
.setName("Easing function")
.setDesc(
fragWithHTML(
`An easing function for the tapering effect. For more info <a href="${URLs.EASINGS_NET}" target="_blank">click here</a>`,
),
)
.setName(t("PEN_SETTINGS_EASING"))
.setDesc(fragWithHTML(t("PEN_SETTINGS_EASING_DESC")))
.addDropdown((dropdown) =>
dropdown
.addOptions(EASINGFUNCTIONS)
.setValue(ps.penOptions.options.start.easing)
.onChange((value) => {
this.dirty = true;
this.isDirty = true;
ps.penOptions.options.start.easing = value;
}),
);
ce.createEl("h3", { text: "End" });
ce.createEl("p", { text: "Tapering options for the end of the line." });
ce.createEl("h3", { text: t("PEN_SETTINGS_END_HEADING") });
ce.createEl("p", { text: t("PEN_SETTINGS_END_DESC") });
new Setting(ce)
.setName("Cap End")
.setDesc("Whether to draw a cap")
.setName(t("PEN_SETTINGS_CAP_END"))
.setDesc(t("PEN_SETTINGS_CAP_DESC"))
.addToggle((toggle) =>
toggle.setValue(ps.penOptions.options.end.cap).onChange((value) => {
this.dirty = true;
this.isDirty = true;
ps.penOptions.options.end.cap = value;
}),
);
@@ -782,12 +867,10 @@ export class PenSettingsModal extends Modal {
const etSetting = new Setting(ce)
.setName(
fragWithHTML(
`Taper: <b>${ps.penOptions.options.end.taper === true ? "true" : ps.penOptions.options.end.taper}</b>`,
`${t("PEN_SETTINGS_TAPER")} <b>${ps.penOptions.options.end.taper === true ? "true" : ps.penOptions.options.end.taper}</b>`,
),
)
.setDesc(
"The distance to taper. If set to true, the taper will be the total length of the stroke.",
)
.setDesc(t("PEN_SETTINGS_TAPER_DESC"))
.addSlider((slider) =>
slider
.setLimits(0, 151, 1)
@@ -797,31 +880,30 @@ export class PenSettingsModal extends Modal {
: ps.penOptions.options.end.taper,
)
.onChange((value) => {
this.dirty = true;
this.isDirty = true;
ps.penOptions.options.end.taper = value === 151 ? true : value;
etSetting.setName(
fragWithHTML(
`Taper: <b>${ps.penOptions.options.end.taper === true ? "true" : ps.penOptions.options.end.taper}</b>`,
`${t("PEN_SETTINGS_TAPER")} <b>${ps.penOptions.options.end.taper === true ? "true" : ps.penOptions.options.end.taper}</b>`,
),
);
}),
);
new Setting(ce)
.setName("Easing function")
.setDesc(
fragWithHTML(
`An easing function for the tapering effect. For more info <a href="${URLs.EASINGS_NET}" target="_blank">click here</a>`,
),
)
.setName(t("PEN_SETTINGS_EASING"))
.setDesc(fragWithHTML(t("PEN_SETTINGS_EASING_DESC")))
.addDropdown((dropdown) =>
dropdown
.addOptions(EASINGFUNCTIONS)
.setValue(ps.penOptions.options.end.easing)
.onChange((value) => {
this.dirty = true;
this.isDirty = true;
ps.penOptions.options.end.easing = value;
}),
);
// Bottom buttons
this.addActionButtons(ce);
}
}
+2 -2
View File
@@ -781,7 +781,7 @@ export class GenericInputPrompt extends Modal {
}
// Create popup element
const popup = activeDocument.createElement("div");
const popup = activeDocument.createDiv();
popup.addClass("excalidraw-genericInputPrompt-specialCharPopup");
// Position near the button
@@ -809,7 +809,7 @@ export class GenericInputPrompt extends Modal {
// Add character buttons
specialChars.forEach((char) => {
const charButton = activeDocument.createElement("button");
const charButton = activeDocument.createEl("button");
charButton.textContent = char;
charButton.addClass("excalidraw-genericInputPrompt-specialCharButton");
+4 -3
View File
@@ -4,9 +4,10 @@ import { errorlog } from "../../utils/utils";
import { log } from "src/utils/debugHelper";
import { ContentSearcher } from "../components/ContentSearcher";
import { URLs } from "src/constants/safeUrls";
import { mainDocument } from "src/constants/constants";
import { t } from "src/lang/helpers";
declare const mainDocument: Document;
const URL =
URLs.RAW_GITHUBUSERCONTENT_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_MASTER_EA_SCRIPTS_INDEX_NEW_MD;
@@ -55,8 +56,8 @@ export class ScriptInstallPrompt extends Modal {
this.contentDiv.querySelectorAll("a.internal-link").forEach((el) => {
el.removeAttribute("target");
});
} catch (e) {
errorlog({ where: "ScriptInstallPrompt.onOpen", error: e as unknown });
} catch (e: unknown) {
errorlog({ where: "ScriptInstallPrompt.onOpen", error: e });
new Notice(t("SCRIPT_INSTALL_PROMPT_OPEN_ERROR"));
this.close();
}
+89
View File
@@ -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[] = [
@@ -3,7 +3,8 @@ import { t } from "src/lang/helpers";
import { NamedExcalidrawFrameElement } from "src/types/excalidrawElementTypes";
import { ScriptEngine } from "../Scripts";
import ExcalidrawView from "src/view/ExcalidrawView";
import { mainDocument } from "src/constants/constants";
declare const mainDocument: Document;
/**
*
+206 -47
View File
@@ -15,14 +15,9 @@ import {
THEME_FILTER,
FRONTMATTER_KEYS,
getCSSFontDefinition,
mainDocument,
} from "../constants/constants";
import { createSVG } from "src/utils/excalidrawAutomateUtils";
import {
EquationItem,
ExcalidrawData,
getTransclusion,
} from "./ExcalidrawData";
import { ExcalidrawData, getTransclusion } from "./ExcalidrawData";
import { t } from "../lang/helpers";
import { tex2dataURL } from "./LaTeX";
import ExcalidrawPlugin from "../core/main";
@@ -78,8 +73,11 @@ import {
isInstanceOfHTMLImageElement,
isInstanceOfSVGElement,
} from "src/utils/typechecks";
import { strictArrayBuffer } from "src/utils/obsidianUtils";
import { getSafeFrontmatter, strictArrayBuffer } from "src/utils/obsidianUtils";
//declared in rollup.config.mjs
declare const deliberateFetch: (payload: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
declare const mainDocument: Document;
//An ugly workaround for the following situation.
//File A is a markdown file that has an embedded Excalidraw file B
//Later file A is embedded into file B as a Markdown embed
@@ -996,15 +994,10 @@ export class EmbeddedFilesLoader {
);
}
let equationItem;
const equations = excalidrawData.getEquationEntries();
while (!(equationItem = equations.next()).done) {
const eiValue = equationItem.value as [FileId, EquationItem];
if (fileIDWhiteList && !fileIDWhiteList.has(eiValue[0])) {
for (const [id, equation] of excalidrawData.getEquationEntries()) {
if (fileIDWhiteList && !fileIDWhiteList.has(id)) {
continue;
}
const equation = eiValue[1];
const id = eiValue[0];
yield createSafeLoadTask(
async () => {
if (this.terminate) {
@@ -1058,12 +1051,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 +1078,7 @@ export class EmbeddedFilesLoader {
depth,
inFile: null,
hasSVGwithBitmap: false,
elements: result.elements,
elements: result.elements as ExcalidrawElement[],
});
if (this.terminate) {
return;
@@ -1124,7 +1122,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 +1152,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 {
@@ -1249,11 +1247,22 @@ export class EmbeddedFilesLoader {
let viewProps: PDFPageViewProps;
const shouldRetryWithFreshDoc = (e: unknown): boolean => {
const message = `${
typeof e === "object" && e !== null && "message" in e
? String((e as { message?: unknown }).message ?? "")
: String(e ?? "")
}`;
let message = "";
if (e instanceof Error) {
// Standard JS Errors are guaranteed to have a string .message
message = e.message;
} else if (typeof e === "string") {
// If someone threw a raw string
message = e;
} else if (e !== null && typeof e === "object" && "message" in e) {
// If it's a custom object with a message property
const maybeMessage = (e as { message?: unknown }).message;
if (typeof maybeMessage === "string") {
message = maybeMessage;
}
}
return (
message.includes("sendWithPromise") ||
message.includes("WorkerTransport") ||
@@ -1407,8 +1416,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 +1449,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 +1497,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 +1523,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 +1578,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 +1662,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 +1746,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 +1767,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 deliberateFetch(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,
@@ -1765,10 +1924,10 @@ export const generateIdFromFile = async (
id = Array.from(new Uint8Array(hashBuffer))
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("") as FileId;
} catch (error) {
} catch (error: unknown) {
errorlog({
where: "EmbeddedFileLoader.generateIdFromFile",
error: error as unknown,
error: error,
});
id = fileid() as FileId;
}
@@ -1788,7 +1947,7 @@ const replaceBlobWithBase64 = async (
const blobUrl = img.src;
try {
// fetch is the only way to read blob: URLs in browser/Obsidian context.
const response = await fetch(blobUrl);
const response = await deliberateFetch(blobUrl);
const blob = await response.blob();
const base64 = await blobToBase64(blob);
img.src = `data:${blob.type};base64,${base64}`;
+31 -12
View File
@@ -38,7 +38,6 @@ import {
MAX_IMAGE_SIZE,
COLOR_NAMES,
fileid,
GITHUB_RELEASES,
getCommonBoundingBox,
getLineHeight,
getMaximumGroups,
@@ -205,7 +204,7 @@ import { AIRequest, ExcalidrawAISettings } from "src/types/AIUtilTypes";
import { getAspectRatio } from "src/utils/YoutTubeUtils";
import { getPDFCropRect } from "src/utils/PDFUtils";
import { CaptureUpdateActionType } from "@zsviczian/excalidraw/types/element/src";
import { URL_REGISTRY } from "src/constants/safeUrls";
import { URL_REGISTRY, URLs } from "src/constants/safeUrls";
type ExcalidrawAutomateHelpTarget = ((...args: unknown[]) => unknown) | string;
@@ -1432,11 +1431,11 @@ export class ExcalidrawAutomate {
const scene = {
type: "excalidraw",
version: 2,
source: GITHUB_RELEASES + PLUGIN_VERSION,
source: `${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/${PLUGIN_VERSION}`,
elements,
appState: {
...templateAppstate,
theme: templateAppstate.theme ?? this.canvas.theme,
theme: (templateAppstate.theme ?? this.canvas.theme) as string,
viewBackgroundColor:
templateAppstate.viewBackgroundColor ??
this.canvas.viewBackgroundColor,
@@ -3035,14 +3034,11 @@ export class ExcalidrawAutomate {
* @returns {string} The ID of the added text element.
*/
addLabelToLine(lineId: string, label: string): string {
const line = this.elementsDict[lineId] as
| Mutable<ExcalidrawLinearElement>
| undefined;
if (
!line ||
!["arrow", "line"].includes(line.type) ||
line.points.length !== 2
) {
const line = this.elementsDict[lineId];
if (!line || (line.type !== "arrow" && line.type !== "line")) {
return;
}
if (line.points.length !== 2) {
return;
}
@@ -4028,6 +4024,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.
+8 -8
View File
@@ -570,7 +570,7 @@ export class ExcalidrawData {
const saveVersion =
this.scene.source?.split(
URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG,
`${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/`,
)[1] ?? "1.8.16";
const elements = this.scene.elements as Mutable<
@@ -714,13 +714,13 @@ export class ExcalidrawData {
container.boundElements = [
{ id: textEl.id, type: "text" as "text" | "arrow" },
].concat(boundEl);
} catch (e) {
} catch (e: unknown) {
errorlog({
message: "unexpected error in initializeNonInitializedFields",
context: this.initializeNonInitializedFields.bind(
this,
) as unknown,
error: e as unknown,
error: e,
});
}
},
@@ -831,7 +831,7 @@ export class ExcalidrawData {
if (f && f instanceof TFile && f.stat.mtime > file.stat.mtime) {
//the .excalidraw file is newer then the .md file
const d = await this.app.vault.read(f);
this.scene = JSON.parse(d);
this.scene = JSON.parse(d) as ExcalidrawDataScene;
}
}
@@ -870,7 +870,7 @@ export class ExcalidrawData {
`excalidraw.com.<br>🔄 If you're using Obsidian on ` +
"multiple devices, you may proceed now, but please, before opening this " +
"file on your other devices, update Excalidraw on those as well.<br>🔍 More info is available " +
`<a href=${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG_1_9_9}>here</a>.<br>🌐 ` +
`<a href=${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/1.9.9>here</a>.<br>🌐 ` +
`<a href=${URLs.TRANSLATE_GOOGLE_COM}>` +
"Translate</a>.",
);
@@ -1711,7 +1711,7 @@ export class ExcalidrawData {
key: FileId,
name?: string,
) {
const scene = this.scene as SceneDataWithFiles;
const scene = this.scene;
let fname = name;
if (!fname) {
@@ -1766,7 +1766,7 @@ export class ExcalidrawData {
}
private syncCroppedPDFs() {
const scene = this.scene as SceneDataWithFiles;
const scene = this.scene;
const pdfScale = this.plugin.settings.pdfScale;
scene.elements
.filter((el) => el.type === "image" && el.crop && !el.isDeleted)
@@ -1808,7 +1808,7 @@ export class ExcalidrawData {
*/
private async syncFiles(): Promise<boolean> {
let dirty = false;
const scene = this.scene as SceneDataWithFiles;
const scene = this.scene;
//remove files and equations that no longer have a corresponding image element
const images = scene.elements.filter(
+3 -2
View File
@@ -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;
@@ -450,7 +450,8 @@ class ImageCache {
} catch (error) {
console.error(
"unexpected error in getResolvedCacheData",
this.getResolvedCacheData.bind(this),
"ImageCache.getResolvedCacheData",
key_,
error,
);
return undefined;
+6 -5
View File
@@ -19,6 +19,7 @@ import {
stripYamlFrontmatter,
} from "../utils/obsidianUtils";
import { ButtonDefinition, InputPromptOptions } from "src/types/promptTypes";
import { errorlog } from "src/utils/coreUtils";
export type ScriptIconMap = {
[key: string]: { name: string; group: string; svgString: string };
@@ -424,12 +425,12 @@ export class ScriptEngine {
hint,
instructions,
);
} catch (error) {
console.error(
"unexpected error in suggester",
this.suggester.bind(this),
} catch (error: unknown) {
errorlog({
message: "unexpected error in suggester",
where: "ScriptEngine.suggester",
error,
);
});
return undefined;
}
}
+1 -1
View File
@@ -56,7 +56,7 @@ export class FileSuggestionModal extends SuggestionModal<LinkSuggestion> {
});
// Pre-bind the handler
this.handleGetFile = this.getFile.bind(this);
this.handleGetFile = () => this.getFile();
this.inputEl.addEventListener("input", this.handleGetFile);
this.setPlaceholder(t("SELECT_FILE_TO_INSERT"));
@@ -20,7 +20,7 @@ export class FolderSuggestionModal extends SuggestionModal<TFolder> {
this.text = input;
// Pre-bind the handler
this.handleGetFolder = this.getFolder.bind(this);
this.handleGetFolder = () => this.getFolder();
this.inputEl.addEventListener("input", this.handleGetFolder);
}
getFolder() {
+1 -1
View File
@@ -24,7 +24,7 @@ export class PathSuggestionModal extends SuggestionModal<
this.text = input;
// Pre-bind the handler
this.handleGetFile = this.getFile.bind(this);
this.handleGetFile = () => this.getFile();
this.inputEl.addEventListener("input", this.handleGetFile);
}
+7 -11
View File
@@ -3,21 +3,17 @@ import { SuggestModal, Scope } from "obsidian";
export class Suggester<T> {
owner: SuggestModal<T>;
items: T[];
suggestions: HTMLDivElement[];
suggestions: HTMLElement[];
selectedItem: number;
containerEl: HTMLElement;
constructor(owner: SuggestModal<T>, containerEl: HTMLElement, scope: Scope) {
this.containerEl = containerEl;
this.owner = owner;
containerEl.on(
"click",
".suggestion-item",
this.onSuggestionClick.bind(this),
containerEl.on("click", ".suggestion-item", (event, el) =>
this.onSuggestionClick(event, el),
);
containerEl.on(
"mousemove",
".suggestion-item",
this.onSuggestionMouseover.bind(this),
containerEl.on("mousemove", ".suggestion-item", (event, el) =>
this.onSuggestionMouseover(event, el),
);
scope.register([], "ArrowUp", () => {
@@ -49,7 +45,7 @@ export class Suggester<T> {
this.owner.onChooseSuggestion(currentValue, evt);
}
}
onSuggestionClick(event: MouseEvent, el: HTMLDivElement): void {
onSuggestionClick(event: MouseEvent, el: HTMLElement): void {
event.preventDefault();
if (!this.suggestions || !this.suggestions.length) {
return;
@@ -60,7 +56,7 @@ export class Suggester<T> {
this.useSelectedItem(event);
}
onSuggestionMouseover(event: MouseEvent, el: HTMLDivElement): void {
onSuggestionMouseover(event: MouseEvent, el: HTMLElement): void {
if (!this.suggestions || !this.suggestions.length) {
return;
}
+4 -4
View File
@@ -34,9 +34,9 @@ export abstract class SuggestionModal<T> extends FuzzySuggestModal<T> {
this.collisionBoundary = collisionBoundary;
// Pre-bind event handlers
this.handleInput = this.onInputChanged.bind(this);
this.handleFocus = this.onFocus.bind(this);
this.handleBlur = this.close.bind(this);
this.handleInput = () => this.onInputChanged();
this.handleFocus = () => this.onFocus();
this.handleBlur = () => this.close();
this.handleMouseDown = (event: MouseEvent) => {
event.preventDefault();
};
@@ -44,7 +44,7 @@ export abstract class SuggestionModal<T> extends FuzzySuggestModal<T> {
this.suggestEl = createDiv("suggestion-container");
this.contentEl = this.suggestEl.createDiv("suggestion");
this.suggester = new Suggester(this, this.contentEl, this.scope);
this.scope.register([], "Escape", this.onEscape.bind(this));
this.scope.register([], "Escape", () => this.onEscape());
this.inputEl.addEventListener("input", this.handleInput);
this.inputEl.addEventListener("focus", this.handleFocus);
this.inputEl.addEventListener("blur", this.handleBlur);
+6 -3
View File
@@ -25,7 +25,8 @@ const openTTDDatabase = async (): Promise<IDBDatabase | null> => {
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
request.onerror = () =>
reject(request.error || new Error("Failed to open IndexedDB"));
},
).catch((): null => null);
};
@@ -39,7 +40,8 @@ const readChatsFromStore = async (
const request = store.get(TTD_STORE_KEY);
request.onsuccess = () => resolve(request.result as SavedChats | undefined);
request.onerror = () => reject(request.error);
request.onerror = () =>
reject(request.error || new Error("Failed to read from IndexedDB store"));
});
};
@@ -53,7 +55,8 @@ const writeChatsToStore = async (
const request = store.put(chats, TTD_STORE_KEY);
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
request.onerror = () =>
reject(request.error || new Error("Failed to write to IndexedDB store"));
});
};
+2 -1
View File
@@ -1,10 +1,11 @@
import { t } from "src/lang/helpers";
import { escapeRegExp } from "../../utils/utils";
import { htmlToMarkdown, Notice, setIcon } from "obsidian";
import { mainDocument } from "src/constants/constants";
import { setStyle } from "src/utils/styleUtils";
import { isInstanceOfHTMLElement } from "src/utils/typechecks";
declare const mainDocument: Document;
export class ContentSearcher {
private contentDiv: HTMLElement;
private searchBar: HTMLInputElement;
@@ -1,4 +1,4 @@
import { GITHUB_RELEASES } from "src/constants/constants";
import { URLs } from "src/constants/safeUrls";
import { ExcalidrawGenericElement } from "./ExcalidrawElement";
declare const PLUGIN_VERSION: string;
@@ -6,7 +6,7 @@ declare const PLUGIN_VERSION: string;
class ExcalidrawScene {
type = "excalidraw";
version = 2;
source = GITHUB_RELEASES + PLUGIN_VERSION;
source = `${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/${PLUGIN_VERSION}`;
elements: ExcalidrawGenericElement[] = [];
constructor(elements: ExcalidrawGenericElement[] = []) {
+3 -1
View File
@@ -25,7 +25,9 @@ import {
import { getTransformMatrix, transformPoints } from "./transform";
import { pointsOnPath } from "points-on-path";
import { randomId, getWindingOrder } from "./utils";
import { mainDocument, ROUNDNESS } from "../../constants/constants";
import { ROUNDNESS } from "../../constants/constants";
declare const mainDocument: Document;
const SUPPORTED_TAGS = [
"svg",
+1 -1
View File
@@ -42,7 +42,7 @@ export type ImageInfo = {
isHyperLink?: boolean;
hyperlink?: string;
file?: string | TFile;
hasSVGwithBitmap: boolean;
hasSVGwithBitmap?: boolean;
latex?: string;
size?: Size;
colorMap?: ColorMap;
+2
View File
@@ -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;
}
+3
View File
@@ -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;
+1 -1
View File
@@ -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" },
+2 -1
View File
@@ -2,7 +2,6 @@ import { NonDeletedExcalidrawElement } from "@zsviczian/excalidraw/types/element
import {
AUDIO_TYPES,
DEVICE,
mainDocument,
REG_LINKINDEX_INVALIDCHARS,
VIDEO_TYPES,
} from "src/constants/constants";
@@ -17,6 +16,8 @@ import { getLinkParts } from "./sceneDataUtils";
import ExcalidrawView from "src/view/ExcalidrawView";
import { setStyle } from "./styleUtils";
declare const mainDocument: Document;
export const createLeaf = (
view: ExcalidrawView,
): { leaf: WorkspaceLeaf; rootSplit: WorkspaceSplit } => {
+52 -28
View File
@@ -18,7 +18,6 @@ import { normalizePath, TFile } from "obsidian";
import type ExcalidrawView from "src/view/ExcalidrawView";
import {
GITHUB_RELEASES,
getCommonBoundingBox,
IMAGE_TYPES,
restoreElements,
@@ -60,6 +59,7 @@ import { ScriptEngine } from "src/shared/Scripts";
import { ColorMap, FileData } from "src/types/embeddedFileLoaderTypes";
import { ExportSettings } from "src/types/exportUtilTypes";
import type { StrokeWidthKey } from "@zsviczian/excalidraw/types/common/src/constants";
import { URLs } from "src/constants/safeUrls";
declare const PLUGIN_VERSION: string;
@@ -451,7 +451,7 @@ export async function getTemplate(
Object.values(scene.files)
.filter((f: BinaryFileData) => fileIDWhiteList.has(f.id))
.forEach((f: BinaryFileData) => {
files[f.id] = f;
files[f.id as string] = f;
});
} else {
files = scene.files;
@@ -522,7 +522,7 @@ export async function createPNG(
if (template?.files) {
Object.values(template.files).forEach((f: BinaryFileData) => {
if (!f.dataURL.startsWith("http")) {
files[f.id] = f;
files[f.id as string] = f;
}
});
}
@@ -531,10 +531,11 @@ export async function createPNG(
{
type: "excalidraw",
version: 2,
source: GITHUB_RELEASES + PLUGIN_VERSION,
source: `${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/${PLUGIN_VERSION}`,
elements,
appState: {
theme: forceTheme ?? template?.appState?.theme ?? canvasTheme,
theme:
forceTheme ?? template?.appState?.theme ?? canvasTheme ?? "light",
viewBackgroundColor:
template?.appState?.viewBackgroundColor ?? canvasBackgroundColor,
...(template?.appState?.frameRendering
@@ -666,11 +667,12 @@ export async function createSVG(
const files = imagesDict ?? {};
if (template?.files) {
Object.values(template.files).forEach((f: BinaryFileData) => {
files[f.id] = f;
files[f.id as string] = f;
});
}
const theme = forceTheme ?? template?.appState?.theme ?? canvasTheme;
const theme =
forceTheme ?? template?.appState?.theme ?? canvasTheme ?? "light";
const withTheme =
exportSettings?.withTheme ?? plugin.settings.exportWithTheme;
@@ -680,7 +682,7 @@ export async function createSVG(
//createAndOpenDrawing
type: "excalidraw",
version: 2,
source: GITHUB_RELEASES + PLUGIN_VERSION,
source: `${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/${PLUGIN_VERSION}`,
elements: includeInternalLinks
? elements
: sceneRemoveInternalLinks({ elements }),
@@ -881,26 +883,28 @@ export const getTextElementsMatchingQuery = (
return [];
}
return elements.filter(
(el: ExcalidrawElement) =>
el.type === "text" &&
query.some((q) => {
if (exactMatch) {
const text =
el.customData?.text2Path?.text ??
el.rawText.toLowerCase().split("\n")[0].trim();
const m = text.match(/^#*(# .*)/);
if (!m || m.length !== 2) {
return false;
}
return m[1] === q.toLowerCase();
}
return elements.filter((el: ExcalidrawElement) => {
if (el.type !== "text") return false;
const text2PathText = el.customData?.text2Path?.text;
const customText =
typeof text2PathText === "string" ? text2PathText : undefined;
return query.some((q) => {
if (exactMatch) {
const text =
el.customData?.text2Path?.text ??
el.rawText.toLowerCase().replaceAll("\n", " ").trim();
return text.includes(q.toLowerCase()); //to distinguish between "# frame" and "# frame 1" https://github.com/zsviczian/obsidian-excalidraw-plugin/issues/530
}),
);
customText ?? el.rawText.toLowerCase().split("\n")[0].trim();
const m = text.match(/^#*(# .*)/);
if (!m || m.length !== 2) {
return false;
}
return m[1] === q.toLowerCase();
}
const text =
customText ?? el.rawText.toLowerCase().replaceAll("\n", " ").trim();
return text.includes(q.toLowerCase());
});
});
};
/**
@@ -1125,6 +1129,25 @@ export const getStrokeKeyFormLegacyWidth = (
}
};
export const getStrokeWidthKeyByWidth = (
strokeWidth: number,
): StrokeWidthKey | "extraBold" | undefined => {
switch (strokeWidth) {
case 0.25:
return "extraThin";
case 0.5:
return "thin";
case 1:
return "medium";
case 2:
return "bold";
case 4:
return "extraBold";
default:
return undefined;
}
};
// Returns an appState key for the stroke width
// excalidraw.com deprected and removed currentItemStrokeWidth from appState
// but the plugin still supports it to allow custom line width settings for scripts and custom pens
@@ -1136,7 +1159,8 @@ export const getAppStateStrokeWidthEntry = (
legacyStrokeWidth: number,
) => {
if (legacyStrokeWidth !== undefined) {
strokeWidthKey = getStrokeKeyFormLegacyWidth(legacyStrokeWidth);
// Reusing the combined function here
strokeWidthKey = getStrokeWidthKeyByWidth(legacyStrokeWidth);
}
if (!!legacyStrokeWidth && !strokeWidthKey) {
return { currentItemStrokeWidth: legacyStrokeWidth };
+2 -2
View File
@@ -114,10 +114,10 @@ export const insertLaTeXToView = (
}
ea.destroy();
},
(e) => {
(e: unknown) => {
// Promise rejection handler (e.g. user cancelled prompt or Extras plugin is missing)
if (e && e instanceof Error) {
errorlog({ message: "LaTeX Insertion aborted", error: e as unknown });
errorlog({ message: "LaTeX Insertion aborted", error: e });
}
},
);
+2 -1
View File
@@ -8,7 +8,6 @@ import {
CARD_HEIGHT,
getDefaultColorPalette,
DEVICE,
mainDocument,
EXCALIDRAW_PLUGIN,
PLUGIN_ID,
} from "src/constants/constants";
@@ -49,6 +48,8 @@ import { setSanitizedHtml } from "./htmlUtils";
import { URLs } from "src/constants/safeUrls";
import { isInstanceOfHTMLDivElement } from "./typechecks";
declare const mainDocument: Document;
type CommandLinkOptInPlugin = {
settings: {
enableCommandLinks?: boolean;
+5 -2
View File
@@ -16,7 +16,6 @@ import {
DEVICE,
EXCALIDRAW_PLUGIN,
FRONTMATTER_KEYS,
mainDocument,
URLFETCHTIMEOUT,
} from "src/constants/constants";
import { ExcalidrawSettings } from "src/core/settings";
@@ -33,6 +32,7 @@ import { setElementDisplay } from "./htmlUtils";
import { NestedFileMap } from "src/types/utilTypes";
export { splitFolderAndFilename } from "./pathUtils";
declare const mainDocument: Document;
type ImageExtension = keyof typeof IMAGE_MIME_TYPES;
/**
@@ -187,6 +187,9 @@ export const getMimeType = (extension: string): MimeType => {
}
};
//declared in rollup.config.mjs
declare const deliberateFetch: (payload: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
// Using fetch as primary for maximum compatibility with CORS/image endpoints.
// fetch is used here because requestUrl sometimes fails for certain endpoints (e.g. Firebase Storage, see comment below).
// This is a network request, not a vault or blob:app:// read.
@@ -202,7 +205,7 @@ const getFileFromURL = async (
// fetch is used here for broad compatibility with image endpoints, including those that fail with requestUrl.
const response = await Promise.race([
fetch(url, { mode: "no-cors" }), // CORS error cannot be caught
deliberateFetch(url, { mode: "no-cors" }), // CORS error cannot be caught
timeoutPromise,
]);
+8 -3
View File
@@ -19,7 +19,6 @@ import {
DEVICE,
EXCALIDRAW_PLUGIN,
FRONTMATTER_KEYS,
mainDocument,
VIEW_TYPE_EXCALIDRAW,
} from "src/constants/constants";
import { parse, stringify } from "yaml";
@@ -27,6 +26,8 @@ import type ExcalidrawView from "src/view/ExcalidrawView";
import { setStyle } from "./styleUtils";
import { isInstanceOfHTMLBodyElement } from "./typechecks";
declare const mainDocument: Document;
export const getParentOfClass = (
element: Element,
cssClass: string,
@@ -659,12 +660,16 @@ export function stripYamlFrontmatter(text: string): string {
export function strictArrayBuffer(
buffer: ArrayBuffer | SharedArrayBuffer,
): ArrayBuffer {
if (buffer instanceof SharedArrayBuffer) {
// Check if SharedArrayBuffer is defined in the current environment
if (
typeof SharedArrayBuffer !== "undefined" &&
buffer instanceof SharedArrayBuffer
) {
const strictBuffer = new ArrayBuffer(buffer.byteLength);
new Uint8Array(strictBuffer).set(new Uint8Array(buffer));
return strictBuffer;
}
return buffer;
return buffer as ArrayBuffer;
}
// 1. Map your custom 'type' strings to actual TypeScript types
+4 -2
View File
@@ -1,11 +1,13 @@
import { Notice } from "obsidian";
import { DEVICE, mainDocument } from "src/constants/constants";
import { DEVICE } from "src/constants/constants";
import { getEA } from "src/core";
import { t } from "src/lang/helpers";
import ExcalidrawView from "src/view/ExcalidrawView";
import { NormalizedZoomValue } from "@zsviczian/excalidraw/types/excalidraw/types";
import type { NormalizedZoomValue } from "@zsviczian/excalidraw/types/excalidraw/types";
import { hideElement, setStyle, showElement } from "./styleUtils";
declare const mainDocument: Document;
export interface ScreenshotOptions {
zoom: number;
margin: number;
+2 -2
View File
@@ -52,12 +52,12 @@ export const installButton = async (
let decodedURI = source;
try {
decodedURI = decodeURI(source);
} catch (e) {
} catch (e: unknown) {
errorlog({
where:
"ExcalidrawPlugin.registerInstallCodeblockProcessor.codeblockProcessor.onClick",
source,
error: e as unknown,
error: e,
});
}
const fname = decodedURI.substring(decodedURI.lastIndexOf("/") + 1);
+63 -73
View File
@@ -4,6 +4,7 @@ import {
AppState,
BinaryFileData,
BinaryFiles,
NormalizedZoomValue,
} from "@zsviczian/excalidraw/types/excalidraw/types";
import { errorlog, getDataURL } from "./coreUtils";
import {
@@ -33,7 +34,11 @@ import {
} from "./fileUtils";
import { FILENAMEPARTS } from "../types/utilTypes";
import { Mutable } from "@zsviczian/excalidraw/types/common/src/utility-types";
import { getExcalidrawViews, getFileCSSClasses } from "./obsidianUtils";
import {
getExcalidrawViews,
getFileCSSClasses,
getSafeFrontmatter,
} from "./obsidianUtils";
import { cleanBlockRef, cleanSectionHeading } from "./pathUtils";
import { addAppendUpdateCustomData } from "./elementCustomDataUtils";
import { updateElementLinksToObsidianLinks } from "./excalidrawAutomateUtils";
@@ -364,10 +369,7 @@ export async function getSVG<TScene extends SceneForExport>(
try {
let svg: SVGSVGElement;
if (exportSettings.isMask) {
const cropObject = new CropImage(
elements,
files as unknown as ConstructorParameters<typeof CropImage>[1],
);
const cropObject = new CropImage(elements, files);
svg = await cropObject.getCroppedSVG();
cropObject.destroy();
} else {
@@ -426,7 +428,7 @@ export async function getPNG<TScene extends SceneForExport>(
exportSettings: ExportSettings,
padding: number,
scale: number = 1,
overrideFiles?: Record<ExcalidrawElement["id"], BinaryFileData>,
overrideFiles?: BinaryFiles,
): Promise<Blob> {
try {
const baseFiles = scene.files ?? {};
@@ -439,10 +441,7 @@ export async function getPNG<TScene extends SceneForExport>(
);
if (exportSettings.isMask) {
const cropObject = new CropImage(
elements,
files as unknown as ConstructorParameters<typeof CropImage>[1],
);
const cropObject = new CropImage(elements, files);
const blob = await cropObject.getCroppedPNG();
cropObject.destroy();
return blob;
@@ -754,10 +753,14 @@ export function isMaskFile(
const fileCache = plugin.app.metadataCache.getFileCache(file);
if (
fileCache?.frontmatter &&
fileCache.frontmatter[FRONTMATTER_KEYS.mask.name] !== null &&
typeof fileCache.frontmatter[FRONTMATTER_KEYS.mask.name] !== "undefined"
getSafeFrontmatter(fileCache.frontmatter)[FRONTMATTER_KEYS.mask.name] !==
null &&
typeof getSafeFrontmatter(fileCache.frontmatter)[
FRONTMATTER_KEYS.mask.name
] !== "undefined"
) {
return Boolean(fileCache.frontmatter[FRONTMATTER_KEYS.mask.name]);
const safeFrontmatter = getSafeFrontmatter(fileCache.frontmatter);
return Boolean(safeFrontmatter[FRONTMATTER_KEYS.mask.name]);
}
}
return false;
@@ -769,11 +772,12 @@ export function hasExportTheme(
): boolean {
if (file) {
const fileCache = plugin.app.metadataCache.getFileCache(file);
const safeFrontmatter = getSafeFrontmatter(fileCache?.frontmatter);
const exportDarkKey = FRONTMATTER_KEYS["export-dark"].name;
if (
fileCache?.frontmatter &&
fileCache.frontmatter[FRONTMATTER_KEYS["export-dark"].name] !== null &&
typeof fileCache.frontmatter[FRONTMATTER_KEYS["export-dark"].name] !==
"undefined"
safeFrontmatter[exportDarkKey] !== null &&
typeof safeFrontmatter[exportDarkKey] !== "undefined"
) {
return true;
}
@@ -788,15 +792,14 @@ export function getExportTheme(
): string {
if (file) {
const fileCache = plugin.app.metadataCache.getFileCache(file);
const safeFrontmatter = getSafeFrontmatter(fileCache?.frontmatter);
const exportDarkKey = FRONTMATTER_KEYS["export-dark"].name;
if (
fileCache?.frontmatter &&
fileCache.frontmatter[FRONTMATTER_KEYS["export-dark"].name] !== null &&
typeof fileCache.frontmatter[FRONTMATTER_KEYS["export-dark"].name] !==
"undefined"
safeFrontmatter[exportDarkKey] !== null &&
typeof safeFrontmatter[exportDarkKey] !== "undefined"
) {
return fileCache.frontmatter[FRONTMATTER_KEYS["export-dark"].name]
? "dark"
: "light";
return safeFrontmatter[exportDarkKey] ? "dark" : "light";
}
}
return plugin.settings.exportWithTheme ? theme : "light";
@@ -808,15 +811,14 @@ export function shouldEmbedScene(
): boolean {
if (file) {
const fileCache = plugin.app.metadataCache.getFileCache(file);
const safeFrontmatter = getSafeFrontmatter(fileCache?.frontmatter);
const exportEmbedSceneKey = FRONTMATTER_KEYS["export-embed-scene"].name;
if (
fileCache?.frontmatter &&
fileCache.frontmatter[FRONTMATTER_KEYS["export-embed-scene"].name] !==
null &&
typeof fileCache.frontmatter[
FRONTMATTER_KEYS["export-embed-scene"].name
] !== "undefined"
safeFrontmatter[exportEmbedSceneKey] !== null &&
typeof safeFrontmatter[exportEmbedSceneKey] !== "undefined"
) {
return fileCache.frontmatter[FRONTMATTER_KEYS["export-embed-scene"].name];
return safeFrontmatter[exportEmbedSceneKey];
}
}
return plugin.settings.exportEmbedScene;
@@ -828,13 +830,12 @@ export function hasExportBackground(
): boolean {
if (file) {
const fileCache = plugin.app.metadataCache.getFileCache(file);
const safeFrontmatter = getSafeFrontmatter(fileCache?.frontmatter);
const exportTransparentKey = FRONTMATTER_KEYS["export-transparent"].name;
if (
fileCache?.frontmatter &&
fileCache.frontmatter[FRONTMATTER_KEYS["export-transparent"].name] !==
null &&
typeof fileCache.frontmatter[
FRONTMATTER_KEYS["export-transparent"].name
] !== "undefined"
safeFrontmatter[exportTransparentKey] !== null &&
typeof safeFrontmatter[exportTransparentKey] !== "undefined"
) {
return true;
}
@@ -848,17 +849,14 @@ export function getWithBackground(
): boolean {
if (file) {
const fileCache = plugin.app.metadataCache.getFileCache(file);
const safeFrontmatter = getSafeFrontmatter(fileCache?.frontmatter);
const exportTransparentKey = FRONTMATTER_KEYS["export-transparent"].name;
if (
fileCache?.frontmatter &&
fileCache.frontmatter[FRONTMATTER_KEYS["export-transparent"].name] !==
null &&
typeof fileCache.frontmatter[
FRONTMATTER_KEYS["export-transparent"].name
] !== "undefined"
safeFrontmatter[exportTransparentKey] !== null &&
typeof safeFrontmatter[exportTransparentKey] !== "undefined"
) {
return !fileCache.frontmatter[
FRONTMATTER_KEYS["export-transparent"].name
];
return !safeFrontmatter[exportTransparentKey];
}
}
return plugin.settings.exportWithBackground;
@@ -870,17 +868,15 @@ export function getExportInternalLinks(
): boolean {
if (file) {
const fileCache = plugin.app.metadataCache.getFileCache(file);
const safeFrontmatter = getSafeFrontmatter(fileCache?.frontmatter);
const exportInternalLinksKey =
FRONTMATTER_KEYS["export-internal-links"].name;
if (
fileCache?.frontmatter &&
fileCache.frontmatter[FRONTMATTER_KEYS["export-internal-links"].name] !==
null &&
typeof fileCache.frontmatter[
FRONTMATTER_KEYS["export-internal-links"].name
] !== "undefined"
safeFrontmatter[exportInternalLinksKey] !== null &&
typeof safeFrontmatter[exportInternalLinksKey] !== "undefined"
) {
return fileCache.frontmatter[
FRONTMATTER_KEYS["export-internal-links"].name
];
return safeFrontmatter[exportInternalLinksKey];
}
}
return true;
@@ -896,30 +892,26 @@ export function getExportPadding(
return plugin.settings.exportPaddingSVG;
}
const safeFrontmatter = getSafeFrontmatter(fileCache.frontmatter);
const exportPaddingKey = FRONTMATTER_KEYS["export-padding"].name;
if (
fileCache.frontmatter[FRONTMATTER_KEYS["export-padding"].name] !== null &&
typeof fileCache.frontmatter[FRONTMATTER_KEYS["export-padding"].name] !==
"undefined"
safeFrontmatter[exportPaddingKey] !== null &&
typeof safeFrontmatter[exportPaddingKey] !== "undefined"
) {
const val = parseInt(
fileCache.frontmatter[FRONTMATTER_KEYS["export-padding"].name],
);
const val = parseInt(String(safeFrontmatter[exportPaddingKey]));
if (!isNaN(val)) {
return val;
}
}
//deprecated. Retained for backward compatibility
const exportSvgPaddingKey = FRONTMATTER_KEYS["export-svgpadding"].name;
if (
fileCache.frontmatter[FRONTMATTER_KEYS["export-svgpadding"].name] !==
null &&
typeof fileCache.frontmatter[
FRONTMATTER_KEYS["export-svgpadding"].name
] !== "undefined"
safeFrontmatter[exportSvgPaddingKey] !== null &&
typeof safeFrontmatter[exportSvgPaddingKey] !== "undefined"
) {
const val = parseInt(
fileCache.frontmatter[FRONTMATTER_KEYS["export-svgpadding"].name],
);
const val = parseInt(String(safeFrontmatter[exportSvgPaddingKey]));
if (!isNaN(val)) {
return val;
}
@@ -931,25 +923,23 @@ export function getExportPadding(
export function getPNGScale(
plugin: ExcalidrawPlugin,
file: TFile | null,
): number {
): NormalizedZoomValue {
if (file) {
const fileCache = plugin.app.metadataCache.getFileCache(file);
const safeFrontmatter = getSafeFrontmatter(fileCache?.frontmatter);
const exportPngScaleKey = FRONTMATTER_KEYS["export-pngscale"].name;
if (
fileCache?.frontmatter &&
fileCache.frontmatter[FRONTMATTER_KEYS["export-pngscale"].name] !==
null &&
typeof fileCache.frontmatter[FRONTMATTER_KEYS["export-pngscale"].name] !==
"undefined"
safeFrontmatter[exportPngScaleKey] !== null &&
typeof safeFrontmatter[exportPngScaleKey] !== "undefined"
) {
const val = parseFloat(
fileCache.frontmatter[FRONTMATTER_KEYS["export-pngscale"].name],
);
const val = parseFloat(String(safeFrontmatter[exportPngScaleKey]));
if (!isNaN(val) && val > 0) {
return val;
return val as NormalizedZoomValue;
}
}
}
return plugin.settings.pngExportScale;
return plugin.settings.pngExportScale as NormalizedZoomValue;
}
export function isVersionNewerThanOther(
+26 -7
View File
@@ -1,11 +1,17 @@
import { App, FileView, WorkspaceLeaf } from "obsidian";
import { VIEW_TYPE_EXCALIDRAW_LOADING } from "src/constants/constants";
import { DEVICE, VIEW_TYPE_EXCALIDRAW } from "src/constants/constants";
import ExcalidrawPlugin from "src/core/main";
import { t } from "src/lang/helpers";
import { setElementDisplay } from "src/utils/htmlUtils";
import { isUnwantedLeaf, setExcalidrawView } from "src/utils/obsidianUtils";
import { isUnwantedLeaf } from "src/utils/obsidianUtils";
export async function switchToExcalidraw(app: App) {
const leaves = app.workspace.getLeavesOfType(VIEW_TYPE_EXCALIDRAW_LOADING);
const leaves: WorkspaceLeaf[] = [];
app.workspace.iterateAllLeaves((leaf) => {
if (leaf.view instanceof ExcalidrawLoading) {
leaves.push(leaf);
}
});
for (const leaf of leaves) {
await (leaf.view as ExcalidrawLoading)?.switchToExcalidraw();
}
@@ -26,7 +32,20 @@ export class ExcalidrawLoading extends FileView {
public async switchToExcalidraw() {
const prevLeaf = this.app.workspace.getLeaf();
await setExcalidrawView(this.leaf);
const state = this.leaf.view.getState();
// Force a fresh view instance: switching to the same type can be a no-op.
await this.leaf.setViewState({
type: "empty",
state: {},
});
await this.leaf.setViewState({
type: VIEW_TYPE_EXCALIDRAW,
state,
});
if (DEVICE.isDesktop) {
return;
}
await sleep(100); // added this 2026.04.19 after instances where the hack did not seem to work, but wasn't able to reliably reproduce. This timeout does not seem to cause any issues and may help in cases where the hack was not working due to some sort of race condition
const activeLeaf = this.app.workspace.getLeaf();
if (!activeLeaf) {
@@ -42,16 +61,16 @@ export class ExcalidrawLoading extends FileView {
}
getViewType(): string {
return VIEW_TYPE_EXCALIDRAW_LOADING;
return VIEW_TYPE_EXCALIDRAW;
}
getDisplayText() {
return `Loading Excalidraw... ${this.file?.basename ?? ""}`;
return `${t("INITIALIZATION_MESSAGE")} ${this.file?.basename ?? ""}`;
}
private displayLoadingText() {
// Create a div element for displaying the text
const loadingTextEl = this.contentEl.createEl("div", {
const loadingTextEl = this.contentEl.createDiv({
text: this.getDisplayText(),
});
+155 -33
View File
@@ -45,10 +45,8 @@ import {
SCRIPTENGINE_ICON_NAME,
TEXT_DISPLAY_RAW_ICON_NAME,
IMAGE_TYPES,
KEYCODE,
FRONTMATTER_KEYS,
DEVICE,
GITHUB_RELEASES,
EXPORT_IMG_ICON_NAME,
viewportCoordsToSceneCoords,
ERROR_IFRAME_CONVERSION_CANCELED,
@@ -62,7 +60,6 @@ import {
syncInvalidIndices,
VIEW_TYPE_SIDEPANEL,
sceneCoordsToViewportCoords,
mainDocument,
} from "../constants/constants";
import ExcalidrawPlugin from "../core/main";
import { ExcalidrawAutomate } from "../shared/ExcalidrawAutomate";
@@ -279,6 +276,7 @@ const PREVENT_RELOAD_TIMEOUT = 2000;
const RE_TAIL = /^## Drawing\n.*```\n%%$(.*)/ms;
declare const PLUGIN_VERSION: string;
declare const mainDocument: Document;
type SelectedElementWithLink = { id: string; text: string };
type SelectedImage = { id: string; fileId: FileId };
@@ -504,6 +502,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 +1481,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 +1505,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,
@@ -2291,8 +2302,8 @@ export default class ExcalidrawView
private displayLoadingText() {
// Create a div element for displaying the text
const loadingTextEl = this.contentEl.createEl("div", {
text: `Loading Excalidraw... ${this.file?.basename ?? ""}`,
const loadingTextEl = this.contentEl.createDiv({
text: `${t("INITIALIZATION_MESSAGE")} ${this.file?.basename ?? ""}`,
});
// Apply styling to center the text
@@ -3339,10 +3350,10 @@ export default class ExcalidrawView
) {
return;
}
} catch (e) {
} catch (e: unknown) {
errorlog({
where: "ExcalidrawView.setViewData",
error: e as unknown,
error: e,
});
if (
e instanceof Error &&
@@ -3390,8 +3401,9 @@ export default class ExcalidrawView
);
if (!drawingBAK) {
new Notice(
`Error loading drawing:\n${e.message}${
e.message === "Cannot read property 'index' of undefined"
`Error loading drawing:\n${(e as Error).message}${
(e as Error).message ===
"Cannot read property 'index' of undefined"
? "\n'# Drawing' section is likely missing"
: ""
}\n\nTry manually fixing the file or restoring an earlier version from sync history.`,
@@ -3477,10 +3489,10 @@ export default class ExcalidrawView
excalidrawFile: this.file,
view: this,
});
} catch (e) {
} catch (e: unknown) {
errorlog({
where: "ExcalidrawView.setViewData.onFileOpenHook",
error: e as unknown,
error: e,
});
} finally {
tempEA.destroy();
@@ -4255,6 +4267,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;
@@ -5017,7 +5138,7 @@ export default class ExcalidrawView
return {
type: "excalidraw",
version: 2,
source: GITHUB_RELEASES + PLUGIN_VERSION,
source: `${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/${PLUGIN_VERSION}`,
elements: el,
//see also ExcalidrawAutomate async create(
appState: {
@@ -5377,7 +5498,7 @@ export default class ExcalidrawView
if (event.target === this.excalidrawWrapperRef.current) {
return;
} //event should originate from the canvas
if (this.isFullscreen() && event.keyCode === KEYCODE.ESC) {
if (this.isFullscreen() && event.key === "Escape") {
this.exitFullscreen();
}
if (
@@ -5615,7 +5736,7 @@ export default class ExcalidrawView
});
}
if (st.newElement?.type === "freedraw") {
if ((st.newElement as ExcalidrawElement)?.type === "freedraw") {
this.freedrawLastActiveTimestamp = Date.now();
}
if (
@@ -5669,10 +5790,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 +5802,8 @@ export default class ExcalidrawView
) {
this.checkSceneVersion(et);
}
this.triggerSceneChangeHooks(et, st, files);
}
private onLibraryChange(items: LibraryItems) {
@@ -5690,7 +5811,7 @@ export default class ExcalidrawView
const lib = {
type: "excalidrawlib",
version: 2,
source: GITHUB_RELEASES + PLUGIN_VERSION,
source: `${URLs.GITHUB_COM_ZSVICZIAN_OBSIDIAN_EXCALIDRAW_PLUGIN_RELEASES_TAG}/${PLUGIN_VERSION}`,
libraryItems: items,
};
@@ -5853,7 +5974,7 @@ export default class ExcalidrawView
const el = ea.getElement(
imgID,
) as Mutable<ExcalidrawImageElement>;
const fd = ea.imagesDict[el.fileId] as FileData;
const fd = ea.imagesDict[el.fileId];
el.crop = getPDFCropRect({
scale: this.plugin.settings.pdfScale,
link,
@@ -7403,17 +7524,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,
{},
@@ -8019,6 +8140,7 @@ export default class ExcalidrawView
if (!api) {
return false;
}
this.obsidianMenu?.invalidateCustomPenCache();
api.updateScene({
appState: {
customPens: this.plugin.settings.customPens.slice(
+99 -37
View File
@@ -7,7 +7,6 @@ import {
DEVICE,
EXTENDED_EVENT_TYPES,
KEYBOARD_EVENT_TYPES,
mainDocument,
} from "src/constants/constants";
import {
ExcalidrawImperativeAPI,
@@ -25,7 +24,9 @@ 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";
declare const mainDocument: Document;
type PdfViewLike = {
containerEl?: HTMLElement;
viewer?: {
@@ -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);
@@ -813,7 +843,8 @@ function RenderObsidianView({
if (mdPropsRef.current?.lockedReadingMode) {
return;
}
return originalStartEditing.apply(this, args) as unknown;
const result: unknown = originalStartEditing.apply(this, args);
return result;
};
}
@@ -906,8 +937,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 +1214,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 +1245,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 +1258,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 +1282,7 @@ function RenderObsidianView({
isActiveRef.current,
isEditingRef.current,
viewTypeRef.current,
fileRef.current,
],
);
@@ -1323,26 +1368,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 +1422,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;
}
+80 -58
View File
@@ -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,
) {
@@ -141,6 +151,10 @@ export class ObsidianMenu {
);
}
public invalidateCustomPenCache() {
this.activePens = {};
}
private actionCustomPenLabelClick(index: number, pen: PenStyle) {
const now = Date.now();
const dblClick = now - this.clickTimestamp[index] < 500;
@@ -158,11 +172,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 +270,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 +290,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 +306,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 +339,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)" }
: {}),
}}
+30 -33
View File
@@ -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)
+10 -3
View File
@@ -16,7 +16,8 @@ import {
isObsidianThemeDark,
} from "../../utils/obsidianUtils";
import { CustomMutationObserver, DEBUGGING } from "../../utils/debugHelper";
import { mainDocument } from "src/constants/constants";
declare const mainDocument: Document;
interface ObsidianCanvas {
createFileNode: (params: {
@@ -152,13 +153,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;
+2 -2
View File
@@ -147,9 +147,9 @@ export class DropManager {
view: this.view, //the excalidraw view receiving the drop
pointerPosition: this.currentPosition, //the pointer position on canvas at the time of drop
});
} catch (e) {
} catch (e: unknown) {
new Notice("On drop hook error. See console log for details");
errorlog({ where: "ExcalidrawView.onDrop", error: e as unknown });
errorlog({ where: "ExcalidrawView.onDrop", error: e });
return false;
}
} else {
+118 -33
View File
@@ -117,40 +117,14 @@ export class ExcalidrawSidepanelView extends ItemView {
private restorePromise: Promise<void> | null = null;
private leafChangeRef: EventRef | null = null;
private windowMigrationCleanup: (() => void) | null = null;
private restoreRetryTimer: number | null = null;
constructor(
leaf: WorkspaceLeaf,
private plugin: ExcalidrawPlugin,
) {
super(leaf);
(plugin.settings.sidepanelTabs ?? [])
.filter((entry) => !!entry)
.forEach((entry) => {
let scriptName = "";
let title = "";
try {
const parsed = JSON.parse(entry);
scriptName = parsed?.script ?? parsed?.name ?? "";
title = parsed?.title ?? scriptName;
} catch (error) {
console.error(
"unexpected error in parsing sidepanel tab entry",
entry,
error,
);
if (entry.includes("::")) {
const [namePart, ...rest] = entry.split("::");
scriptName = namePart;
title = rest.join("::") || namePart;
} else {
scriptName = entry;
title = entry;
}
}
if (scriptName) {
this.persistedScripts.set(scriptName, { title: title || scriptName });
}
});
this.loadPersistedScriptsFromSettings();
this.readyPromise = new Promise((resolve) => {
this.resolveReady = resolve;
});
@@ -237,6 +211,10 @@ export class ExcalidrawSidepanelView extends ItemView {
*/
protected async onClose() {
await super.onClose();
if (this.restoreRetryTimer !== null) {
window.clearTimeout(this.restoreRetryTimer);
this.restoreRetryTimer = null;
}
if (this.windowMigrationCleanup) {
this.windowMigrationCleanup();
this.windowMigrationCleanup = null;
@@ -349,10 +327,12 @@ export class ExcalidrawSidepanelView extends ItemView {
tab.destroy();
if (this.activeTabId === tab.id) {
this.activeTabId = null;
const next = this.tabs.values().next().value as
| ExcalidrawSidepanelTab
| undefined;
this.setActiveTab(next ?? null);
let nextTab: ExcalidrawSidepanelTab | null = null;
for (const t of this.tabs.values()) {
nextTab = t;
break; // Grab just the first one
}
this.setActiveTab(nextTab);
}
this.updateEmptyStateVisibility();
}
@@ -369,6 +349,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.
*/
@@ -427,11 +430,16 @@ export class ExcalidrawSidepanelView extends ItemView {
return this.restorePromise;
}
this.restorePromise = (async () => {
const restoreReady = await this.awaitRestoreReadiness();
if (!restoreReady) {
this.queueRestoreRetry();
return;
}
this.loadPersistedScriptsFromSettings();
if (!this.persistedScripts.size) {
return;
}
ExcalidrawSidepanelView.restoreSilent = true;
await this.plugin.awaitInit();
try {
for (const [scriptName, meta] of Array.from(
this.persistedScripts.entries(),
@@ -454,6 +462,35 @@ export class ExcalidrawSidepanelView extends ItemView {
return this.restorePromise;
}
/**
* Waits until the minimum prerequisites for sidepanel script restoration are available.
* Sidepanel restoration is independent from Excalidraw view loading.
*/
private async awaitRestoreReadiness(): Promise<boolean> {
let counter = 0;
while (
(!this.plugin.settings || !this.plugin.scriptEngine) &&
counter++ < 200
) {
await sleep(50);
}
return Boolean(this.plugin.settings && this.plugin.scriptEngine);
}
/**
* Re-attempts restore when sidepanel opens before plugin startup prerequisites are ready.
*/
private queueRestoreRetry(): void {
if (this.restoreRetryTimer !== null) {
return;
}
this.restoreRetryTimer = window.setTimeout(() => {
this.restoreRetryTimer = null;
this.restorePromise = null;
void this.restorePersistedTabs();
}, 500);
}
/**
* Re-runs the script backing an existing tab, typically after the script file was updated.
*/
@@ -519,6 +556,54 @@ export class ExcalidrawSidepanelView extends ItemView {
}
}
/**
* Loads persisted sidepanel script descriptors from settings.
* This may run before settings are available, in which case it leaves the map unchanged.
*/
private loadPersistedScriptsFromSettings() {
const sidepanelTabs = this.plugin.settings?.sidepanelTabs;
if (!sidepanelTabs) {
return;
}
this.persistedScripts.clear();
sidepanelTabs
.filter((entry) => !!entry)
.forEach((entry) => {
let scriptName = "";
let title = "";
try {
const parsed: unknown = JSON.parse(entry);
if (parsed && typeof parsed === "object") {
const p = parsed as Record<string, unknown>;
const pScript = typeof p.script === "string" ? p.script : "";
const pName = typeof p.name === "string" ? p.name : "";
const pTitle = typeof p.title === "string" ? p.title : "";
scriptName = pScript || pName || "";
title = pTitle || scriptName;
}
} catch (error) {
console.error(
"unexpected error in parsing sidepanel tab entry",
entry,
error,
);
if (entry.includes("::")) {
const [namePart, ...rest] = entry.split("::");
scriptName = namePart;
title = rest.join("::") || namePart;
} else {
scriptName = entry;
title = entry;
}
}
if (scriptName) {
this.persistedScripts.set(scriptName, { title: title || scriptName });
}
});
}
/**
* Persists current set of script tabs to plugin settings.
*/
+7
View File
@@ -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();
+18 -2
View File
@@ -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;
}
@@ -1077,4 +1077,20 @@ End Obsidian Sheets Plus support
.excalidraw .App-tray-menu {
min-width: calc(6 * var(--default-button-size));
}
.excalidraw-pen-settings-floating-actions {
position: sticky;
bottom: -20px;
margin-bottom: -20px;
padding-bottom: 20px;
padding-top: 15px;
background-color: var(--background-primary);
border-top: 1px solid var(--background-modifier-border);
z-index: 10;
}
.excalidraw-pen-settings-floating-actions .setting-item {
border-top: none;
padding: 0;
}